file_name stringlengths 6 86 | file_path stringlengths 45 249 | content stringlengths 47 6.26M | file_size int64 47 6.26M | language stringclasses 1 value | extension stringclasses 1 value | repo_name stringclasses 767 values | repo_stars int64 8 14.4k | repo_forks int64 0 1.17k | repo_open_issues int64 0 788 | repo_created_at stringclasses 767 values | repo_pushed_at stringclasses 767 values |
|---|---|---|---|---|---|---|---|---|---|---|---|
Functions.java | /FileExtraction/Java_unseen/fgp_AirReceiver/src/main/java/org/phlo/audio/Functions.java | package org.phlo.audio;
public final class Functions {
public static double sinc(double x) {
return Math.sin(x) / x;
}
public static float sinc(float x) {
return (float)Math.sin(x) / x;
}
}
| 201 | Java | .java | fgp/AirReceiver | 170 | 102 | 9 | 2011-04-28T07:17:04Z | 2020-10-13T10:13:16Z |
SampleBufferLayout.java | /FileExtraction/Java_unseen/fgp_AirReceiver/src/main/java/org/phlo/audio/SampleBufferLayout.java | /*
* This file is part of AirReceiver.
*
* AirReceiver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* AirReceiver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with AirReceiver. If not, see <http://www.gnu.org/licenses/>.
*/
package org.phlo.audio;
/**
* Describes the layout of the samples in a buffer.
* <p>
* Serves as a factory for {@link SampleIndexer} instances
* which provide methods to convert separate channel and
* sample indices into a combined sample index.
*/
public enum SampleBufferLayout {
Interleaved {
@Override
public final SampleIndexer getIndexer(final SampleDimensions bufferDimensions, final SampleRange indexedRange) {
return new SampleIndexer() {
@Override public int getSampleIndex(final int channel, final int sample) {
return (indexedRange.offset.sample + sample) * bufferDimensions.channels + indexedRange.offset.channel + channel;
}
@Override
public SampleDimensions getDimensions() {
return indexedRange.size;
}
@Override
public SampleIndexer slice(SampleOffset offset, SampleDimensions dimensions) {
return getIndexer(bufferDimensions, indexedRange.slice(offset, dimensions));
}
@Override
public SampleIndexer slice(SampleRange range) {
return getIndexer(bufferDimensions, indexedRange.slice(range));
}
};
}
},
Banded {
@Override
public final SampleIndexer getIndexer(final SampleDimensions bufferDimensions, final SampleRange indexedRange) {
return new SampleIndexer() {
@Override public int getSampleIndex(final int channel, final int sample) {
return (indexedRange.offset.channel + channel) * bufferDimensions.samples + indexedRange.offset.sample + sample;
}
@Override
public SampleDimensions getDimensions() {
return indexedRange.size;
}
@Override
public SampleIndexer slice(SampleOffset offset, SampleDimensions dimensions) {
return getIndexer(bufferDimensions, indexedRange.slice(offset, dimensions));
}
@Override
public SampleIndexer slice(SampleRange range) {
return getIndexer(bufferDimensions, indexedRange.slice(range));
}
};
}
};
/**
* Returns a {@link SampleIndexer} which indices the sample in the
* given {@code indexedRange} inside a buffer with the given
* {@code bufferDimensions}.
*
* @param bufferDimensions The buffer's dimensions
* @param indexedRange The range to index
* @return Instance of {@link SampleIndexer}
*/
public abstract SampleIndexer getIndexer(SampleDimensions bufferDimensions, SampleRange indexedRange);
/**
* Returns a {@link SampleIndexer} which indices the sample inside a
* buffer with the given {@code bufferDimensions}.
*
* @param bufferDimensions The buffer's dimensions
* @return Instance of {@link SampleIndexer}
*/
public final SampleIndexer getIndexer(final SampleDimensions dims) {
return getIndexer(dims, new SampleRange(SampleOffset.Zero, dims));
}
/**
* Returns a {@link SampleIndexer} which indices the sample inside a
* buffer with the given {@code bufferDimensions} starting at
* {@code offset}
*
* @param bufferDimensions The buffer's dimensions
* @param offset The offset at which the indices start
* @return Instance of {@link SampleIndexer}
*/
public final SampleIndexer getIndexer(final SampleDimensions dims, final SampleOffset offset) {
dims.assertContains(offset);
return getIndexer(dims, new SampleRange(offset, dims.reduce(offset.channel, offset.sample)));
}
}
| 3,957 | Java | .java | fgp/AirReceiver | 170 | 102 | 9 | 2011-04-28T07:17:04Z | 2020-10-13T10:13:16Z |
SampleClock.java | /FileExtraction/Java_unseen/fgp_AirReceiver/src/main/java/org/phlo/audio/SampleClock.java | /*
* This file is part of AirReceiver.
*
* AirReceiver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* AirReceiver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with AirReceiver. If not, see <http://www.gnu.org/licenses/>.
*/
package org.phlo.audio;
public interface SampleClock {
public double getNowTime();
public double getNextTime();
public double getSampleRate();
}
| 840 | Java | .java | fgp/AirReceiver | 170 | 102 | 9 | 2011-04-28T07:17:04Z | 2020-10-13T10:13:16Z |
SampleRange.java | /FileExtraction/Java_unseen/fgp_AirReceiver/src/main/java/org/phlo/audio/SampleRange.java | /*
* This file is part of AirReceiver.
*
* AirReceiver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* AirReceiver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with AirReceiver. If not, see <http://www.gnu.org/licenses/>.
*/
package org.phlo.audio;
public class SampleRange {
public final SampleOffset offset;
public final SampleDimensions size;
public SampleRange(final SampleOffset _offset, final SampleDimensions _size) {
offset = _offset;
size = _size;
}
public SampleRange(final SampleDimensions _size) {
offset = SampleOffset.Zero;
size = _size;
}
public SampleRange slice(SampleOffset _offset, SampleDimensions _dimensions) {
if (_offset == null)
_offset = SampleOffset.Zero;
if (_dimensions == null)
_dimensions = size.reduce(_offset.channel, _offset.sample);
size.assertContains(_offset, _dimensions);
return new SampleRange(offset.add(_offset), _dimensions);
}
public SampleRange slice(SampleRange _range) {
return slice(_range.offset, _range.size);
}
@Override
public String toString() {
return
"[" +
offset.channel + "..." + (offset.channel + size.channels) + ";" +
offset.sample + "..." + (offset.sample + size.samples) +
"]";
}
}
| 1,675 | Java | .java | fgp/AirReceiver | 170 | 102 | 9 | 2011-04-28T07:17:04Z | 2020-10-13T10:13:16Z |
SampleAccessor.java | /FileExtraction/Java_unseen/fgp_AirReceiver/src/main/java/org/phlo/audio/SampleAccessor.java | /*
* This file is part of AirReceiver.
*
* AirReceiver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* AirReceiver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with AirReceiver. If not, see <http://www.gnu.org/licenses/>.
*/
package org.phlo.audio;
/**
* Provides access to samples in a buffer via
* their absolute position in the buffer.
* <p>
* The caller is required to know the layout
* of the samples, since the methods in this
* interface don't allow specifying the
* channel and sample index separately. For
* this reason, it is usually preferable to
* use a {@link SampleIndexedAccessor} instance
* instead.
*
* @see {@link SampleIndexedAccessor}
*/
public interface SampleAccessor {
/**
* Return the value of the sample {@code index}
* bytes into the buffer
*/
float getSample(int index);
/**
* Sets the value of the sample {code index}
* bytes into the buffer.
*/
void setSample(int index, float value);
}
| 1,411 | Java | .java | fgp/AirReceiver | 170 | 102 | 9 | 2011-04-28T07:17:04Z | 2020-10-13T10:13:16Z |
Signedness.java | /FileExtraction/Java_unseen/fgp_AirReceiver/src/main/java/org/phlo/audio/Signedness.java | /*
* This file is part of AirReceiver.
*
* AirReceiver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* AirReceiver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with AirReceiver. If not, see <http://www.gnu.org/licenses/>.
*/
package org.phlo.audio;
public enum Signedness {
Signed {
@Override public final int intToSignedInt(final int v) { return v; }
@Override public final short shortToSignedShort(final short v) { return v; }
@Override public final byte byteToSignedByte(final byte v) { return v; }
@Override public final int intToUnsignedInt(final int v) { return v ^ 0x80000000; }
@Override public final short shortToUnsignedShort(final short v) { return (short)((int)v - (int)Short.MIN_VALUE); }
@Override public final byte byteToUnsignedByte(final byte v) { return (byte)((int)v - (int)Byte.MIN_VALUE); }
@Override public final int intFromSignedInt(final int v) { return v; }
@Override public final short shortFromSignedShort(final short v) { return v; }
@Override public final byte byteFromSignedByte(final byte v) { return v; }
@Override public final int intFromUnsignedInt(final int v) { return Unsigned.intToSignedInt(v); }
@Override public final short shortFromUnsignedShort(final short v) { return Unsigned.shortToSignedShort(v); }
@Override public final byte byteFromUnsignedByte(final byte v) { return Unsigned.byteToSignedByte(v); }
@Override public final float intToFloat(final int v) { return v; }
@Override public final float shortToFloat(final short v) { return v; }
@Override public final float byteToFloat(final byte v) { return v; }
@Override public final int intFromFloat(final float v) { return (int)v; }
@Override public final short shortFromFloat(final float v) { return (short)Math.max(Short.MIN_VALUE, Math.min((int)v, Short.MAX_VALUE)); }
@Override public final byte byteFromFloat(final float v) { return (byte)Math.max(Byte.MIN_VALUE, Math.min((int)v, Byte.MAX_VALUE)); }
},
Unsigned {
@Override public final int intToSignedInt(final int v) { return v ^ Integer.MIN_VALUE; }
@Override public final short shortToSignedShort(final short v) { return (short)((int)v + (int)Short.MIN_VALUE); }
@Override public final byte byteToSignedByte(final byte v) { return (byte)((int)v + (int)Byte.MIN_VALUE); }
@Override public final int intToUnsignedInt(final int v) { return v; }
@Override public final short shortToUnsignedShort(final short v) { return v; }
@Override public final byte byteToUnsignedByte(final byte v) { return v; }
@Override public final int intFromSignedInt(final int v) { return Signed.intToUnsignedInt(v); }
@Override public final short shortFromSignedShort(final short v) { return Signed.shortToUnsignedShort(v); }
@Override public final byte byteFromSignedByte(final byte v) { return Signed.byteToUnsignedByte(v); }
@Override public final int intFromUnsignedInt(final int v) { return v; }
@Override public final short shortFromUnsignedShort(final short v) { return v; }
@Override public final byte byteFromUnsignedByte(final byte v) { return v; }
@Override public final float intToFloat(final int v) { return Signed.intToFloat(intToSignedInt(v)) - (float)Integer.MIN_VALUE; }
@Override public final float shortToFloat(final short v) { return Signed.shortToFloat(shortToSignedShort(v)) - (float)Short.MIN_VALUE; }
@Override public final float byteToFloat(final byte v) { return Signed.byteToFloat(byteToSignedByte(v)) - (float)Byte.MIN_VALUE; }
@Override public final int intFromFloat(final float v) { return intFromSignedInt(Signed.intFromFloat(v + (float)Integer.MIN_VALUE)); }
@Override public final short shortFromFloat(final float v) { return shortFromSignedShort(Signed.shortFromFloat(v + (float)Short.MIN_VALUE)); }
@Override public final byte byteFromFloat(final float v) { return byteFromSignedByte(Signed.byteFromFloat(v + (float)Byte.MIN_VALUE)); }
};
public final float IntMin = intToFloat(intFromSignedInt(Integer.MIN_VALUE));
public final float IntMax = intToFloat(intFromSignedInt(Integer.MAX_VALUE));
public final float IntRange = IntMax - IntMin;
public final float IntBias = 0.5f * IntMin + 0.5f * IntMax;
public final float ShortMin = shortToFloat(shortFromSignedShort(Short.MIN_VALUE));
public final float ShortMax = shortToFloat(shortFromSignedShort(Short.MAX_VALUE));
public final float ShortRange = ShortMax - ShortMin;
public final float ShortBias = 0.5f * ShortMin + 0.5f * ShortMax;
public final float ByteMin = byteToFloat(byteFromSignedByte(Byte.MIN_VALUE));
public final float ByteMax = byteToFloat(byteFromSignedByte(Byte.MAX_VALUE));
public final float ByteRange = ByteMax - ByteMin;
public final float ByteBias = 0.5f * ByteMin + 0.5f * ByteMax;
public abstract int intToUnsignedInt(int v);
public abstract short shortToUnsignedShort(short v);
public abstract byte byteToUnsignedByte(byte v);
public abstract int intToSignedInt(int v);
public abstract short shortToSignedShort(short v);
public abstract byte byteToSignedByte(byte v);
public abstract int intFromUnsignedInt(int v);
public abstract short shortFromUnsignedShort(short v);
public abstract byte byteFromUnsignedByte(byte v);
public abstract int intFromSignedInt(int v);
public abstract short shortFromSignedShort(short v);
public abstract byte byteFromSignedByte(byte v);
public abstract float intToFloat(int v);
public abstract float shortToFloat(short v);
public abstract float byteToFloat(byte v);
public abstract int intFromFloat(float v);
public abstract short shortFromFloat(float v);
public abstract byte byteFromFloat(float v);
public final float intToNormalizedFloat(final int v) {
return (intToFloat(v) - IntBias) * 2.0f / IntRange;
}
public final float shortToNormalizedFloat(final short v) {
return (shortToFloat(v) - ShortBias) * 2.0f / ShortRange;
}
public final float byteToNormalizedFloat(final byte v) {
return (byteToFloat(v) - ByteBias) * 2.0f / ByteRange;
}
public final int intFromNormalizedFloat(final float v) {
return intFromFloat((v * IntRange / 2.0f) + IntBias);
}
public final short shortFromNormalizedFloat(final float v) {
return shortFromFloat((v * ShortRange / 2.0f) + ShortBias);
}
public final byte byteFromNormalizedFloat(final float v) {
return byteFromFloat((v * ByteRange / 2.0f) + ByteBias);
}
}
| 6,789 | Java | .java | fgp/AirReceiver | 170 | 102 | 9 | 2011-04-28T07:17:04Z | 2020-10-13T10:13:16Z |
Taylor.java | /FileExtraction/Java_unseen/fgp_AirReceiver/src/main/java/org/phlo/audio/Taylor.java | package org.phlo.audio;
public final class Taylor {
public interface Coefficients {
public double coefficient(int power);
}
public static double taylor(double x, Coefficients source) {
if ((x >= 1.0) || (x <= -1.0))
throw new IllegalArgumentException("x must be strictly larger than -1.0 and strictly smaller than 1.0");
double result = 0.0;
double xnPrevious = 0.0;
double xn = 1.0;
int n = 0;
while (xn != xnPrevious) {
result += source.coefficient(n) * xn;
n += 1;
xnPrevious = xn;
xn *= x;
}
return result;
}
public static final Coefficients SincCoefficients = new Coefficients() {
@Override
public double coefficient(int power) {
if ((power % 2) != 0)
return 0.0;
double coeff = ((power/2) % 2 == 0) ? 1.0 : -1.0;
for(int i=1; i <= (power + 1); ++i)
coeff /= (double)i;
return coeff;
}
};
public static double sinc(double x) {
return taylor(x, SincCoefficients);
}
}
| 962 | Java | .java | fgp/AirReceiver | 170 | 102 | 9 | 2011-04-28T07:17:04Z | 2020-10-13T10:13:16Z |
SampleByteBufferFormat.java | /FileExtraction/Java_unseen/fgp_AirReceiver/src/main/java/org/phlo/audio/SampleByteBufferFormat.java | /*
* This file is part of AirReceiver.
*
* AirReceiver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* AirReceiver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with AirReceiver. If not, see <http://www.gnu.org/licenses/>.
*/
package org.phlo.audio;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import javax.sound.sampled.*;
/**
* Described to format of a byte-based sample buffer
* (usually a {@link ByteBuffer}).
* <p>
* Used as a factory for {SampleIndexedAccessor} instances
* which provide access to the buffer's samples as
* float values indexed by their channel and sample
* index.
*/
public final class SampleByteBufferFormat {
/**
* The buffer's layout
*/
public final SampleBufferLayout layout;
/**
* The buffer's byte order
*/
public final ByteOrder byteOrder;
/**
* The individual sample's format
*/
public final SampleByteFormat sampleFormat;
public SampleByteBufferFormat(SampleBufferLayout _layout, ByteOrder _byteOrder, SampleByteFormat _sampleFormat) {
layout = _layout;
byteOrder = _byteOrder;
sampleFormat = _sampleFormat;
}
public SampleByteBufferFormat(AudioFormat audioFormat) {
this(
SampleBufferLayout.Interleaved,
audioFormat.isBigEndian() ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN,
SampleByteFormat.fromAudioFormat(audioFormat)
);
}
public ByteBuffer allocateBuffer(SampleDimensions dimensions) {
ByteBuffer buffer = ByteBuffer.allocate(sampleFormat.getSizeBytes((dimensions)));
buffer.order(byteOrder);
return buffer;
}
public ByteBuffer wrapBytes(byte[] bytes) {
ByteBuffer buffer = ByteBuffer.wrap(bytes);
buffer.order(byteOrder);
return buffer;
}
public SampleIndexedAccessor getAccessor(final ByteBuffer buffer, final SampleDimensions bufferDimensions, final SampleRange range) {
final ByteBuffer bufferWithByteOrder = buffer.duplicate();
bufferWithByteOrder.order(byteOrder);
final SampleIndexer sampleIndexer = layout.getIndexer(bufferDimensions, range);
final SampleAccessor sampleAccessor = sampleFormat.getAccessor(bufferWithByteOrder);
return new SampleIndexedAccessor() {
@Override
public float getSample(int channel, int sample) {
return sampleAccessor.getSample(sampleIndexer.getSampleIndex(channel, sample));
}
@Override
public void setSample(int channel, int sample, float value) {
sampleAccessor.setSample(sampleIndexer.getSampleIndex(channel, sample), value);
}
@Override
public SampleDimensions getDimensions() {
return range.size;
}
@Override
public SampleIndexedAccessor slice(SampleOffset offset, SampleDimensions dimensions) {
return getAccessor(buffer, bufferDimensions, range.slice(offset, dimensions));
}
@Override
public SampleIndexedAccessor slice(SampleRange range) {
return getAccessor(buffer, bufferDimensions, range.slice(range));
}
};
}
public SampleIndexedAccessor getAccessor(final ByteBuffer buffer, final SampleDimensions bufferDimensions, final SampleOffset offset) {
return getAccessor(buffer, bufferDimensions, new SampleRange(offset, bufferDimensions.reduce(offset.channel, offset.sample)));
}
public SampleIndexedAccessor getAccessor(final ByteBuffer buffer, final SampleDimensions bufferDimensions) {
return getAccessor(buffer, bufferDimensions, new SampleRange(SampleOffset.Zero, bufferDimensions));
}
}
| 3,830 | Java | .java | fgp/AirReceiver | 170 | 102 | 9 | 2011-04-28T07:17:04Z | 2020-10-13T10:13:16Z |
JavaSoundSink.java | /FileExtraction/Java_unseen/fgp_AirReceiver/src/main/java/org/phlo/audio/JavaSoundSink.java | /*
* This file is part of AirReceiver.
*
* AirReceiver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* AirReceiver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with AirReceiver. If not, see <http://www.gnu.org/licenses/>.
*/
package org.phlo.audio;
import java.nio.ByteBuffer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sound.sampled.*;
public class JavaSoundSink implements SampleClock {
private static Logger s_logger = Logger.getLogger(JavaSoundSink.class.getName());
private static final double TimeOffset = 2208988800.0;
private static final int BytesPerSample = 2;
private static final double BufferSizeSeconds = 0.2;
private final double m_sampleRate;
private final int m_channels;
private final SampleSource m_sampleSource;
private final AudioFormat m_javaSoundAudioFormat;
private final SourceDataLine m_javaSoundLine;
private final FloatControl m_javaSoundLineControlMasterGain;
private final float m_javaSoundLineControlMasterGainMin;
private final float m_javaSoundLineControlMasterGainMax;
private final JavaSoundLineWriter m_javaSoundLineWriter;
private final double m_lineStartTime;
private volatile double m_startTime;
private float m_currentGain;
private float m_requestedGain;
private final class JavaSoundLineWriter extends Thread {
/**
* Latch used to pass the line start time to the outer class'es constructor.
*/
final Latch<Double> lineStartTimeLatch = new Latch<Double>(JavaSoundSink.this);
/**
* Latch used to signal that the outer class'es constructor has set
* the line start time. Uses the outer instance as monitor to make sure
* that we actually see the updated instance variable.
*
*/
final Latch<Void> startTimeSetLatch = new Latch<Void>(JavaSoundSink.this);
/**
* Latch used to signal that the inner class'es run() method has initialized
* the line end time. Uses the inner instance as monitor to make sure that
* we actually see the updated instance variable.
*/
final Latch<Void> endTimeSetLatch = new Latch<Void>(JavaSoundSink.this);
public volatile boolean exit = false;
private volatile double m_lineEndTime;
private final float[] m_lineEndSample = new float[m_channels];
private final SampleByteBufferFormat m_bufferFormat = new SampleByteBufferFormat(m_javaSoundAudioFormat);
private final SampleDimensions m_bufferDimensions =
m_bufferFormat.sampleFormat.getDimensionsFromChannelsAndByteSize(
m_channels,
m_javaSoundLine.getBufferSize()
);
private final ByteBuffer m_buffer = m_bufferFormat.allocateBuffer(m_bufferDimensions);
private final SampleBuffer m_silence = new SampleBuffer(m_bufferDimensions);
@Override
public void run() {
try {
setPriority(MAX_PRIORITY);
/* Arrange for the current time to be offered via the
* lineStartTimeLatch one the line actually starts.
* The outer class'es constructor waits for this, sets up
* the m_lineStartTime instance variable, and offers
* on the startTimeSetLatch afterwards.
*/
{
m_javaSoundLine.addLineListener(new LineListener() {
@Override public void update(LineEvent evt) {
if (LineEvent.Type.START.equals(evt.getType())) {
/* Offer the current system time */
try {
lineStartTimeLatch.offer(TimeOffset + 1e-3 * (double)System.currentTimeMillis());
}
catch (InterruptedException e) {
s_logger.log(Level.WARNING, "Java Sound line writer was interrupted during startup", e);
throw new RuntimeException(e.getMessage(), e);
}
/* We're not interested in further notifications */
m_javaSoundLine.removeLineListener(this);
}
}
});
}
/* Start the line. It probably won't actuall start until we write some data */
m_javaSoundLine.start();
/* Write some silence to the line. This is supposed to start the line.
* Note that we *must* *not* call advanceEndTime here, since the end
* time hasn't yet been initialized. Instead, we remember the number of
* sample we wrote and call advanceEndTime() after the outer class
* signals us that lineStartTime has been set
*/
{
final int silenceWritten = write(m_silence);
/* Wait for the outer class'es constructor to initialize m_lineStartTime
* and use that to initialize the line end time
*/
startTimeSetLatch.consume();
synchronized(this) {
m_lineEndTime = m_lineStartTime;
advanceEndTime(silenceWritten);
}
endTimeSetLatch.offer(null);
}
/* We're now up and running */
boolean lineIsMuted = false;
boolean lineIsPaused = true;
while (!exit) {
/* Check whether the line's supposed to be paused
* If it is, we mute the line, otherwise we un-mute
*/
final boolean lineShouldPause = m_startTime > m_lineEndTime;
if (lineIsPaused != lineShouldPause) {
if (lineShouldPause) {
mute();
lineIsPaused = true;
s_logger.log(Level.INFO, "Audio output paused at " + m_lineEndTime);
}
else {
unmute();
lineIsPaused = false;
s_logger.log(Level.INFO, "Audio output resumed at " + m_lineEndTime);
}
}
/* Get a buffer to write from the sample source. If it
* doesn't provide one, we mute the line, otherwise we un-mute,
* similar to the paused handling above. In fact, these states
* are only kept separately for the sake of the log messages
*/
final SampleBuffer sampleSourceBuffer;
if (lineIsPaused) {
sampleSourceBuffer = null;
}
else {
sampleSourceBuffer = m_sampleSource.getSampleBuffer(m_lineEndTime);
/* If the source provides no data, we mute the line.
* Once it resumed, we unmute again
*/
if ((sampleSourceBuffer == null) != lineIsMuted) {
if (sampleSourceBuffer != null) {
unmute();
lineIsMuted = false;
s_logger.log(Level.WARNING, "Audio sample source resumed providing samples at " + m_lineEndTime + ", un-muted line");
}
else {
mute();
lineIsMuted = true;
s_logger.log(Level.WARNING, "Audio sample source stopped providing samples at " + m_lineEndTime + ", muted line");
}
}
}
/* Compute the number of silence samples to insert before
* the sample source buffer (in case of a gap, pause or
* under-run) and the number of samples to skip from that
* buffer (in case of an overlap)
*/
final int silenceSamples;
final int skipSamples;
if (sampleSourceBuffer != null) {
silenceSamples = (int)Math.round(Math.min(Math.max(
0.0,
(sampleSourceBuffer.getTimeStamp() - m_lineEndTime) * m_sampleRate),
(double)m_silence.getDimensions().samples
));
skipSamples = (int)Math.round(Math.min(Math.max(
0.0,
(m_lineEndTime - sampleSourceBuffer.getTimeStamp()) * m_sampleRate),
(double)sampleSourceBuffer.getDimensions().samples
));
}
else {
silenceSamples = (int)Math.ceil(Math.min(
(m_startTime - m_lineEndTime) * m_sampleRate,
(double)m_silence.getDimensions().samples
));
skipSamples = -1;
}
/* Write silence samples */
if (silenceSamples > 0)
advanceEndTime(write(repeatLastSample(silenceSamples)));
/* Write sample source samples */
if (sampleSourceBuffer != null) {
if (skipSamples >= sampleSourceBuffer.getDimensions().samples) {
s_logger.warning("Audio output overlaps " + skipSamples + " samples, ignored buffer");
}
else if (silenceSamples >= sampleSourceBuffer.getDimensions().samples) {
s_logger.warning("Audio output has gap of " + silenceSamples + " samples, ignored buffer");
}
else {
if (skipSamples > 0)
s_logger.warning("Audio output overlaps " + skipSamples + " samples, skipped samples");
if (silenceSamples > 0)
s_logger.warning("Audio output has gap of " + silenceSamples + " samples, filled with silence");
advanceEndTime(write(sampleSourceBuffer.slice(
new SampleOffset(0, skipSamples),
sampleSourceBuffer.getDimensions().reduce(0, skipSamples)
)));
}
}
} /* while (!exit)
/* Exiting */
/* Write some silence and mute the line to prevent
* it from emitting noise while it's closing
*/
advanceEndTime(write(repeatLastSample(m_silence.getDimensions().samples)));
mute();
m_javaSoundLine.stop();
}
catch (InterruptedException e) {
/* Done */
}
}
private SampleBuffer repeatLastSample(int samples) {
SampleBuffer result = m_silence.slice(
SampleOffset.Zero,
new SampleDimensions(m_silence.getDimensions().channels, samples)
);
for(int c=0; c < result.getDimensions().channels; ++c)
for(int s=0; s < result.getDimensions().samples; ++s)
result.setSample(c, s, m_lineEndSample[c]);
return result;
}
private int write(SampleBuffer sampleBuffer) {
int totalWrittenSamples = 0;
while (sampleBuffer.getDimensions().samples > 0) {
final SampleDimensions writeDimensions =
sampleBuffer.getDimensions().intersect(m_bufferDimensions);
sampleBuffer
.slice(SampleOffset.Zero, writeDimensions)
.copyTo(m_buffer, m_bufferDimensions, m_bufferFormat);
final int writtenBytes = m_javaSoundLine.write(
m_buffer.array(),
m_buffer.arrayOffset(),
m_bufferFormat.sampleFormat.getSizeBytes(writeDimensions)
);
final SampleDimensions writtenDimensions =
m_bufferFormat.sampleFormat.getDimensionsFromChannelsAndByteSize(
m_bufferDimensions.channels,
writtenBytes
);
if (writtenDimensions.samples > 0) {
for(int c=0; c < writtenDimensions.channels; ++c)
m_lineEndSample[c] = sampleBuffer.getSample(c, writtenDimensions.samples-1);
}
totalWrittenSamples += writtenDimensions.samples;
if (writeDimensions.samples < writtenDimensions.samples)
break;
sampleBuffer = sampleBuffer.slice(new SampleOffset(
0,
writtenDimensions.samples
), null);
}
return totalWrittenSamples;
}
private void advanceEndTime(int samples) {
m_lineEndTime += (double)samples / m_sampleRate;
}
public double getEndTime() {
return m_lineEndTime;
}
}
public JavaSoundSink(final double sampleRate, int channels, SampleSource sampleSource)
throws InterruptedException
{
/* Initialize instance variables */
m_sampleRate = sampleRate;
m_channels = channels;
m_sampleSource = sampleSource;
m_startTime = Double.MAX_VALUE;
/* Create and open JavaSound SourceDataLine */
final int bufferSizeBytes = (int)Math.round(BufferSizeSeconds * m_sampleRate * (double)channels * (double)BytesPerSample);
m_javaSoundAudioFormat = new AudioFormat(
(float)m_sampleRate,
BytesPerSample * 8,
channels,
true,
true
);
final DataLine.Info lineInfo = new DataLine.Info(
SourceDataLine.class,
m_javaSoundAudioFormat,
bufferSizeBytes
);
try {
m_javaSoundLine = (SourceDataLine)AudioSystem.getLine(lineInfo);
m_javaSoundLine.open(m_javaSoundAudioFormat, bufferSizeBytes);
} catch (LineUnavailableException e) {
throw new RuntimeException(e.getMessage(), e);
}
/* Get Master Gain Control for Java Sound SourceDataLine */
if (m_javaSoundLine.isControlSupported(FloatControl.Type.MASTER_GAIN)) {
m_javaSoundLineControlMasterGain = (FloatControl)m_javaSoundLine.getControl(FloatControl.Type.MASTER_GAIN);
m_javaSoundLineControlMasterGainMin = m_javaSoundLineControlMasterGain.getMinimum();
m_javaSoundLineControlMasterGainMax = m_javaSoundLineControlMasterGain.getMaximum();
}
else {
m_javaSoundLineControlMasterGain = null;
m_javaSoundLineControlMasterGainMin = 0.0f;
m_javaSoundLineControlMasterGainMax = 0.0f;
}
/* Start the line writer thread.
* The line writer starts the line and passes the system time it started at
* via the lineStartTimeLatch. We then initialize the corresponding instance
* variable, signal the line writer thread, and finally wait for it to
* initialize it's the line end time instance variables.
*/
m_javaSoundLineWriter = new JavaSoundLineWriter();
m_javaSoundLineWriter.start();
m_lineStartTime = m_javaSoundLineWriter.lineStartTimeLatch.consume();
m_javaSoundLineWriter.startTimeSetLatch.offer(null);
m_javaSoundLineWriter.endTimeSetLatch.consume();
}
public void close() {
/* Tell the writer to exit and wait for that to happen */
m_javaSoundLineWriter.exit = true;
while (m_javaSoundLineWriter.isAlive()) {
try {
/* Be patient ... */
Thread.sleep(1);
}
catch (InterruptedException e) {
/* But when stressed, share the trouble ... */
m_javaSoundLineWriter.interrupt();
}
}
m_javaSoundLine.close();
}
public void setStartTime(double timeStamp) {
m_startTime = timeStamp;
}
public synchronized void setGain(float gain) {
m_requestedGain = gain;
if (m_requestedGain != m_currentGain)
setJavaSoundLineGain(m_requestedGain);
}
public synchronized float getGain(float gain) {
return m_requestedGain;
}
@Override
public double getNowTime() {
return m_lineStartTime + (double)m_javaSoundLine.getLongFramePosition() / m_sampleRate;
}
@Override
public double getNextTime() {
return m_javaSoundLineWriter.getEndTime();
}
@Override
public double getSampleRate() {
return m_sampleRate;
}
private synchronized void setJavaSoundLineGain(float gain) {
m_javaSoundLineControlMasterGain.setValue(Math.max(Math.min(
m_javaSoundLineControlMasterGainMin,
gain),
m_javaSoundLineControlMasterGainMax
));
m_currentGain = gain;
}
private synchronized void mute() {
if (m_currentGain > Float.MIN_VALUE)
setJavaSoundLineGain(Float.MIN_VALUE);
}
private synchronized void unmute() {
if (m_currentGain == Float.MIN_VALUE)
setJavaSoundLineGain(m_requestedGain);
}
}
| 14,633 | Java | .java | fgp/AirReceiver | 170 | 102 | 9 | 2011-04-28T07:17:04Z | 2020-10-13T10:13:16Z |
SampleByteFormat.java | /FileExtraction/Java_unseen/fgp_AirReceiver/src/main/java/org/phlo/audio/SampleByteFormat.java | /*
* This file is part of AirReceiver.
*
* AirReceiver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* AirReceiver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with AirReceiver. If not, see <http://www.gnu.org/licenses/>.
*/
package org.phlo.audio;
import java.nio.ByteBuffer;
import javax.sound.sampled.AudioFormat;
/**
* Described the byte format of individual samples
* <p>
* Used as a factory for {SampleAccessor} instances
* which provide access to the buffer's samples as
* float values indexed by their absolute position
* inside the buffer.
*/
public enum SampleByteFormat {
UnsignedInteger16(2) {
@Override public final Signedness getSignedness() {
return Signedness.Unsigned;
}
@Override public final SampleAccessor getAccessor(final ByteBuffer buffer) {
return new SampleAccessor() {
@Override public float getSample(final int index) {
return Signedness.Unsigned.shortToNormalizedFloat(buffer.getShort(BytesPerSample * index));
}
@Override public void setSample(final int index, final float sample) {
buffer.putShort(BytesPerSample * index, Signedness.Unsigned.shortFromNormalizedFloat(sample));
}
};
}
},
SignedInteger16(2) {
@Override public final Signedness getSignedness() {
return Signedness.Signed;
}
@Override public final SampleAccessor getAccessor(final ByteBuffer buffer) {
return new SampleAccessor() {
@Override public float getSample(final int index) {
return Signedness.Signed.shortToNormalizedFloat(buffer.getShort(BytesPerSample * index));
}
@Override public void setSample(final int index, final float sample) {
buffer.putShort(BytesPerSample * index, Signedness.Signed.shortFromNormalizedFloat(sample));
}
};
}
},
Float32(4) {
@Override public final Signedness getSignedness() {
return null;
}
@Override public final SampleAccessor getAccessor(final ByteBuffer buffer) {
return new SampleAccessor() {
@Override public float getSample(final int index) {
return buffer.getFloat(BytesPerSample * index);
}
@Override public void setSample(final int index, final float sample) {
buffer.putFloat(BytesPerSample * index, sample);
}
};
}
};
public static SampleByteFormat fromAudioFormat(AudioFormat audioFormat) {
if (
(AudioFormat.Encoding.PCM_SIGNED.equals(audioFormat.getEncoding())) &&
(audioFormat.getSampleSizeInBits() == 16)
) {
return SignedInteger16;
}
else if (
(AudioFormat.Encoding.PCM_UNSIGNED.equals(audioFormat.getEncoding())) &&
(audioFormat.getSampleSizeInBits() == 16)
) {
return UnsignedInteger16;
}
else {
throw new IllegalArgumentException("Audio format with encoding " + audioFormat.getEncoding() + " and " + audioFormat.getSampleSizeInBits() + " bits per sample is unsupported");
}
}
public final int BytesPerSample;
private SampleByteFormat(final int _bytesPerSample) {
BytesPerSample = _bytesPerSample;
}
/**
* Returns the size required to store a buffer of the
* given {@code dimensions}.
*
* @param dimensions dimensions of the buffer
* @return size of the buffer in bytes
*/
public int getSizeBytes(SampleDimensions dimensions) {
return dimensions.getTotalSamples() * BytesPerSample;
}
/**
* Computes the number of samples in a buffer from
* it's size in bytes and the number of channels.
*
* @param channels number of channels
* @param byteSize size in bytes
* @return dimensions of the buffer
*/
public SampleDimensions getDimensionsFromChannelsAndByteSize(int channels, int byteSize) {
return new SampleDimensions(channels, byteSize / (BytesPerSample * channels));
}
/**
* Returns the signedness (signed or unsigned) of
* a sample byte format
*
* @return signedness, or null of not relevant
*/
public abstract Signedness getSignedness();
/**
* Returns an accessor for a given byte buffer
*
* @param buffer byte buffer to access
* @return accessor instance
*/
public abstract SampleAccessor getAccessor(ByteBuffer buffer);
}
| 4,513 | Java | .java | fgp/AirReceiver | 170 | 102 | 9 | 2011-04-28T07:17:04Z | 2020-10-13T10:13:16Z |
SampleIndexer.java | /FileExtraction/Java_unseen/fgp_AirReceiver/src/main/java/org/phlo/audio/SampleIndexer.java | /*
* This file is part of AirReceiver.
*
* AirReceiver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* AirReceiver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with AirReceiver. If not, see <http://www.gnu.org/licenses/>.
*/
package org.phlo.audio;
public interface SampleIndexer {
SampleDimensions getDimensions();
SampleIndexer slice(SampleOffset offset, SampleDimensions dimensions);
SampleIndexer slice(SampleRange range);
int getSampleIndex(int channel, int sample);
}
| 945 | Java | .java | fgp/AirReceiver | 170 | 102 | 9 | 2011-04-28T07:17:04Z | 2020-10-13T10:13:16Z |
SampleDimensions.java | /FileExtraction/Java_unseen/fgp_AirReceiver/src/main/java/org/phlo/audio/SampleDimensions.java | /*
* This file is part of AirReceiver.
*
* AirReceiver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* AirReceiver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with AirReceiver. If not, see <http://www.gnu.org/licenses/>.
*/
package org.phlo.audio;
public final class SampleDimensions {
public final int channels;
public final int samples;
public SampleDimensions(final int _channels, final int _samples) {
if (_channels < 0)
throw new IllegalArgumentException("channels must be greater or equal to zero");
if (_samples < 0)
throw new IllegalArgumentException("samples must be greater or equal to zero");
channels = _channels;
samples = _samples;
}
public SampleDimensions reduce(int _channels, int _samples) {
assertContains(_channels, _samples);
return new SampleDimensions(channels - _channels, samples - _samples);
}
public SampleDimensions intersect(final SampleDimensions other) {
return new SampleDimensions(
Math.min(channels, other.channels),
Math.min(samples, other.samples)
);
}
public int getTotalSamples() {
return channels * samples;
}
public boolean contains(int _channels, int _samples) {
return (_channels <= channels) && (_samples <= samples);
}
public boolean contains(SampleOffset offset, SampleDimensions dimensions) {
return contains(offset.channel + dimensions.channels, offset.sample + dimensions.samples);
}
public boolean contains(SampleRange range) {
return contains(range.offset, range.size);
}
public boolean contains(SampleOffset offset) {
return (offset.channel < channels) && (offset.sample < samples);
}
public boolean contains(SampleDimensions dimensions) {
return contains(dimensions.channels, dimensions.samples);
}
public void assertContains(int _channels, int _samples) {
if (!contains(_channels, _samples))
throw new IllegalArgumentException("Index (" + _channels + "," + _samples + ") exceeds dimensions " + this);
}
public void assertContains(SampleOffset offset, SampleDimensions dimensions) {
if (!contains(offset, dimensions))
throw new IllegalArgumentException("Dimensions " + dimensions + " at " + offset + " exceed dimensions " + this);
}
public void assertContains(SampleRange range) {
if (!contains(range))
throw new IllegalArgumentException("Range " + range + " exceeds dimensions " + this);
}
public void assertContains(SampleOffset offset) {
if (!contains(offset))
throw new IllegalArgumentException("Offset " + offset + " exceeds dimensions " + this);
}
public void assertContains(SampleDimensions dimensions) {
if (!contains(dimensions))
throw new IllegalArgumentException("Dimensions " + dimensions + " exceeds dimensions " + this);
}
@Override
public String toString() {
return "[" + channels + ";" + samples + "]";
}
}
| 3,264 | Java | .java | fgp/AirReceiver | 170 | 102 | 9 | 2011-04-28T07:17:04Z | 2020-10-13T10:13:16Z |
Defines.java | /FileExtraction/Java_unseen/fgp_AirReceiver/src/main/java/com/beatofthedrum/alacdecoder/Defines.java | /*
** Defines.java
**
** Copyright (c) 2011 Peter McQuillan
**
** All Rights Reserved.
**
** Distributed under the BSD Software License (see license.txt)
**
*/
package com.beatofthedrum.alacdecoder;
class Defines
{
static int RICE_THRESHOLD = 8;
} | 278 | Java | .java | fgp/AirReceiver | 170 | 102 | 9 | 2011-04-28T07:17:04Z | 2020-10-13T10:13:16Z |
AlacDecodeUtils.java | /FileExtraction/Java_unseen/fgp_AirReceiver/src/main/java/com/beatofthedrum/alacdecoder/AlacDecodeUtils.java | /*
** AlacDecodeUtils.java
**
** Copyright (c) 2011 Peter McQuillan
**
** All Rights Reserved.
**
** Distributed under the BSD Software License (see license.txt)
**
*/
package com.beatofthedrum.alacdecoder;
public class AlacDecodeUtils
{
public static void alac_set_info(AlacFile alac, int[] inputbuffer)
{
int ptrIndex = 0;
ptrIndex += 4; // size
ptrIndex += 4; // frma
ptrIndex += 4; // alac
ptrIndex += 4; // size
ptrIndex += 4; // alac
ptrIndex += 4; // 0 ?
alac.setinfo_max_samples_per_frame = ((inputbuffer[ptrIndex] << 24) + (inputbuffer[ptrIndex+1] << 16) + (inputbuffer[ptrIndex+2] << 8) + inputbuffer[ptrIndex+3]); // buffer size / 2 ?
ptrIndex += 4;
alac.setinfo_7a = inputbuffer[ptrIndex];
ptrIndex += 1;
alac.setinfo_sample_size = inputbuffer[ptrIndex];
ptrIndex += 1;
alac.setinfo_rice_historymult = (inputbuffer[ptrIndex] & 0xff);
ptrIndex += 1;
alac.setinfo_rice_initialhistory = (inputbuffer[ptrIndex] & 0xff);
ptrIndex += 1;
alac.setinfo_rice_kmodifier = (inputbuffer[ptrIndex] & 0xff);
ptrIndex += 1;
alac.setinfo_7f = inputbuffer[ptrIndex];
ptrIndex += 1;
alac.setinfo_80 = (inputbuffer[ptrIndex] << 8) + inputbuffer[ptrIndex+1];
ptrIndex += 2;
alac.setinfo_82 = ((inputbuffer[ptrIndex] << 24) + (inputbuffer[ptrIndex+1] << 16) + (inputbuffer[ptrIndex+2] << 8) + inputbuffer[ptrIndex+3]);
ptrIndex += 4;
alac.setinfo_86 = ((inputbuffer[ptrIndex] << 24) + (inputbuffer[ptrIndex+1] << 16) + (inputbuffer[ptrIndex+2] << 8) + inputbuffer[ptrIndex+3]);
ptrIndex += 4;
alac.setinfo_8a_rate = ((inputbuffer[ptrIndex] << 24) + (inputbuffer[ptrIndex+1] << 16) + (inputbuffer[ptrIndex+2] << 8) + inputbuffer[ptrIndex+3]);
ptrIndex += 4;
}
/* stream reading */
/* supports reading 1 to 16 bits, in big endian format */
static int readbits_16(AlacFile alac, int bits )
{
int result = 0;
int new_accumulator = 0;
int part1 = 0;
int part2 = 0;
int part3 =0;
part1 = (alac.input_buffer[alac.ibIdx] & 0xff);
part2 = (alac.input_buffer[alac.ibIdx + 1] & 0xff);
part3 = (alac.input_buffer[alac.ibIdx + 2] & 0xff);
result = ((part1 << 16) | (part2 << 8) | part3);
/* shift left by the number of bits we've already read,
* so that the top 'n' bits of the 24 bits we read will
* be the return bits */
result = result << alac.input_buffer_bitaccumulator;
result = result & 0x00ffffff;
/* and then only want the top 'n' bits from that, where
* n is 'bits' */
result = result >> (24 - bits);
new_accumulator = (alac.input_buffer_bitaccumulator + bits);
/* increase the buffer pointer if we've read over n bytes. */
alac.ibIdx += (new_accumulator >> 3);
/* and the remainder goes back into the bit accumulator */
alac.input_buffer_bitaccumulator = (new_accumulator & 7);
return result;
}
/* supports reading 1 to 32 bits, in big endian format */
static int readbits(AlacFile alac, int bits )
{
int result = 0;
if (bits > 16)
{
bits -= 16;
result = readbits_16(alac, 16) << bits;
}
result |= readbits_16(alac, bits);
return result;
}
/* reads a single bit */
static int readbit(AlacFile alac)
{
int result = 0;
int new_accumulator = 0;
int part1 = 0;
part1 = (alac.input_buffer[alac.ibIdx] & 0xff);
result = part1;
result = result << alac.input_buffer_bitaccumulator;
result = result >> 7 & 1;
new_accumulator = (alac.input_buffer_bitaccumulator + 1);
alac.ibIdx += new_accumulator / 8;
alac.input_buffer_bitaccumulator = (new_accumulator % 8);
return result;
}
static void unreadbits(AlacFile alac, int bits )
{
int new_accumulator = (alac.input_buffer_bitaccumulator - bits);
alac.ibIdx += (new_accumulator >> 3);
alac.input_buffer_bitaccumulator = (new_accumulator & 7);
if (alac.input_buffer_bitaccumulator < 0)
alac.input_buffer_bitaccumulator *= -1;
}
static LeadingZeros count_leading_zeros_extra(int curbyte, int output, LeadingZeros lz)
{
if ((curbyte & 0xf0)==0)
{
output += 4;
}
else
curbyte = curbyte >> 4;
if ((curbyte & 0x8) != 0)
{
lz.output = output;
lz.curbyte = curbyte;
return lz;
}
if ((curbyte & 0x4) != 0)
{
lz.output = output + 1;
lz.curbyte = curbyte;
return lz;
}
if ((curbyte & 0x2) != 0)
{
lz.output = output + 2;
lz.curbyte = curbyte;
return lz;
}
if ((curbyte & 0x1) != 0)
{
lz.output = output + 3;
lz.curbyte = curbyte;
return lz;
}
/* shouldn't get here: */
lz.output = output + 4;
lz.curbyte = curbyte;
return lz;
}
static int count_leading_zeros(int input, LeadingZeros lz)
{
int output = 0;
int curbyte = 0;
curbyte = input >> 24;
if (curbyte != 0)
{
count_leading_zeros_extra(curbyte, output, lz);
output = lz.output;
curbyte = lz.curbyte;
return output;
}
output += 8;
curbyte = input >> 16;
if ((curbyte & 0xFF) != 0)
{
count_leading_zeros_extra(curbyte, output, lz);
output = lz.output;
curbyte = lz.curbyte;
return output;
}
output += 8;
curbyte = input >> 8;
if ((curbyte & 0xFF) != 0)
{
count_leading_zeros_extra(curbyte, output, lz);
output = lz.output;
curbyte = lz.curbyte;
return output;
}
output += 8;
curbyte = input;
if ((curbyte & 0xFF) != 0)
{
count_leading_zeros_extra(curbyte, output, lz);
output = lz.output;
curbyte = lz.curbyte;
return output;
}
output += 8;
return output;
}
public static int entropy_decode_value(AlacFile alac, int readSampleSize , int k , int rice_kmodifier_mask )
{
int x = 0; // decoded value
// read x, number of 1s before 0 represent the rice value.
while (x <= Defines.RICE_THRESHOLD && readbit(alac) != 0)
{
x++;
}
if (x > Defines.RICE_THRESHOLD)
{
// read the number from the bit stream (raw value)
int value = 0;
value = readbits(alac, readSampleSize);
// mask value
value &= ((0xffffffff) >> (32 - readSampleSize));
x = value;
}
else
{
if (k != 1)
{
int extraBits = readbits(alac, k);
x *= (((1 << k) - 1) & rice_kmodifier_mask);
if (extraBits > 1)
x += extraBits - 1;
else
unreadbits(alac, 1);
}
}
return x;
}
public static void entropy_rice_decode(AlacFile alac, int[] outputBuffer, int outputSize , int readSampleSize , int rice_initialhistory , int rice_kmodifier , int rice_historymult , int rice_kmodifier_mask )
{
int history = rice_initialhistory;
int outputCount = 0;
int signModifier = 0;
while(outputCount < outputSize)
{
int decodedValue = 0;
int finalValue = 0;
int k = 0;
k = 31 - rice_kmodifier - count_leading_zeros((history >> 9) + 3, alac.lz);
if (k < 0)
k += rice_kmodifier;
else
k = rice_kmodifier;
// note: don't use rice_kmodifier_mask here (set mask to 0xFFFFFFFF)
decodedValue = entropy_decode_value(alac, readSampleSize, k, 0xFFFFFFFF);
decodedValue += signModifier;
finalValue = ((decodedValue + 1) / 2); // inc by 1 and shift out sign bit
if ((decodedValue & 1) != 0) // the sign is stored in the low bit
finalValue *= -1;
outputBuffer[outputCount] = finalValue;
signModifier = 0;
// update history
history += (decodedValue * rice_historymult) - ((history * rice_historymult) >> 9);
if (decodedValue > 0xFFFF)
history = 0xFFFF;
// special case, for compressed blocks of 0
if ((history < 128) && (outputCount + 1 < outputSize))
{
int blockSize = 0;
signModifier = 1;
k = count_leading_zeros(history, alac.lz) + ((history + 16) / 64) - 24;
// note: blockSize is always 16bit
blockSize = entropy_decode_value(alac, 16, k, rice_kmodifier_mask);
// got blockSize 0s
if (blockSize > 0)
{
int countSize = 0;
countSize = blockSize;
for (int j = 0; j < countSize; j++)
{
outputBuffer[outputCount + 1 + j] = 0;
}
outputCount += blockSize;
}
if (blockSize > 0xFFFF)
signModifier = 0;
history = 0;
}
outputCount++;
}
}
static int[] predictor_decompress_fir_adapt(int[] error_buffer, int output_size , int readsamplesize , int[] predictor_coef_table, int predictor_coef_num , int predictor_quantitization )
{
int buffer_out_idx = 0;
int[] buffer_out;
int bitsmove = 0;
/* first sample always copies */
buffer_out = error_buffer;
if (predictor_coef_num == 0)
{
if (output_size <= 1)
return(buffer_out);
int sizeToCopy = 0;
sizeToCopy = (output_size-1) * 4;
System.arraycopy(error_buffer, 1, buffer_out, 1, sizeToCopy);
return(buffer_out);
}
if (predictor_coef_num == 0x1f) // 11111 - max value of predictor_coef_num
{
/* second-best case scenario for fir decompression,
* error describes a small difference from the previous sample only
*/
if (output_size <= 1)
return(buffer_out);
for (int i = 0; i < (output_size - 1); i++)
{
int prev_value = 0;
int error_value = 0;
prev_value = buffer_out[i];
error_value = error_buffer[i+1];
bitsmove = 32 - readsamplesize;
buffer_out[i+1] = (((prev_value + error_value) << bitsmove) >> bitsmove);
}
return(buffer_out);
}
/* read warm-up samples */
if (predictor_coef_num > 0)
{
for (int i = 0; i < predictor_coef_num; i++)
{
int val = 0;
val = buffer_out[i] + error_buffer[i+1];
bitsmove = 32 - readsamplesize;
val = ((val << bitsmove) >> bitsmove);
buffer_out[i+1] = val;
}
}
/* general case */
if (predictor_coef_num > 0)
{
buffer_out_idx = 0;
for (int i = predictor_coef_num + 1; i < output_size; i++)
{
int j ;
int sum = 0;
int outval ;
int error_val = error_buffer[i];
for (j = 0; j < predictor_coef_num; j++)
{
sum += (buffer_out[buffer_out_idx + predictor_coef_num-j] - buffer_out[buffer_out_idx]) * predictor_coef_table[j];
}
outval = (1 << (predictor_quantitization-1)) + sum;
outval = outval >> predictor_quantitization;
outval = outval + buffer_out[buffer_out_idx] + error_val;
bitsmove = 32 - readsamplesize;
outval = ((outval << bitsmove) >> bitsmove);
buffer_out[buffer_out_idx+predictor_coef_num+1] = outval;
if (error_val > 0)
{
int predictor_num = predictor_coef_num - 1;
while (predictor_num >= 0 && error_val > 0)
{
int val = buffer_out[buffer_out_idx] - buffer_out[buffer_out_idx + predictor_coef_num - predictor_num];
int sign = ((val < 0) ? (-1) : ((val > 0) ? (1) : (0)));
predictor_coef_table[predictor_num] -= sign;
val *= sign; // absolute value
error_val -= ((val >> predictor_quantitization) * (predictor_coef_num - predictor_num));
predictor_num--;
}
}
else if (error_val < 0)
{
int predictor_num = predictor_coef_num - 1;
while (predictor_num >= 0 && error_val < 0)
{
int val = buffer_out[buffer_out_idx] - buffer_out[buffer_out_idx + predictor_coef_num - predictor_num];
int sign = - ((val < 0) ? (-1) : ((val > 0) ? (1) : (0)));
predictor_coef_table[predictor_num] -= sign;
val *= sign; // neg value
error_val -= ((val >> predictor_quantitization) * (predictor_coef_num - predictor_num));
predictor_num--;
}
}
buffer_out_idx++;
}
}
return(buffer_out);
}
public static void deinterlace_16(int[] buffer_a, int[] buffer_b, int[] buffer_out, int numchannels , int numsamples , int interlacing_shift , int interlacing_leftweight )
{
if (numsamples <= 0)
return;
/* weighted interlacing */
if (0 != interlacing_leftweight)
{
for (int i = 0; i < numsamples; i++)
{
int difference = 0;
int midright = 0;
int left = 0;
int right = 0;
midright = buffer_a[i];
difference = buffer_b[i];
right = (midright - ((difference * interlacing_leftweight) >> interlacing_shift));
left = (right + difference);
/* output is always little endian */
buffer_out[i *numchannels] = left;
buffer_out[i *numchannels + 1] = right;
}
return;
}
/* otherwise basic interlacing took place */
for (int i = 0; i < numsamples; i++)
{
int left = 0;
int right = 0;
left = buffer_a[i];
right = buffer_b[i];
/* output is always little endian */
buffer_out[i *numchannels] = left;
buffer_out[i *numchannels + 1] = right;
}
}
public static void deinterlace_24(int[] buffer_a, int[] buffer_b, int uncompressed_bytes , int[] uncompressed_bytes_buffer_a, int[] uncompressed_bytes_buffer_b, int[] buffer_out, int numchannels , int numsamples , int interlacing_shift , int interlacing_leftweight )
{
if (numsamples <= 0)
return;
/* weighted interlacing */
if (interlacing_leftweight != 0)
{
for (int i = 0; i < numsamples; i++)
{
int difference = 0;
int midright = 0;
int left = 0;
int right = 0;
midright = buffer_a[i];
difference = buffer_b[i];
right = midright - ((difference * interlacing_leftweight) >> interlacing_shift);
left = right + difference;
if (uncompressed_bytes != 0)
{
int mask = ~(0xFFFFFFFF << (uncompressed_bytes * 8));
left <<= (uncompressed_bytes * 8);
right <<= (uncompressed_bytes * 8);
left = left | (uncompressed_bytes_buffer_a[i] & mask);
right = right | (uncompressed_bytes_buffer_b[i] & mask);
}
buffer_out[i * numchannels * 3] = (left & 0xFF);
buffer_out[i * numchannels * 3 + 1] = ((left >> 8) & 0xFF);
buffer_out[i * numchannels * 3 + 2] = ((left >> 16) & 0xFF);
buffer_out[i * numchannels * 3 + 3] = (right & 0xFF);
buffer_out[i * numchannels * 3 + 4] = ((right >> 8) & 0xFF);
buffer_out[i * numchannels * 3 + 5] = ((right >> 16) & 0xFF);
}
return;
}
/* otherwise basic interlacing took place */
for (int i = 0; i < numsamples; i++)
{
int left = 0;
int right = 0;
left = buffer_a[i];
right = buffer_b[i];
if (uncompressed_bytes != 0)
{
int mask = ~(0xFFFFFFFF << (uncompressed_bytes * 8));
left <<= (uncompressed_bytes * 8);
right <<= (uncompressed_bytes * 8);
left = left | (uncompressed_bytes_buffer_a[i] & mask);
right = right | (uncompressed_bytes_buffer_b[i] & mask);
}
buffer_out[i * numchannels * 3] = (left & 0xFF);
buffer_out[i * numchannels * 3 + 1] = ((left >> 8) & 0xFF);
buffer_out[i * numchannels * 3 + 2] = ((left >> 16) & 0xFF);
buffer_out[i * numchannels * 3 + 3] = (right & 0xFF);
buffer_out[i * numchannels * 3 + 4] = ((right >> 8) & 0xFF);
buffer_out[i * numchannels * 3 + 5] = ((right >> 16) & 0xFF);
}
}
public static int decode_frame(AlacFile alac, byte[] inbuffer, int[] outbuffer, int outputsize )
{
int channels ;
int outputsamples = alac.setinfo_max_samples_per_frame;
/* setup the stream */
alac.input_buffer = inbuffer;
alac.input_buffer_bitaccumulator = 0;
alac.ibIdx = 0;
channels = readbits(alac, 3);
outputsize = outputsamples * alac.bytespersample;
if(channels == 0) // 1 channel
{
int hassize ;
int isnotcompressed ;
int readsamplesize ;
int uncompressed_bytes ;
int ricemodifier ;
int tempPred = 0;
/* 2^result = something to do with output waiting.
* perhaps matters if we read > 1 frame in a pass?
*/
readbits(alac, 4);
readbits(alac, 12); // unknown, skip 12 bits
hassize = readbits(alac, 1); // the output sample size is stored soon
uncompressed_bytes = readbits(alac, 2); // number of bytes in the (compressed) stream that are not compressed
isnotcompressed = readbits(alac, 1); // whether the frame is compressed
if (hassize != 0)
{
/* now read the number of samples,
* as a 32bit integer */
outputsamples = readbits(alac, 32);
outputsize = outputsamples * alac.bytespersample;
}
readsamplesize = alac.setinfo_sample_size - (uncompressed_bytes * 8);
if (isnotcompressed == 0)
{ // so it is compressed
int[] predictor_coef_table = alac.predictor_coef_table;
int predictor_coef_num ;
int prediction_type ;
int prediction_quantitization ;
int i ;
/* skip 16 bits, not sure what they are. seem to be used in
* two channel case */
readbits(alac, 8);
readbits(alac, 8);
prediction_type = readbits(alac, 4);
prediction_quantitization = readbits(alac, 4);
ricemodifier = readbits(alac, 3);
predictor_coef_num = readbits(alac, 5);
/* read the predictor table */
for (i = 0; i < predictor_coef_num; i++)
{
tempPred = readbits(alac,16);
if(tempPred > 32767)
{
// the predictor coef table values are only 16 bit signed
tempPred = tempPred - 65536;
}
predictor_coef_table[i] = tempPred;
}
if (uncompressed_bytes != 0)
{
for (i = 0; i < outputsamples; i++)
{
alac.uncompressed_bytes_buffer_a[i] = readbits(alac, uncompressed_bytes * 8);
}
}
entropy_rice_decode(alac, alac.predicterror_buffer_a, outputsamples, readsamplesize, alac.setinfo_rice_initialhistory, alac.setinfo_rice_kmodifier, ricemodifier * (alac.setinfo_rice_historymult / 4), (1 << alac.setinfo_rice_kmodifier) - 1);
if (prediction_type == 0)
{ // adaptive fir
alac.outputsamples_buffer_a = predictor_decompress_fir_adapt(alac.predicterror_buffer_a, outputsamples, readsamplesize, predictor_coef_table, predictor_coef_num, prediction_quantitization);
}
else
{
System.err.println("FIXME: unhandled predicition type: " +prediction_type);
/* i think the only other prediction type (or perhaps this is just a
* boolean?) runs adaptive fir twice.. like:
* predictor_decompress_fir_adapt(predictor_error, tempout, ...)
* predictor_decompress_fir_adapt(predictor_error, outputsamples ...)
* little strange..
*/
}
}
else
{ // not compressed, easy case
if (alac.setinfo_sample_size <= 16)
{
int bitsmove = 0;
for (int i = 0; i < outputsamples; i++)
{
int audiobits = readbits(alac, alac.setinfo_sample_size);
bitsmove = 32 - alac.setinfo_sample_size;
audiobits = ((audiobits << bitsmove) >> bitsmove);
alac.outputsamples_buffer_a[i] = audiobits;
}
}
else
{
int x ;
int m = 1 << (24 -1);
for (int i = 0; i < outputsamples; i++)
{
int audiobits ;
audiobits = readbits(alac, 16);
/* special case of sign extension..
* as we'll be ORing the low 16bits into this */
audiobits = audiobits << (alac.setinfo_sample_size - 16);
audiobits = audiobits | readbits(alac, alac.setinfo_sample_size - 16);
x = audiobits & ((1 << 24) - 1);
audiobits = (x ^ m) - m; // sign extend 24 bits
alac.outputsamples_buffer_a[i] = audiobits;
}
}
uncompressed_bytes = 0; // always 0 for uncompressed
}
switch(alac.setinfo_sample_size)
{
case 16:
{
for (int i = 0; i < outputsamples; i++)
{
int sample = alac.outputsamples_buffer_a[i];
outbuffer[i * alac.numchannels] = sample;
/*
** We have to handle the case where the data is actually mono, but the stsd atom says it has 2 channels
** in this case we create a stereo file where one of the channels is silent. If mono and 1 channel this value
** will be overwritten in the next iteration
*/
outbuffer[(i * alac.numchannels) + 1] = 0;
}
break;
}
case 24:
{
for (int i = 0; i < outputsamples; i++)
{
int sample = alac.outputsamples_buffer_a[i];
if (uncompressed_bytes != 0)
{
int mask = 0;
sample = sample << (uncompressed_bytes * 8);
mask = ~(0xFFFFFFFF << (uncompressed_bytes * 8));
sample = sample | (alac.uncompressed_bytes_buffer_a[i] & mask);
}
outbuffer[i * alac.numchannels * 3] = ((sample) & 0xFF);
outbuffer[i * alac.numchannels * 3 + 1] = ((sample >> 8) & 0xFF);
outbuffer[i * alac.numchannels * 3 + 2] = ((sample >> 16) & 0xFF);
/*
** We have to handle the case where the data is actually mono, but the stsd atom says it has 2 channels
** in this case we create a stereo file where one of the channels is silent. If mono and 1 channel this value
** will be overwritten in the next iteration
*/
outbuffer[i * alac.numchannels * 3 + 3] = 0;
outbuffer[i * alac.numchannels * 3 + 4] = 0;
outbuffer[i * alac.numchannels * 3 + 5] = 0;
}
break;
}
case 20:
case 32:
System.err.println("FIXME: unimplemented sample size " + alac.setinfo_sample_size);
default:
}
}
else if(channels == 1) // 2 channels
{
int hassize ;
int isnotcompressed ;
int readsamplesize ;
int uncompressed_bytes ;
int interlacing_shift ;
int interlacing_leftweight ;
/* 2^result = something to do with output waiting.
* perhaps matters if we read > 1 frame in a pass?
*/
readbits(alac, 4);
readbits(alac, 12); // unknown, skip 12 bits
hassize = readbits(alac, 1); // the output sample size is stored soon
uncompressed_bytes = readbits(alac, 2); // the number of bytes in the (compressed) stream that are not compressed
isnotcompressed = readbits(alac, 1); // whether the frame is compressed
if (hassize != 0)
{
/* now read the number of samples,
* as a 32bit integer */
outputsamples = readbits(alac, 32);
outputsize = outputsamples * alac.bytespersample;
}
readsamplesize = alac.setinfo_sample_size - (uncompressed_bytes * 8) + 1;
if (isnotcompressed == 0)
{ // compressed
int[] predictor_coef_table_a = alac.predictor_coef_table_a;
int predictor_coef_num_a ;
int prediction_type_a ;
int prediction_quantitization_a ;
int ricemodifier_a ;
int[] predictor_coef_table_b = alac.predictor_coef_table_b;
int predictor_coef_num_b ;
int prediction_type_b ;
int prediction_quantitization_b ;
int ricemodifier_b ;
int tempPred = 0;
interlacing_shift = readbits(alac, 8);
interlacing_leftweight = readbits(alac, 8);
/******** channel 1 ***********/
prediction_type_a = readbits(alac, 4);
prediction_quantitization_a = readbits(alac, 4);
ricemodifier_a = readbits(alac, 3);
predictor_coef_num_a = readbits(alac, 5);
/* read the predictor table */
for (int i = 0; i < predictor_coef_num_a; i++)
{
tempPred = readbits(alac,16);
if(tempPred > 32767)
{
// the predictor coef table values are only 16 bit signed
tempPred = tempPred - 65536;
}
predictor_coef_table_a[i] = tempPred;
}
/******** channel 2 *********/
prediction_type_b = readbits(alac, 4);
prediction_quantitization_b = readbits(alac, 4);
ricemodifier_b = readbits(alac, 3);
predictor_coef_num_b = readbits(alac, 5);
/* read the predictor table */
for (int i = 0; i < predictor_coef_num_b; i++)
{
tempPred = readbits(alac,16);
if(tempPred > 32767)
{
// the predictor coef table values are only 16 bit signed
tempPred = tempPred - 65536;
}
predictor_coef_table_b[i] = tempPred;
}
/*********************/
if (uncompressed_bytes != 0)
{ // see mono case
for (int i = 0; i < outputsamples; i++)
{
alac.uncompressed_bytes_buffer_a[i] = readbits(alac, uncompressed_bytes * 8);
alac.uncompressed_bytes_buffer_b[i] = readbits(alac, uncompressed_bytes * 8);
}
}
/* channel 1 */
entropy_rice_decode(alac, alac.predicterror_buffer_a, outputsamples, readsamplesize, alac.setinfo_rice_initialhistory, alac.setinfo_rice_kmodifier, ricemodifier_a * (alac.setinfo_rice_historymult / 4), (1 << alac.setinfo_rice_kmodifier) - 1);
if (prediction_type_a == 0)
{ // adaptive fir
alac.outputsamples_buffer_a = predictor_decompress_fir_adapt(alac.predicterror_buffer_a, outputsamples, readsamplesize, predictor_coef_table_a, predictor_coef_num_a, prediction_quantitization_a);
}
else
{ // see mono case
System.err.println("FIXME: unhandled predicition type: " + prediction_type_a);
}
/* channel 2 */
entropy_rice_decode(alac, alac.predicterror_buffer_b, outputsamples, readsamplesize, alac.setinfo_rice_initialhistory, alac.setinfo_rice_kmodifier, ricemodifier_b * (alac.setinfo_rice_historymult / 4), (1 << alac.setinfo_rice_kmodifier) - 1);
if (prediction_type_b == 0)
{ // adaptive fir
alac.outputsamples_buffer_b = predictor_decompress_fir_adapt(alac.predicterror_buffer_b, outputsamples, readsamplesize, predictor_coef_table_b, predictor_coef_num_b, prediction_quantitization_b);
}
else
{
System.err.println("FIXME: unhandled predicition type: " + prediction_type_b);
}
}
else
{ // not compressed, easy case
if (alac.setinfo_sample_size <= 16)
{
int bitsmove ;
for (int i = 0; i < outputsamples; i++)
{
int audiobits_a ;
int audiobits_b ;
audiobits_a = readbits(alac, alac.setinfo_sample_size);
audiobits_b = readbits(alac, alac.setinfo_sample_size);
bitsmove = 32 - alac.setinfo_sample_size;
audiobits_a = ((audiobits_a << bitsmove) >> bitsmove);
audiobits_b = ((audiobits_b << bitsmove) >> bitsmove);
alac.outputsamples_buffer_a[i] = audiobits_a;
alac.outputsamples_buffer_b[i] = audiobits_b;
}
}
else
{
int x ;
int m = 1 << (24 -1);
for (int i = 0; i < outputsamples; i++)
{
int audiobits_a ;
int audiobits_b ;
audiobits_a = readbits(alac, 16);
audiobits_a = audiobits_a << (alac.setinfo_sample_size - 16);
audiobits_a = audiobits_a | readbits(alac, alac.setinfo_sample_size - 16);
x = audiobits_a & ((1 << 24) - 1);
audiobits_a = (x ^ m) - m; // sign extend 24 bits
audiobits_b = readbits(alac, 16);
audiobits_b = audiobits_b << (alac.setinfo_sample_size - 16);
audiobits_b = audiobits_b | readbits(alac, alac.setinfo_sample_size - 16);
x = audiobits_b & ((1 << 24) - 1);
audiobits_b = (x ^ m) - m; // sign extend 24 bits
alac.outputsamples_buffer_a[i] = audiobits_a;
alac.outputsamples_buffer_b[i] = audiobits_b;
}
}
uncompressed_bytes = 0; // always 0 for uncompressed
interlacing_shift = 0;
interlacing_leftweight = 0;
}
switch(alac.setinfo_sample_size)
{
case 16:
{
deinterlace_16(alac.outputsamples_buffer_a, alac.outputsamples_buffer_b, outbuffer, alac.numchannels, outputsamples, interlacing_shift, interlacing_leftweight);
break;
}
case 24:
{
deinterlace_24(alac.outputsamples_buffer_a, alac.outputsamples_buffer_b, uncompressed_bytes, alac.uncompressed_bytes_buffer_a, alac.uncompressed_bytes_buffer_b, outbuffer, alac.numchannels, outputsamples, interlacing_shift, interlacing_leftweight);
break;
}
case 20:
case 32:
System.err.println("FIXME: unimplemented sample size " + alac.setinfo_sample_size);
default:
}
}
return outputsize;
}
public static AlacFile create_alac(int samplesize , int numchannels )
{
AlacFile newfile = new AlacFile();
newfile.samplesize = samplesize;
newfile.numchannels = numchannels;
newfile.bytespersample = (samplesize / 8) * numchannels;
return newfile;
}
}
| 27,475 | Java | .java | fgp/AirReceiver | 170 | 102 | 9 | 2011-04-28T07:17:04Z | 2020-10-13T10:13:16Z |
AlacFile.java | /FileExtraction/Java_unseen/fgp_AirReceiver/src/main/java/com/beatofthedrum/alacdecoder/AlacFile.java | /*
** AlacFile.java
**
** Copyright (c) 2011 Peter McQuillan
**
** All Rights Reserved.
**
** Distributed under the BSD Software License (see license.txt)
**
*/
package com.beatofthedrum.alacdecoder;
public class AlacFile
{
byte input_buffer[];
int ibIdx = 0;
int input_buffer_bitaccumulator = 0; /* used so we can do arbitary
bit reads */
int samplesize = 0;
int numchannels = 0;
int bytespersample = 0;
LeadingZeros lz = new LeadingZeros();
private int buffer_size = 16384;
/* buffers */
int predicterror_buffer_a[] = new int[buffer_size];
int predicterror_buffer_b[] = new int[buffer_size];
int outputsamples_buffer_a[] = new int[buffer_size];
int outputsamples_buffer_b[] = new int[buffer_size];
int uncompressed_bytes_buffer_a[] = new int[buffer_size];
int uncompressed_bytes_buffer_b[] = new int[buffer_size];
/* stuff from setinfo */
public int setinfo_max_samples_per_frame = 0; // 0x1000 = 4096
/* max samples per frame? */
public int setinfo_7a = 0; // 0x00
public int setinfo_sample_size = 0; // 0x10
public int setinfo_rice_historymult = 0; // 0x28
public int setinfo_rice_initialhistory = 0; // 0x0a
public int setinfo_rice_kmodifier = 0; // 0x0e
public int setinfo_7f = 0; // 0x02
public int setinfo_80 = 0; // 0x00ff
public int setinfo_82 = 0; // 0x000020e7
/* max sample size?? */
public int setinfo_86 = 0; // 0x00069fe4
/* bit rate (avarge)?? */
public int setinfo_8a_rate = 0; // 0x0000ac44
/* end setinfo stuff */
public int[] predictor_coef_table = new int[1024];
public int[] predictor_coef_table_a = new int[1024];
public int[] predictor_coef_table_b = new int[1024];
} | 1,689 | Java | .java | fgp/AirReceiver | 170 | 102 | 9 | 2011-04-28T07:17:04Z | 2020-10-13T10:13:16Z |
LeadingZeros.java | /FileExtraction/Java_unseen/fgp_AirReceiver/src/main/java/com/beatofthedrum/alacdecoder/LeadingZeros.java | /*
** LeadingZeros.java
**
** Copyright (c) 2011 Peter McQuillan
**
** All Rights Reserved.
**
** Distributed under the BSD Software License (see license.txt)
**
*/
package com.beatofthedrum.alacdecoder;
class LeadingZeros
{
public int curbyte = 0;
public int output = 0;
} | 302 | Java | .java | fgp/AirReceiver | 170 | 102 | 9 | 2011-04-28T07:17:04Z | 2020-10-13T10:13:16Z |
Rayce.java | /FileExtraction/Java_unseen/Usbac_Rayce/core/src/com/mygdx/game/Rayce.java | package com.mygdx.game;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
public class Rayce extends ApplicationAdapter {
SpriteBatch batch;
Texture img;
@Override
public void create () {
batch = new SpriteBatch();
img = new Texture("badlogic.jpg");
}
@Override
public void render () {
Gdx.gl.glClearColor(1, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
batch.draw(img, 0, 0);
batch.end();
}
@Override
public void dispose () {
batch.dispose();
img.dispose();
}
}
| 675 | Java | .java | Usbac/Rayce | 9 | 2 | 0 | 2018-06-29T23:14:46Z | 2020-05-12T14:58:21Z |
Base.java | /FileExtraction/Java_unseen/Usbac_Rayce/desktop/src/com/mygdx/game/desktop/Base.java | package com.mygdx.game.desktop;
import com.badlogic.gdx.Game;
public class Base extends Game {
Main state;
@Override
public void create() {
state = new Main(this);
this.setScreen(state);
}
} | 4,615 | Java | .java | Usbac/Rayce | 9 | 2 | 0 | 2018-06-29T23:14:46Z | 2020-05-12T14:58:21Z |
DesktopLauncher.java | /FileExtraction/Java_unseen/Usbac_Rayce/desktop/src/com/mygdx/game/desktop/DesktopLauncher.java | package com.mygdx.game.desktop;
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
public class DesktopLauncher {
public static void main (String[] arg) {
LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
new LwjglApplication(new Base(), config);
//Configuracion graficos
config.title="RAYCE - Raycasting Engine";
config.width = 1280;
config.height = 720;
config.vSyncEnabled = false;
config.foregroundFPS = 0;
config.fullscreen = false;
config.resizable = false;
}
}
| 659 | Java | .java | Usbac/Rayce | 9 | 2 | 0 | 2018-06-29T23:14:46Z | 2020-05-12T14:58:21Z |
Entity.java | /FileExtraction/Java_unseen/Usbac_Rayce/desktop/src/com/mygdx/game/desktop/Entity.java | package com.mygdx.game.desktop;
import com.badlogic.gdx.graphics.g2d.*;
import org.lwjgl.util.vector.Vector2f;
public class Entity {
static final float DEFAULT_SIZE = 1.8f;
static Vector2f rayIntensity;
private Vector2f position;
private float distance, size;
private Sprite texture;
private boolean in_vision, visible, is_drawn, collisionable;
public Entity() {
visible = true;
}
public Entity(TextureRegion text, int x, int y, boolean c) {
position = new Vector2f(x, y);
rayIntensity = new Vector2f();
texture = new Sprite(text);
visible = true;
size = DEFAULT_SIZE;
collisionable = c;
}
/**
* Returns the entity distance
* @return the entity distance
*/
public float getDistance() {
return distance;
}
/**
* Executes the collision of the entity with the player
* @return <code>true</code> if the entity collides with the player, <code>false</code> otherwise
*/
private boolean collision() {
if (!collisionable) {
return false;
}
float distX = Math.abs(Player.position.x - position.x);
float distY = Math.abs(Player.position.y - position.y);
if (distX < 0.3f && distY < 0.3f) {
Player.position.x = Player.old_position.x;
Player.position.y = Player.old_position.y;
}
return (distX < 0.3f && distY < 0.3f);
}
/**
* Returns <code>true</code> if the entity is visible by the player, <code>false</code> otherwise
* @param distance The distance between the entity and the player
* @return <code>true</code> if the entity is visible by the player, <code>false</code> otherwise
*/
private boolean inVision(float distance) {
float comparison_angle = (float) Math.cos(Math.atan2(position.x - Player.position.x,
position.y - Player.position.y));
int start = (int) (size / distance) * -Renderer.width;
for (int x = start; x < Renderer.width - start; x += 2) {
float ray_angle = (Player.angle - 0.5f) + ((float) x / Renderer.width);
if (Math.abs(Math.cos(ray_angle)-comparison_angle) < 0.01f && touchedByRay(ray_angle, x))
return true;
}
return false;
}
/**
* Returns <code>true</code> if the indicated ray touches the entity, <code>false</code> otherwise
* @param ray_angle The angle of the ray
* @param x the horizontal position in the screen
* @return <code>true</code> if the indicated ray touches the entity, <code>false</code> otherwise
*/
private boolean touchedByRay(float ray_angle, int x) {
float offset = 0.02f;
rayIntensity.x = (float) Math.sin(ray_angle) * offset;
rayIntensity.y = (float) Math.cos(ray_angle) * offset;
//Search entity
float ray_x = Player.position.x;
float ray_y = Player.position.y;
float tmp_distance = 0f;
while (tmp_distance < 40f) {
tmp_distance += offset;
ray_x += rayIntensity.x;
ray_y += rayIntensity.y;
if (Math.abs(ray_x - position.x) < offset && Math.abs(ray_y - position.y) < offset) {
in_vision = true;
break;
}
}
//Update variables
if (in_vision) {
distance = tmp_distance;
texture.setSize(-texture.getY() * size, -texture.getY() * size);
texture.setPosition((x - Renderer.centerX) - (texture.getWidth() / 2), -(Renderer.height / distance));
}
return in_vision;
}
/**
* Render the entity in the SpriteBatch
* @param batch the sprite batch
*/
public void Render(SpriteBatch batch) {
if (!visible || !in_vision || is_drawn) {
return;
}
texture.draw(batch);
is_drawn = true;
}
/**
* Update the entity in General
*/
public void update() {
in_vision = is_drawn = false;
distance = 0f;
float x1 = Player.position.x - position.x;
float y1 = Player.position.y - position.y;
float player_distance = (float) (Math.sqrt((x1*x1) + (y1*y1)));
inVision(player_distance);
collision();
}
} | 4,635 | Java | .java | Usbac/Rayce | 9 | 2 | 0 | 2018-06-29T23:14:46Z | 2020-05-12T14:58:21Z |
Main.java | /FileExtraction/Java_unseen/Usbac_Rayce/desktop/src/com/mygdx/game/desktop/Main.java | package com.mygdx.game.desktop;
import com.badlogic.gdx.*;
import static com.badlogic.gdx.Gdx.gl;
import com.badlogic.gdx.graphics.*;
import com.badlogic.gdx.graphics.g2d.*;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.maps.tiled.*;
import java.util.ArrayList;
public final class Main implements Screen {
Player player;
public final Base Base;
Renderer renderer;
//Camera
static SpriteBatch batch;
static ShapeRenderer shape_renderer;
static Camera camera;
//Map & Entities
TiledMapTileLayer[] floors;
ArrayList<Entity> entity;
public Main(Base base) {
Base = base;
player = Player.getInstance();
renderer = new Renderer();
//Batch & Camera
camera = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
shape_renderer = new ShapeRenderer();
shape_renderer.setProjectionMatrix(camera.combined);
batch = new SpriteBatch();
batch.setProjectionMatrix(camera.projection);
//Map
entity = new ArrayList<>();
floors = new TiledMapTileLayer[3];
TiledMap tmp_map = new TmxMapLoader().load("Mapa.tmx");
for (int i = 0; i < tmp_map.getLayers().getCount(); i++) {
floors[i] = (TiledMapTileLayer) tmp_map.getLayers().get(i);
}
initEntities();
}
/**
* Loads the entities of the map in the entity list
*/
private void initEntities() {
for (int x = 0; x < floors[1].getWidth(); x++) {
for (int y = 0; y < floors[1].getHeight(); y++) {
//Entities with collision
if (floors[1].getCell(x, y) != null) {
entity.add(new Entity(floors[1].getCell(x, y).getTile().getTextureRegion(), x, y, true));
}
//Entities without collision
if (floors[2].getCell(x, y) != null) {
entity.add(new Entity(floors[2].getCell(x, y).getTile().getTextureRegion(), x, y, false));
}
}
}
}
@Override
public void render(float f) {
gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
entity.forEach((aux) -> aux.update());
batch.begin();
renderer.render(batch, floors, entity);
player.update(this);
batch.end();
}
@Override
public void show() {}
@Override
public void resize(int i, int i1) {}
@Override
public void pause() {}
@Override
public void resume() {}
@Override
public void hide() {}
@Override
public void dispose() {}
}
| 2,803 | Java | .java | Usbac/Rayce | 9 | 2 | 0 | 2018-06-29T23:14:46Z | 2020-05-12T14:58:21Z |
Player.java | /FileExtraction/Java_unseen/Usbac_Rayce/desktop/src/com/mygdx/game/desktop/Player.java | package com.mygdx.game.desktop;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer;
import org.lwjgl.util.vector.Vector2f;
public final class Player {
static Vector2f position, old_position;
static float angle, delta;
private static float speed_movement, speed_lateral, speed_rotation;
static Player instance;
public Player() {
position = new Vector2f(10, 9);
old_position = new Vector2f(position.x, position.y);
angle = 5.75f;
speed_movement = 5;
speed_rotation = 1.7f;
speed_lateral = speed_movement / 2f;
}
//Singleton
public static Player getInstance() {
return instance = (instance == null) ? new Player() : instance;
}
/**
* Allows the rotation of the player
*/
public void rotation() {
if (Gdx.input.isKeyPressed(Input.Keys.D)) {
angle += speed_rotation * delta;
}
if (Gdx.input.isKeyPressed(Input.Keys.A)) {
angle -= speed_rotation * delta;
}
}
/**
* Adjusts the angle of the player if it goes outside of the circle
*/
public void adjustAngle() {
if (angle > Renderer.TWO_PI) {
angle = 0;
}
if (angle < 0) {
angle = Renderer.TWO_PI;
}
}
/**
* Allows the movement of the player
*/
public void movement() {
old_position.set(position);
float currentSpeedMovement = (delta * speed_movement);
float currentLateralSpeedMovement = (delta * speed_lateral);
if (Gdx.input.isKeyPressed(Input.Keys.W)) {
position.x += Math.sin(angle) * currentSpeedMovement;
position.y += Math.cos(angle) * currentSpeedMovement;
}
if (Gdx.input.isKeyPressed(Input.Keys.S)) {
position.x -= Math.sin(angle) * currentSpeedMovement;
position.y -= Math.cos(angle) * currentSpeedMovement;
}
if (Gdx.input.isKeyPressed(Input.Keys.RIGHT)) {
position.x += Math.sin(angle+Renderer.HALF_PI) * currentLateralSpeedMovement;
position.y += Math.cos(angle+Renderer.HALF_PI) * currentLateralSpeedMovement;
}
if (Gdx.input.isKeyPressed(Input.Keys.LEFT)) {
position.x += Math.sin(angle-Renderer.HALF_PI) * currentLateralSpeedMovement;
position.y += Math.cos(angle-Renderer.HALF_PI) * currentLateralSpeedMovement;
}
}
/**
* Blocks the movement of the player if its collides with a wall
* @param floor the floor to check the collision
*/
public void collision(TiledMapTileLayer floor) {
int actualX = (int) Math.floor(position.x),
actualY = (int) Math.floor(position.y);
if (floor.getCell((int)actualX, (int)actualY) != null) {
position.x = old_position.x;
position.y = old_position.y;
}
}
/**
* Updates the player in general
* @param e the main state
*/
public void update(Main e) {
delta = Gdx.graphics.getDeltaTime();
adjustAngle();
rotation();
movement();
collision(e.floors[0]);
}
} | 3,465 | Java | .java | Usbac/Rayce | 9 | 2 | 0 | 2018-06-29T23:14:46Z | 2020-05-12T14:58:21Z |
Renderer.java | /FileExtraction/Java_unseen/Usbac_Rayce/desktop/src/com/mygdx/game/desktop/Renderer.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mygdx.game.desktop;
import java.util.*;
import com.badlogic.gdx.*;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer;
import org.lwjgl.util.vector.Vector2f;
import java.util.ArrayList;
public class Renderer {
static final float ALMOSTZERO = 0.001f;
static final float TWO_PI = (float) (Math.PI * 2f);
static final float PI = (float) Math.PI;
static final float HALF_PI = (float) (Math.PI / 2f);
static final float THREEHALF_PI = (float) ((3f * Math.PI) / 2f);
static final int PRECISION = 1000;
Vector2f drawPosition, ray_intensity;
static int width, height, centerX, centerY;
//Raycasting
private float aX, aY, intersection_x, intersection_y;
private float tan, cotan;
private boolean horizontal;
private boolean collision_h, collision_v;
private float ray_x, ray_y;
private float ray_x_vertical, ray_y_vertical;
private float distance_h, distance_v;
private float darknest_level;
private Texture[] screen;
private float[] distances, texture_positions;
private float[] cotans, tans;
private enum ORIENTATION {
Vertical, Horizontal;
}
//Textures
Sprite floor, ceil;
Color floorColor, ceilColor;
public Renderer() {
setTrigonometryValues();
//Screen
width = Gdx.graphics.getWidth();
height = Gdx.graphics.getHeight();
centerX = width / 2;
centerY = height / 2;
darknest_level = 15f;
//RayCasting
drawPosition = new Vector2f();
ray_intensity = new Vector2f();
//Arrays
screen = new Texture[width];
distances = new float[width];
texture_positions = new float[width];
//Floor
floor = new Sprite(new Texture("degradado.png"));
floor.setSize(width, centerY);
floor.setPosition(-centerX, -centerY);
floorColor = new Color(Color.valueOf("311a12"));
floor.setColor(floorColor);
//Ceil
ceil = new Sprite(new Texture("degradado.png"));
ceil.setSize(width, centerY);
ceil.setPosition(-centerX, 0);
ceil.flip(false, true);
ceilColor = new Color(Color.valueOf("7f7f7f"));
ceil.setColor(ceilColor);
}
/**
* Returns the distance between the player and a point in the indicated position
* @param x the position in the horizontal axis
* @param y the position in the vertical axis
* @return the distance between the player and a point in the indicated position
*/
public float getRayDistance(float x, float y) {
float distanceX = Math.abs(x - Player.position.x);
float distanceY = Math.abs(y - Player.position.y);
return (float) Math.sqrt(distanceX * distanceX + distanceY * distanceY);
}
/**
* Adjust the ray angle if it goes outside of the circle
* @param ray_angle the angle of the ray
* @return the adjusted angle of the ray
*/
public float adjustRayAngle(float ray_angle) {
if (ray_angle > TWO_PI) {
ray_angle -= TWO_PI;
}
if (ray_angle < 0f) {
ray_angle += TWO_PI;
}
return ray_angle;
}
/**
* Returns the distance of the ray with the fixed fish eye effect
* @param distance the distance of the ray
* @param ray_angle the angle of the ray
* @return the distance with the fish eye effect fixed
*/
public float fixFishEyeEffect(float distance, float ray_angle) {
return (float) (distance * Math.cos(Player.angle - ray_angle));
}
/**
* Set the orientation of the current ray collision with a wall
*/
public void setCollisionOrientation() {
if (distance_v < distance_h) {
horizontal = false;
ray_x = ray_x_vertical;
ray_y = ray_y_vertical;
} else {
horizontal = true;
}
}
/**
* Populate the tangent and cotangent arrays with its respective values
*/
private void setTrigonometryValues() {
int length = (int) ((Math.PI * 2 + 0.1f) * PRECISION);
tans = new float[length];
cotans = new float[length];
for (int i = 0; i < length; i++) {
tans[i] = (float) Math.tan((float) i / PRECISION);
cotans[i] = (float) (1f / tans[i]);
}
}
/**
* Updates the values of the trigonometry variables
* based in the given angle of the ray
* @param ray_angle the angle of the ray
*/
private void updateTrigonometryValues(float ray_angle) {
int angle = (int) Math.abs(ray_angle * PRECISION);
tan = tans[angle];
cotan = cotans[angle];
}
/**
* Sorts the entity list by distance
* @param entities the list of entities
*/
private void sortListByDistance(ArrayList<Entity> entities) {
Collections.sort(entities, Comparator.comparing(Entity::getDistance).reversed());
}
/**
* Returns the index of the highest value in the array
* @param array the array
* @return the index of the highest value in the array
*/
private int getHigherValue(float[] array) {
int highestValueIndex = 0;
for (int i = 0; i < width; i++) {
if (array[i] >= array[highestValueIndex]) {
highestValueIndex = i;
}
}
return highestValueIndex;
}
/**
* Sets the luminosity of the Spritebatch for the indicated ray
* @param batch the sprite batch
* @param index the horizontal position of the ray in the Screen
*/
private void setRayLuminosity(SpriteBatch batch, int index) {
float luminosity = (darknest_level / distances[index]);
if (luminosity > 1f) {
luminosity = 1f;
}
batch.setColor(luminosity, luminosity, luminosity, 1);
}
/**
* Finds the intersection of a ray with a wall in the indicated angle
* @param floors the floors to check the intersection
* @param ray_angle the angle of the ray
*/
private void findIntersectionWalls(TiledMapTileLayer[] floors, float ray_angle) {
collision_h = collision_v = false;
ray_x = Player.position.x;
ray_y = Player.position.y;
ray_x_vertical = Player.position.x;
ray_y_vertical = Player.position.y;
distance_h = distance_v = 0f;
while (true) {
//HORIZONTAL Intersection
if (!collision_h) {
intersection_y = (float) Math.abs(ray_y - Math.floor(ray_y));
if (ray_angle < HALF_PI || ray_angle > THREEHALF_PI) {
intersection_y = 1f - intersection_y;
}
if (intersection_y < ALMOSTZERO) {
intersection_y = 1f;
}
aX = (float) (intersection_y * tan);
aY = intersection_y;
if (ray_angle < HALF_PI || ray_angle > THREEHALF_PI) {
ray_y += aY;
ray_x += aX;
if (floors[0].getCell((int) Math.floor(ray_x), (int) Math.floor(ray_y)) != null) {
collision_h = true;
}
} else {
ray_y -= aY;
ray_x -= aX;
if (floors[0].getCell((int) Math.floor(ray_x), (int) Math.floor(ray_y-1)) != null) {
collision_h = true;
}
}
distance_h = getRayDistance(ray_x, ray_y);
if (collision_v && (distance_h >= distance_v)) {
return;
}
}
//VERTICAL Intersection
if (!collision_v) {
intersection_x = (float) Math.abs(ray_x_vertical - Math.floor(ray_x_vertical));
if (ray_angle < PI) {
intersection_x = 1f - intersection_x;
}
if (intersection_x < ALMOSTZERO) {
intersection_x = 1f;
}
aY = (float) (intersection_x * (cotan));
aX = intersection_x;
if (ray_angle < PI) {
ray_y_vertical += aY;
ray_x_vertical += aX;
if (floors[0].getCell((int) Math.floor(ray_x_vertical), (int) Math.floor(ray_y_vertical)) != null) {
collision_v = true;
}
} else {
ray_y_vertical -= aY;
ray_x_vertical -= aX;
if (floors[0].getCell((int) Math.floor(ray_x_vertical - 1), (int) Math.floor(ray_y_vertical)) != null) {
collision_v = true;
}
}
distance_v = getRayDistance(ray_x_vertical, ray_y_vertical);
if (collision_h && (distance_h <= distance_v)) {
return;
}
}
if (collision_v && collision_h) {
return;
}
}
}
/**
* Renders all the map and the entities
* @param batch the sprite batch
* @param floors the floors to render
* @param entity the list of entities to render
*/
public void render(SpriteBatch batch, TiledMapTileLayer[] floors, ArrayList<Entity> entity) {
sortListByDistance(entity);
drawFloorCeil(batch);
RayCasting(floors);
generalRender(batch, entity);
}
/**
* Draws both the floor and the ceiling
* @param batch the sprite batch
*/
private void drawFloorCeil(SpriteBatch batch) {
floor.draw(batch);
ceil.draw(batch);
}
/**
* General function of RayCasting
* @param floors the floors to render
*/
private void RayCasting(TiledMapTileLayer[] floors) {
for (int x = 0; x < width; x++) {
float ray_angle = adjustRayAngle((Player.angle - 0.5f) + ((float) x / (float) width));
updateTrigonometryValues(ray_angle);
findIntersectionWalls(floors, ray_angle);
distances[x] = fixFishEyeEffect(Math.min(distance_v, distance_h), ray_angle);
setCollisionOrientation();
ORIENTATION wallOrientation = (ray_x - Math.floor(ray_x) < 0.01f) ?
ORIENTATION.Vertical : ORIENTATION.Horizontal;
float textureX = (float) (ray_x - Math.floor(ray_x)),
textureY = (float) (ray_y - Math.floor(ray_y));
texture_positions[x] = (wallOrientation == ORIENTATION.Vertical) ?
((textureX > 0.5f) ? textureY : 1 - textureY):
((textureY > 0.5f) ? 1 - textureX : textureX);
//Adjust Ray position in the map if the Ray angle is negative
if (horizontal && (ray_angle > HALF_PI && ray_angle < THREEHALF_PI)) {
ray_y--;
}
if (!horizontal && ray_angle > PI) {
ray_x--;
}
if (floors[0].getCell((int)ray_x, (int)ray_y) != null) {
screen[x] = floors[0].getCell((int)ray_x, (int)ray_y).getTile().getTextureRegion().getTexture();
}
}
}
/**
* Calls the render function for all the rays and entities in the Screen
* @param batch the sprite batch
* @param entity the list of entities to render
*/
private void generalRender(SpriteBatch batch, ArrayList<Entity> entity) {
for (int x = 0; x < width; x++) {
int mostDistant = getHigherValue(distances);
for (Entity aux: entity) {
if (aux.getDistance() > distances[mostDistant] || x == (width - 1)) {
aux.Render(batch);
}
}
setRayLuminosity(batch, mostDistant);
rayRender(batch, mostDistant);
distances[mostDistant] = 0;
}
}
/**
* Renders one single ray in the indicated index
* @param batch the sprite batch
* @param i the horizontal position of the ray in the Screen
*/
private void rayRender(SpriteBatch batch, int i) {
int floorPosition = (int) (centerY - height / distances[i]);
int wallHeight = height - (floorPosition * 2);
drawPosition.set(i - centerX, floorPosition - centerY);
batch.draw(screen[i], drawPosition.x, drawPosition.y, 1, wallHeight, texture_positions[i], 1, texture_positions[i] - 0.01f, 0);
}
}
| 13,416 | Java | .java | Usbac/Rayce | 9 | 2 | 0 | 2018-06-29T23:14:46Z | 2020-05-12T14:58:21Z |
ExampleUnitTest.java | /FileExtraction/Java_unseen/kartikhimself_Simple-Video-Player/app/src/test/java/com/sdcode/videoplayer/ExampleUnitTest.java | package com.sdcode.videoplayer;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
} | 383 | Java | .java | kartikhimself/Simple-Video-Player | 11 | 4 | 0 | 2019-07-03T02:35:28Z | 2019-07-02T15:42:27Z |
SettingsActivity.java | /FileExtraction/Java_unseen/kartikhimself_Simple-Video-Player/app/src/main/java/com/sdcode/videoplayer/SettingsActivity.java | package com.sdcode.videoplayer;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Switch;
import com.sdcode.videoplayer.customizeUI.WrapContentGridLayoutManager;
import com.sdcode.videoplayer.kxUtil.PreferencesUtility;
import com.sdcode.videoplayer.customizeUI.ThemeChoiceItem;
import com.sdcode.videoplayer.adapter.ThemeChoiceItemAdapter;
import java.util.ArrayList;
public class SettingsActivity extends BaseActivity {
Switch backgroundAudioSwitch ;
PreferencesUtility preferencesUtility;
GlobalVar mGlobalVar = GlobalVar.getInstance();
ThemeChoiceItemAdapter themeChoiceItemAdapter;
RecyclerView recyclerView;
int currentTheme ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
preferencesUtility = PreferencesUtility.getInstance(this);
currentTheme = preferencesUtility.getThemeSettings();
backgroundAudioSwitch = findViewById(R.id.backgroundAudioSwitch);
backgroundAudioSwitch.setChecked(preferencesUtility.isAllowBackgroundAudio());
backgroundAudioSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> {
if(isChecked) mGlobalVar.openNotification();
else mGlobalVar.closeNotification();
preferencesUtility.setAllowBackgroundAudio(isChecked);
});
if(getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
recyclerView = findViewById(R.id.recyclerView);
themeChoiceItemAdapter = new ThemeChoiceItemAdapter(this);
recyclerView.setLayoutManager(new WrapContentGridLayoutManager(this, 5));
recyclerView.setAdapter(themeChoiceItemAdapter);
themeChoiceItemAdapter.updateData(setupListData());
}
@Override
public boolean onSupportNavigateUp() {
if(preferencesUtility.getThemeSettings() == currentTheme)
finish();
else {
Intent intent = new Intent(SettingsActivity.this, FirstActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK );
startActivity(intent);
finish();
}
return true;
}
@Override
public void onBackPressed() {
if(preferencesUtility.getThemeSettings() == currentTheme)
super.onBackPressed();
else {
Intent intent = new Intent(SettingsActivity.this, FirstActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK );
startActivity(intent);
finish();
}
}
private ArrayList<ThemeChoiceItem> setupListData(){
ArrayList<ThemeChoiceItem> themeChoiceItems = new ArrayList<>();
themeChoiceItems.add(new ThemeChoiceItem(R.color.nice_green,0));
themeChoiceItems.add(new ThemeChoiceItem(R.color.nice_pink,1));
themeChoiceItems.add(new ThemeChoiceItem(R.color.nice_pink1,2));
themeChoiceItems.add(new ThemeChoiceItem(R.color.nice_pink2,3));
themeChoiceItems.add(new ThemeChoiceItem(R.color.nice_blue,4));
themeChoiceItems.add(new ThemeChoiceItem(R.color.nice_red,5));
themeChoiceItems.add(new ThemeChoiceItem(R.color.nice_pink3,6));
themeChoiceItems.add(new ThemeChoiceItem(R.color.nice_green1,7));
themeChoiceItems.add(new ThemeChoiceItem(R.color.nice_purple,8));
themeChoiceItems.add(new ThemeChoiceItem(R.color.nice_yellow,9));
return themeChoiceItems;
}
}
| 3,939 | Java | .java | kartikhimself/Simple-Video-Player | 11 | 4 | 0 | 2019-07-03T02:35:28Z | 2019-07-02T15:42:27Z |
GlobalVar.java | /FileExtraction/Java_unseen/kartikhimself_Simple-Video-Player/app/src/main/java/com/sdcode/videoplayer/GlobalVar.java | package com.sdcode.videoplayer;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.sdcode.videoplayer.folder.FolderItem;
import com.sdcode.videoplayer.videoService.VideoService;
import com.sdcode.videoplayer.video.VideoItem;
import java.util.ArrayList;
public class GlobalVar {
private static final GlobalVar ourInstance = new GlobalVar();
public static GlobalVar getInstance() {
return ourInstance;
}
private GlobalVar() {
}
public VideoItem playingVideo;
public VideoService videoService;
public boolean isMutilSelectEnalble = false;
public long seekPosition = 0;
public boolean isPlaying = true;
public boolean isNeedRefreshFolder = false;
public boolean isOpenFromIntent = false;
public ArrayList<VideoItem> videoItemsPlaylist = new ArrayList<>();
public ArrayList<VideoItem> allVideoItems = new ArrayList<>();
public FolderItem folderItem;
public boolean isSeekBarProcessing = false;
public String getPath(){
if(playingVideo != null)
return playingVideo.getPath();
return "77777777777";
}
public SimpleExoPlayer getPlayer(){
if(videoService == null)
return null;
return videoService.getVideoPlayer();
}
public boolean isPlayingAsPopup(){
if(videoService == null) return false;
return videoService.isPlayingAsPopup();
}
public void playNext(){
if(videoService == null) return;
videoService.handleAction(VideoService.NEXT_ACTION);
}
public void playPrevious(){
if(videoService == null) return;
videoService.handleAction(VideoService.PREVIOUS_ACTION);
}
public void closeNotification(){
if(videoService == null) return;
videoService.closeBackgroundMode();
}
public void openNotification(){
if(videoService == null) return;
videoService.openBackgroundMode();
}
public void pausePlay(){
if(videoService == null) return;
videoService.handleAction(VideoService.TOGGLEPAUSE_ACTION);
}
public void createShuffle(){
if(videoService == null) return;
videoService.createShuffleArray();
}
public int getCurrentPosition(){
if(videoService == null) return - 1;
return videoService.getCurrentPosition();
}
}
| 2,363 | Java | .java | kartikhimself/Simple-Video-Player | 11 | 4 | 0 | 2019-07-03T02:35:28Z | 2019-07-02T15:42:27Z |
AboutActivity.java | /FileExtraction/Java_unseen/kartikhimself_Simple-Video-Player/app/src/main/java/com/sdcode/videoplayer/AboutActivity.java | package com.sdcode.videoplayer;
import androidx.appcompat.widget.Toolbar;
import android.os.Bundle;
public class AboutActivity extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if(getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
}
}
| 608 | Java | .java | kartikhimself/Simple-Video-Player | 11 | 4 | 0 | 2019-07-03T02:35:28Z | 2019-07-02T15:42:27Z |
PlayerManager.java | /FileExtraction/Java_unseen/kartikhimself_Simple-Video-Player/app/src/main/java/com/sdcode/videoplayer/PlayerManager.java | package com.sdcode.videoplayer;
import android.content.Context;
import android.net.Uri;
import com.google.android.exoplayer2.ExoPlayerFactory;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory;
import com.google.android.exoplayer2.source.ExtractorMediaSource;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.trackselection.AdaptiveTrackSelection;
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;
import com.google.android.exoplayer2.trackselection.TrackSelection;
import com.google.android.exoplayer2.upstream.BandwidthMeter;
import com.google.android.exoplayer2.upstream.DataSource;
import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter;
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
import com.google.android.exoplayer2.util.Util;
public class PlayerManager{
GlobalVar mGlobalVar = GlobalVar.getInstance();
private SimpleExoPlayer simpleExoPlayer;
private DataSource.Factory mediaDataSourceFactory;
private DefaultTrackSelector trackSelector;
Context context;
public PlayerManager(Context context) {
this.context = context;
initExoPlayer();
}
public SimpleExoPlayer getCurrentPlayer(){
return simpleExoPlayer;
}
public SimpleExoPlayer getSimpleExoPlayer(){
return simpleExoPlayer;
}
private void initExoPlayer(){
BandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
mediaDataSourceFactory = new DefaultDataSourceFactory(context,
Util.getUserAgent(context, context.getString(R.string.app_name)));
TrackSelection.Factory videoTrackSelectionFactory =
new AdaptiveTrackSelection.Factory(bandwidthMeter);
trackSelector = new DefaultTrackSelector(videoTrackSelectionFactory);
simpleExoPlayer = ExoPlayerFactory.newSimpleInstance(context, trackSelector);
simpleExoPlayer.setPlayWhenReady(true);
}
public void prepare(boolean resetPosition, boolean resetState){
DefaultExtractorsFactory extractorsFactory = new DefaultExtractorsFactory();
// MediaSource mediaSource = new ExtractorMediaSource(Uri.parse(GlobalVar.getInstance().getPath()),
// mediaDataSourceFactory, extractorsFactory, null, null);
MediaSource mediaSource = new ExtractorMediaSource.Factory(mediaDataSourceFactory).setExtractorsFactory(extractorsFactory)
.createMediaSource(Uri.parse(GlobalVar.getInstance().getPath()));
simpleExoPlayer.prepare(mediaSource, resetPosition, resetState);
}
public boolean getPlayWhenReady(){
if(simpleExoPlayer == null)
return false;
return simpleExoPlayer.getPlayWhenReady();
}
public void setPlayWhenReady(boolean value){
if(simpleExoPlayer == null) return;
simpleExoPlayer.setPlayWhenReady(value);
}
public void setVolume(float volume){
if(simpleExoPlayer == null ) return;
simpleExoPlayer.setVolume(volume);
}
public void onFullScreen() {
if (simpleExoPlayer == null) return;
mGlobalVar.seekPosition = simpleExoPlayer.getCurrentPosition();
mGlobalVar.isPlaying = simpleExoPlayer.getPlayWhenReady();
}
public void releasePlayer(){
if (simpleExoPlayer != null) {
simpleExoPlayer.release();
simpleExoPlayer = null;
trackSelector = null;
}
}
// private static MediaQueueItem buildMediaQueueItem(VideoItem videoItem) {
// String type = MimeTypes.BASE_TYPE_VIDEO + "/" + kxUtils.getFileExtension(videoItem.getPath());
// MediaMetadata movieMetadata = new MediaMetadata(MediaMetadata.MEDIA_TYPE_TV_SHOW);
// movieMetadata.putString(MediaMetadata.KEY_TITLE, videoItem.getVideoTitle());
// MediaInfo mediaInfo = new MediaInfo.Builder(videoItem.getPath())
// .setStreamType(MediaInfo.STREAM_TYPE_NONE).setContentType(type)
// .setMetadata(movieMetadata).build();
// return new MediaQueueItem.Builder(mediaInfo).build();
// }
}
| 4,219 | Java | .java | kartikhimself/Simple-Video-Player | 11 | 4 | 0 | 2019-07-03T02:35:28Z | 2019-07-02T15:42:27Z |
FolderDetailActivity.java | /FileExtraction/Java_unseen/kartikhimself_Simple-Video-Player/app/src/main/java/com/sdcode/videoplayer/FolderDetailActivity.java | package com.sdcode.videoplayer;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import androidx.appcompat.widget.Toolbar;
import com.sdcode.videoplayer.fragment.FragmentVideoList;
import com.sdcode.videoplayer.kxUtil.PreferencesUtility;
import com.sdcode.videoplayer.video.VideoItem;
import java.util.ArrayList;
public class FolderDetailActivity extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
currentFragment = new FragmentVideoList();
setContentView(R.layout.activity_folder_detail);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,currentFragment).commit();
if(getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
if(mGlobalVar.folderItem != null && mGlobalVar.folderItem.getFolderName() != null)
setActionBar(mGlobalVar.folderItem.getFolderName());
}
@Override
public boolean onSupportNavigateUp() {
if(!mGlobalVar.isMutilSelectEnalble)
finish();
else releaseUI();
return true;
}
@Override
public void onResume(){
super.onResume();
if(mGlobalVar.isNeedRefreshFolder){
currentFragment = new FragmentVideoList();
}
}
@Override
public void onBackPressed() {
if(!mGlobalVar.isMutilSelectEnalble)
super.onBackPressed();
else releaseUI();
}
@Override
public void updateMultiSelectedState(){
if(currentFragment == null) return;
int totalVideoSelected = currentFragment.getTotalSelected();
if(totalVideoSelected == 0){
releaseUI();
}else {
if (getSupportActionBar() != null) {
getSupportActionBar().setTitle(String.valueOf(totalVideoSelected)+ " " + getString(R.string.video));
}
}
}
@Override
public void updateListAfterDelete(ArrayList<VideoItem> videoItems){
if(currentFragment == null) return;
currentFragment.updateVideoList(videoItems);
}
private void releaseUI(){
mGlobalVar.isMutilSelectEnalble = false;
setActionBar(mGlobalVar.folderItem.getFolderName());
if(currentFragment != null)currentFragment.releaseUI();
}
public void setActionBar(String title){
if(getSupportActionBar()!=null)
getSupportActionBar().setTitle(title);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.clear();
if(!mGlobalVar.isMutilSelectEnalble){
if(PreferencesUtility.getInstance(FolderDetailActivity.this).isAlbumsInGrid())
getMenuInflater().inflate(R.menu.first, menu);
else
getMenuInflater().inflate(R.menu.first1, menu);
}else {
getMenuInflater().inflate(R.menu.menu_multiselected_option, menu);
}
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
if(!mGlobalVar.isMutilSelectEnalble){
if(PreferencesUtility.getInstance(FolderDetailActivity.this).isAlbumsInGrid())
getMenuInflater().inflate(R.menu.first, menu);
else
getMenuInflater().inflate(R.menu.first1, menu);
}else {
getMenuInflater().inflate(R.menu.menu_multiselected_option, menu);
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
Handler handler = new Handler();
//noinspection SimplifiableIfStatement
if(id == R.id.action_view_list){
PreferencesUtility.getInstance(FolderDetailActivity.this).setAlbumsInGrid(false);
currentFragment = new FragmentVideoList();
handler.postDelayed(() -> getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,currentFragment).commit(), 500);
} if(id == R.id.action_view_grid) {
PreferencesUtility.getInstance(FolderDetailActivity.this).setAlbumsInGrid(true);
currentFragment = new FragmentVideoList();
handler.postDelayed(() -> getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, currentFragment).commit(), 500);
} if(id == R.id.action_play){
currentFragment.playItemSelected();
releaseUI();
}else if(id == R.id.action_share){
currentFragment.shareSelected();
}else if(id == R.id.action_delete){
currentFragment.deleteSelected();
}else if(id == R.id.menu_sort_by_az){
currentFragment.sortAZ();
}else if(id == R.id.menu_sort_by_za){
currentFragment.sortZA();
}else if(id == R.id.menu_sort_by_size){
currentFragment.sortSize();
}else if(id == R.id.action_go_to_playing){
if (mGlobalVar.videoService == null || mGlobalVar.playingVideo == null) {
Toast.makeText(this, getString(R.string.no_video_playing), Toast.LENGTH_SHORT).show();
return false;
}
final Intent intent = new Intent(FolderDetailActivity.this, PlayVideoActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_in_left,
R.anim.slide_stay_x);
}
return false;
}
}
| 5,835 | Java | .java | kartikhimself/Simple-Video-Player | 11 | 4 | 0 | 2019-07-03T02:35:28Z | 2019-07-02T15:42:27Z |
PlayVideoActivity.java | /FileExtraction/Java_unseen/kartikhimself_Simple-Video-Player/app/src/main/java/com/sdcode/videoplayer/PlayVideoActivity.java | package com.sdcode.videoplayer;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.Point;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.github.rubensousa.previewseekbar.PreviewView;
import com.github.rubensousa.previewseekbar.exoplayer.PreviewTimeBar;
import com.google.android.exoplayer2.Player;
import com.google.android.exoplayer2.ui.PlayerControlView;
import com.google.android.exoplayer2.ui.TimeBar;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import com.alexvasilkov.gestures.views.GestureFrameLayout;
import com.google.android.exoplayer2.ui.AspectRatioFrameLayout;
import com.google.android.exoplayer2.ui.PlayerView;
import com.sdcode.videoplayer.customizeUI.PlayPauseDrawable;
import com.sdcode.videoplayer.customizeUI.WrapContentLinearLayoutManager;
import com.sdcode.videoplayer.kxUtil.PreferencesUtility;
import com.sdcode.videoplayer.kxUtil.kxUtils;
import com.sdcode.videoplayer.adapter.VideoPlayingListAdapter;
import com.sdcode.videoplayer.video.VideoItem;
import net.cachapa.expandablelayout.ExpandableLayout;
import net.steamcrafted.materialiconlib.MaterialDrawableBuilder;
import net.steamcrafted.materialiconlib.MaterialIconView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
public class PlayVideoActivity extends AppCompatActivity implements PreviewView.OnPreviewChangeListener {
private VideoItem currentVideo = new VideoItem();
private int currentVideoPosition = - 999;
GlobalVar mGlobalVar = GlobalVar.getInstance();
private PlayerView mPlayerView;
Runnable r;
private boolean isVideoPlaying = false;
private static final int CONTROL_HIDE_TIMEOUT = 3000;
private long lastTouchTime;
PlayPauseDrawable playPauseDrawable = new PlayPauseDrawable();
FloatingActionButton btnPausePlay;
GestureFrameLayout gestureFrameLayout;
FrameLayout frameLayout_preview;
RelativeLayout layout_all_control_container,layout_region_volume, layout_region_brightness;
RelativeLayout layout_control_top, layout_btn_bottom, layout_skip_next_10, layout_skip_back_10;
private ExpandableLayout expandableLayout, expandableRecyclerView;
MaterialIconView btnExpandLayout, btnRotation,btnVolume,btnBrightness, btnPopupMode, btnClosePlaylist;
MaterialIconView btn_fwb,btn_fwn,btn_next_video,btn_pre_video,btnLockControl,btnChangeMode,btnEnableAllControl,btnBackgroundAudio,btn_repeatMode;
int fullMode, currentMode;
boolean isControlLocked = false;
SeekBar seekBarVolume,seekBarBrightness;
RequestOptions options;
PreviewTimeBar previewTimeBar;
PlayerControlView playerControlView;
ImageView preViewImage;
Point screenSize;
Toolbar toolbar;
VideoPlayingListAdapter videoPlayingListAdapter;
RecyclerView recyclerView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_video);
fullMode = AspectRatioFrameLayout.RESIZE_MODE_FILL;
currentMode = AspectRatioFrameLayout.RESIZE_MODE_FIT;
screenSize = getScreenSize();
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if(getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
initializePlayer();
initControlView();
}
@Override
public boolean onSupportNavigateUp() {
super.onBackPressed();
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.more_option, menu);
// CastButtonFactory.setUpMediaRouteButton(this, menu, R.id.media_route_menu_item);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == R.id.action_menu){
if(expandableRecyclerView!= null) {
expandableRecyclerView.toggle();
hideSystemUi();
}
}else if(id == R.id.action_info){
if(mGlobalVar.playingVideo != null)
createDialog(mGlobalVar.playingVideo);
}else if(id == R.id.action_share){
if(mGlobalVar.playingVideo != null)
startActivity(Intent.createChooser(kxUtils.shareVideo(PlayVideoActivity.this, mGlobalVar.playingVideo),
getString(R.string.action_share)));
}
return false;
// else if(id == R.id.action_delete){
// if(videoPlayingListAdapter != null && mGlobalVar.playingVideo != null)
// videoPlayingListAdapter.deleteVideo(mGlobalVar.playingVideo);
// }
}
private void initializePlayer() {
playerControlView = findViewById(R.id.player_control_view);
playerControlView.setVisibilityListener(visibility -> {
if(visibility == PlayerControlView.GONE){
toolbar.setVisibility(View.GONE);
hideSystemUi();
if(layout_region_volume != null) layout_region_volume.setVisibility(View.GONE);
if(layout_region_brightness != null) layout_region_brightness.setVisibility(View.GONE);
// if(expandableLayout != null && expandableTitleLayout != null)
// if(expandableLayout.isExpanded()){
// expandableTitleLayout.toggle();
// expandableLayout.toggle();
// }
}
if(visibility == PlayerControlView.VISIBLE){
toolbar.setVisibility(View.VISIBLE);
delayHideControl();
showSystemUI();
}
});
playerControlView.setOnClickListener(v -> playerControlView.hide());
playerControlView.setPlayer(mGlobalVar.getPlayer());
mPlayerView = findViewById(R.id.player_view);
mPlayerView.requestFocus();
if(mGlobalVar.getPlayer() == null)
return;
mPlayerView.setPlayer(mGlobalVar.getPlayer());
mPlayerView.setResizeMode(currentMode);
}
private void initControlView(){
btn_repeatMode = findViewById(R.id.btn_repeatMode);
if(mGlobalVar.getPlayer() == null) return;
setRepeatModeIcon();
btn_repeatMode.setOnClickListener(v -> {
if(mGlobalVar.getPlayer().getShuffleModeEnabled()){
mGlobalVar.getPlayer().setShuffleModeEnabled(false);
mGlobalVar.getPlayer().setRepeatMode(Player.REPEAT_MODE_ALL);
btn_repeatMode.setIcon(MaterialDrawableBuilder.IconValue.REPEAT);
}
else if(mGlobalVar.getPlayer().getRepeatMode() == Player.REPEAT_MODE_ALL){
mGlobalVar.getPlayer().setRepeatMode(Player.REPEAT_MODE_ONE);
btn_repeatMode.setIcon(MaterialDrawableBuilder.IconValue.REPEAT_ONCE);
}else if(mGlobalVar.getPlayer().getRepeatMode() == Player.REPEAT_MODE_ONE){
mGlobalVar.getPlayer().setRepeatMode(Player.REPEAT_MODE_OFF);
btn_repeatMode.setIcon(MaterialDrawableBuilder.IconValue.REPEAT_OFF);
}else {
mGlobalVar.getPlayer().setShuffleModeEnabled(true);
btn_repeatMode.setIcon(MaterialDrawableBuilder.IconValue.SHUFFLE);
}
});
btnBackgroundAudio = findViewById(R.id.btn_bgAudio);
btnBackgroundAudio.setColor(PreferencesUtility.getInstance(this).isAllowBackgroundAudio() ? Color.GREEN : Color.WHITE);
btnBackgroundAudio.setOnClickListener(v -> {
if(PreferencesUtility.getInstance(PlayVideoActivity.this).isAllowBackgroundAudio())
mGlobalVar.closeNotification();
else mGlobalVar.openNotification();
PreferencesUtility.getInstance(PlayVideoActivity.this).setAllowBackgroundAudio(!PreferencesUtility.getInstance(this).isAllowBackgroundAudio());
btnBackgroundAudio.setColor(PreferencesUtility.getInstance(PlayVideoActivity.this).isAllowBackgroundAudio() ? Color.GREEN : Color.WHITE);
});
btnRotation = findViewById(R.id.btn_btnRotation);
btnRotation.setOnClickListener(v -> {
int requestScreenInfo = getRequestedOrientation();
if(requestScreenInfo == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT || requestScreenInfo == ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT){
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
}else if(requestScreenInfo == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE||requestScreenInfo == ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE){
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);
}else if(requestScreenInfo == ActivityInfo.SCREEN_ORIENTATION_SENSOR || requestScreenInfo == ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR){
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
}
updateScreenOrientationIco(getRequestedOrientation());
});
int defaultOrientation = PreferencesUtility.getInstance(this).getScreenOrientation();
setScreenOrientation(defaultOrientation);
seekBarBrightness = findViewById(R.id.seekBar_brightness);
seekBarBrightness.setMax(100);
seekBarBrightness.setProgress(getCurrentBrightness());
seekBarBrightness.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if(fromUser) {
delayHideControl();
changeBrightness(progress);
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
seekBarVolume = findViewById(R.id.seekBar_volume);
if(getMaxVolume() >= -1) {
seekBarVolume.setMax(getMaxVolume());
seekBarVolume.setProgress(getStreamVolume());
}
seekBarVolume.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if(fromUser) {
setVolume(progress);
delayHideControl();
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
btnBrightness = findViewById(R.id.btnBrightness);
btnBrightness.setOnClickListener(v -> {
if(layout_region_brightness!= null) layout_region_brightness.setVisibility(View.VISIBLE);
if(layout_region_volume!= null) layout_region_volume.setVisibility(View.GONE);
delayHideControl();
});
btnVolume = findViewById(R.id.btnVolumes);
btnVolume.setOnClickListener(v -> {
if(layout_region_volume!= null) layout_region_volume.setVisibility(View.VISIBLE);
if(layout_region_brightness!= null) layout_region_brightness.setVisibility(View.GONE);
delayHideControl();
});
layout_control_top = findViewById(R.id.layout_title_top);
btnPopupMode = findViewById(R.id.btn_popup);
btnPopupMode.setOnClickListener(v -> {
showFloatingView(PlayVideoActivity.this,true);
});
btnExpandLayout = findViewById(R.id.btn_btnExpandControl);
btnExpandLayout.setOnClickListener(v -> {
delayHideControl();
if(expandableLayout != null) expandableLayout.toggle();
});
gestureFrameLayout = findViewById(R.id.frame_item_layout);
expandableLayout = findViewById(R.id.expandable_layout);
expandableLayout.setOnExpansionUpdateListener((expansionFraction, state) -> btnExpandLayout.setRotation(expansionFraction * 180));
layout_region_volume = findViewById(R.id.region_volume);
layout_region_brightness = findViewById(R.id.region_brightness);
btnEnableAllControl = findViewById(R.id.btnEnableAllControl);
btnEnableAllControl.setOnClickListener(v -> {
btnEnableAllControl.setVisibility(View.GONE);
isControlLocked = false;
showControl();
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);
updateScreenOrientationIco(getRequestedOrientation());
});
/// bot control
layout_skip_back_10 = findViewById(R.id.layout_skip_pre_10s);
layout_skip_next_10 = findViewById(R.id.layout_skip_next_10s);
frameLayout_preview = findViewById(R.id.previewFrameLayout);
preViewImage = findViewById(R.id.preImageView);
previewTimeBar = findViewById(R.id.previewTimebar);
previewTimeBar.addListener(new TimeBar.OnScrubListener() {
@Override
public void onScrubStart(TimeBar timeBar, long position) {
mGlobalVar.isSeekBarProcessing = true;
delayHideControl();
}
@Override
public void onScrubMove(TimeBar timeBar, long position) {
delayHideControl();
}
@Override
public void onScrubStop(TimeBar timeBar, long position, boolean canceled) {
mGlobalVar.getPlayer().seekTo(position);
previewTimeBar.setPosition(position);
delayHideControl();
}
});
previewTimeBar.setPreviewLoader((currentPosition, max) -> {
if(preViewImage != null)
options = new RequestOptions().frame(currentPosition*1000);
Glide.with(PlayVideoActivity.this)
.load(mGlobalVar.playingVideo.getPath())
.override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
.apply(options)
.into(preViewImage);
});
previewTimeBar.addOnPreviewChangeListener(this);
layout_btn_bottom = findViewById(R.id.layout_btn_bot);
btnPausePlay = findViewById(R.id.btnPlayPause);
btnPausePlay.setImageDrawable(playPauseDrawable);
if (mGlobalVar.getPlayer().getPlayWhenReady()) {
playPauseDrawable.transformToPause(true);
} else {
playPauseDrawable.transformToPlay(true);
}
btnPausePlay.setOnClickListener(v -> {
delayHideControl();
if(mGlobalVar.getPlayer()!= null) {
isVideoPlaying = !mGlobalVar.getPlayer().getPlayWhenReady();
mGlobalVar.pausePlay();
playPauseDrawable.transformToPlay(true);
playPauseDrawable.transformToPause(true);
}
});
btnChangeMode = findViewById(R.id.btnResize);
btnChangeMode.setOnClickListener(v -> {
delayHideControl();
currentMode += 1;
if(currentMode > 4)
currentMode = 0;
mPlayerView.setResizeMode(currentMode);
});
btn_fwb = findViewById(R.id.btn_skip_pre_10s);
btn_fwb.setOnClickListener(v -> {
long currentPostion = mGlobalVar.getPlayer().getCurrentPosition();
if(currentPostion - 10*1000 < 0) currentPostion = 0;
mGlobalVar.getPlayer().seekTo(currentPostion - 10000);
});
btn_fwn = findViewById(R.id.btn_skip_next_10s);
btn_fwn.setOnClickListener(v -> {
long currentPosition = mGlobalVar.getPlayer().getCurrentPosition();
if(currentPosition + 10*1000 < mGlobalVar.getPlayer().getDuration())
mGlobalVar.getPlayer().seekTo(currentPosition + 10000);
});
btn_next_video = findViewById(R.id.btn_skip_next);
btn_next_video.setOnClickListener(v ->{
mGlobalVar.playNext();
});
btn_pre_video = findViewById(R.id.btn_skip_pre);
btn_pre_video.setOnClickListener(v -> {
mGlobalVar.playPrevious();
});
btnLockControl = findViewById(R.id.btnLock);
btnLockControl.setOnClickListener(v -> {
if(layout_all_control_container != null && btnEnableAllControl != null) {
isControlLocked = true;
if(playerControlView != null) playerControlView.hide();
btnEnableAllControl.setVisibility(View.VISIBLE);
int currentOrientation = getCurrentOrientation();
if(currentOrientation == Configuration.ORIENTATION_LANDSCAPE){
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
}else if(currentOrientation == Configuration.ORIENTATION_PORTRAIT){
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
}
updateScreenOrientationIco(getRequestedOrientation());
}
});
/// container control
layout_all_control_container = findViewById(R.id.layout_all_control_container);
r = new Runnable() {
@Override
public void run() {
if (System.currentTimeMillis() - lastTouchTime > CONTROL_HIDE_TIMEOUT) {
hideControlContainer();
}
layout_all_control_container.postDelayed(this, 500);
if(mGlobalVar.getPlayer() != null){
if(mGlobalVar.getPlayer().getPlayWhenReady() != isVideoPlaying){
isVideoPlaying = mGlobalVar.getPlayer().getPlayWhenReady();
if(getSupportActionBar() != null) getSupportActionBar().setTitle(mGlobalVar.playingVideo.getVideoTitle());
if (isVideoPlaying)
playPauseDrawable.transformToPause(false);
else playPauseDrawable.transformToPlay(false);
}
if(previewTimeBar != null){
if(currentVideo != mGlobalVar.playingVideo && mGlobalVar.getPlayer().getPlaybackState() == Player.STATE_READY){
if(getSupportActionBar() != null) getSupportActionBar().setTitle(mGlobalVar.playingVideo.getVideoTitle());
currentVideo = mGlobalVar.playingVideo;
previewTimeBar.setDuration(mGlobalVar.getPlayer().getDuration());
}else if(!mGlobalVar.isSeekBarProcessing) {
previewTimeBar.setPosition(mGlobalVar.getPlayer().getCurrentPosition());
//Toast.makeText(PlayVideoActivity.this,"update seek",Toast.LENGTH_SHORT).show();
}
}
if(currentVideoPosition != mGlobalVar.getCurrentPosition()){
currentVideoPosition = mGlobalVar.getCurrentPosition();
if(currentVideoPosition >= 0 && currentVideoPosition < mGlobalVar.videoItemsPlaylist.size())
recyclerView.smoothScrollToPosition(currentVideoPosition);
}
}
}
};
layout_all_control_container.postDelayed(r,500);
layout_all_control_container.setOnClickListener(v ->
showControl()
);
recyclerView = findViewById(R.id.recyclerView_playlist);
recyclerView.setLayoutManager(new WrapContentLinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
videoPlayingListAdapter = new VideoPlayingListAdapter(this);
recyclerView.setAdapter(videoPlayingListAdapter);
videoPlayingListAdapter.updateData(mGlobalVar.videoItemsPlaylist);
if(currentVideoPosition != mGlobalVar.getCurrentPosition()){
currentVideoPosition = mGlobalVar.getCurrentPosition();
if(currentVideoPosition >= 0 && currentVideoPosition < mGlobalVar.videoItemsPlaylist.size())
recyclerView.smoothScrollToPosition(currentVideoPosition);
}
expandableRecyclerView = findViewById(R.id.expandable_recyclerView_layout);
btnClosePlaylist = findViewById(R.id.btn_CloseList);
btnClosePlaylist.setOnClickListener(v -> {
if(expandableRecyclerView != null)
expandableRecyclerView.toggle();
});
doLayoutChange(getCurrentOrientation());
}
private void setRepeatModeIcon(){
if(mGlobalVar.getPlayer() == null) return;
if(mGlobalVar.getPlayer().getShuffleModeEnabled()){
btn_repeatMode.setIcon(MaterialDrawableBuilder.IconValue.SHUFFLE);
}
else if(mGlobalVar.getPlayer().getRepeatMode() == Player.REPEAT_MODE_OFF){
btn_repeatMode.setIcon(MaterialDrawableBuilder.IconValue.REPEAT_OFF);
}else if(mGlobalVar.getPlayer().getRepeatMode() == Player.REPEAT_MODE_ONE){
btn_repeatMode.setIcon(MaterialDrawableBuilder.IconValue.REPEAT_ONCE);
}else {
btn_repeatMode.setIcon(MaterialDrawableBuilder.IconValue.REPEAT);
}
}
private void changeBrightness(int value){
if(value <= 5) value = 5;
WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
layoutParams.screenBrightness = (float) value/100;
getWindow().setAttributes(layoutParams);
}
private int getCurrentBrightness(){
try {
return Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
return 70;
}
}
boolean isVolumeVisible = false;
private int getMaxVolume(){
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
int volumeStreamMax = 0;
try {
if (audioManager != null)
volumeStreamMax = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
if (volumeStreamMax < 1)
volumeStreamMax = 1;
isVolumeVisible = true;
} catch (Throwable ex) {
isVolumeVisible = false;
ex.printStackTrace();
return -1;
}
return volumeStreamMax;
}
public void setVolume(int volume) {
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
int oldVolume = getStreamVolume();
try {
if (audioManager != null)
audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, (volume >= oldVolume) ? AudioManager.ADJUST_RAISE : AudioManager.ADJUST_LOWER, 0);
} catch (Throwable ex) {
//too bad...
}
//apparently a few devices don't like to have the streamVolume changed from another thread....
//maybe there is another reason for why it fails... I just haven't found yet :(
try {
if (audioManager != null)
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, volume, 0);
} catch (Throwable ex) {
//too bad...
}
}
private int getStreamVolume(){
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
if(audioManager!=null)
return audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
return 0;
}
private void setScreenOrientation(int value){
setRequestedOrientation(value);
updateScreenOrientationIco(value);
}
private void updateScreenOrientationIco(int value){
if(btnRotation != null) {
if (value == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE || value == ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE) {
btnRotation.setIcon(MaterialDrawableBuilder.IconValue.PHONE_ROTATE_LANDSCAPE);
} else if (value == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT || value == ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT) {
btnRotation.setIcon(MaterialDrawableBuilder.IconValue.PHONE_ROTATE_PORTRAIT);
} else if (value == ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR || value == ActivityInfo.SCREEN_ORIENTATION_SENSOR) {
btnRotation.setIcon(MaterialDrawableBuilder.IconValue.SCREEN_ROTATION);
}
}
PreferencesUtility.getInstance(this).setScreenOrientation(value);
}
private void hideControlContainer(){
if(!isControlLocked) {
if (playerControlView != null)
playerControlView.hide();
if(layout_region_volume != null) layout_region_volume.setVisibility(View.GONE);
if(layout_region_brightness != null) layout_region_brightness.setVisibility(View.GONE);
}else
if(btnEnableAllControl != null)
btnEnableAllControl.setVisibility(View.GONE);
}
private void delayHideControl(){
lastTouchTime = System.currentTimeMillis();
}
private void showControl(){
delayHideControl();
if(!isControlLocked) {
if (playerControlView != null) playerControlView.show();
}else
if(btnEnableAllControl != null)
btnEnableAllControl.setVisibility(View.VISIBLE);
}
@Override
public void onConfigurationChanged(@NonNull Configuration newConfig) {
super.onConfigurationChanged(newConfig);
doLayoutChange(newConfig.orientation);
// Checking the orientation of the screen
}
private void doLayoutChange(int orientation) {
if(orientation == Configuration.ORIENTATION_PORTRAIT){
if(layout_skip_back_10 != null) layout_skip_back_10.setVisibility(View.GONE);
if(layout_skip_next_10 != null) layout_skip_next_10.setVisibility(View.GONE);
if(toolbar != null){
ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) toolbar.getLayoutParams();
params.setMarginEnd(10*(int)getDensity());
}
if(btnExpandLayout != null){
ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) btnExpandLayout.getLayoutParams();
params.setMarginEnd(10*(int)getDensity());
}
}else if(orientation == Configuration.ORIENTATION_LANDSCAPE){
if(toolbar != null){
ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) toolbar.getLayoutParams();
params.setMarginEnd(50*(int)getDensity());
}
if(btnExpandLayout != null){
ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) btnExpandLayout.getLayoutParams();
params.setMarginEnd(50*(int)getDensity());
}
if(layout_skip_back_10 != null) layout_skip_back_10.setVisibility(View.VISIBLE);
if(layout_skip_next_10 != null) layout_skip_next_10.setVisibility(View.VISIBLE);
}
}
private float getDensity(){
DisplayMetrics metrics = getResources().getDisplayMetrics();
return (metrics.density);
}
private int getCurrentOrientation(){
return getResources().getConfiguration().orientation;
}
private void releasePlayer() {
}
private Point getScreenSize(){
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
return size;
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public void onStop(){
super.onStop();
if(!PreferencesUtility.getInstance(this).isAllowBackgroundAudio() && !isPopupModeEnalbe){
if(mGlobalVar.getPlayer()!= null && mGlobalVar.getPlayer().getPlayWhenReady()) {
mGlobalVar.pausePlay();
}
}
isPopupModeEnalbe = false;
}
@Override
public void onResume(){
super.onResume();
if(layout_all_control_container != null)
layout_all_control_container.postDelayed(r,500);
}
@Override
public void onPause(){
super.onPause();
releasePlayer();
if(layout_all_control_container != null)
layout_all_control_container.removeCallbacks(r);
}
boolean isPopupModeEnalbe = false;
public void startPopupMode() {
GlobalVar.getInstance().videoService.playVideo(mGlobalVar.seekPosition,true);
isPopupModeEnalbe = true;
finish();
}
int requestCode = 1;
@Override
@TargetApi(Build.VERSION_CODES.M)
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (this.requestCode == resultCode) {
startPopupMode();
}
}
@SuppressLint("NewApi")
public void showFloatingView(Context context, boolean isShowOverlayPermission) {
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP_MR1) {
startPopupMode();
return;
}
if (Settings.canDrawOverlays(context)) {
startPopupMode();
return;
}
if (isShowOverlayPermission) {
final Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + context.getPackageName()));
startActivityForResult(intent, requestCode);
}
}
private void showSystemUI(){
getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
}
private void hideSystemUi(){
getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
| View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
| View.SYSTEM_UI_FLAG_IMMERSIVE);
}
// public static void setAutoOrientationEnabled(Context context, boolean enabled)
// {
// Settings.System.putInt( context.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, enabled ? 1 : 0);
// }
// public boolean isAutoRotationState(){
// if (android.provider.Settings.System.getInt(getContentResolver(),
// Settings.System.ACCELEROMETER_ROTATION, 0) == 1)
// return true;
//
// return false;
// }
@Override
public void onStartPreview(PreviewView previewView, int progress) {
}
@Override
public void onStopPreview(PreviewView previewView, int progress) {
}
@Override
public void onPreview(PreviewView previewView, int progress, boolean fromUser) {
}
private void createDialog(VideoItem videoItem){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.content_video_info,null);
TextView txtVideoTitle = view.findViewById(R.id.txtVideoTitle);
txtVideoTitle.setText(videoItem.getVideoTitle());
TextView txtLocation = view.findViewById(R.id.txtLocation_value);
txtLocation.setText(videoItem.getPath());
TextView txtVideoFormat = view.findViewById(R.id.txtFormat_value);
txtVideoFormat.setText(kxUtils.getFileExtension(videoItem.getPath()));
TextView txtDuration = view.findViewById(R.id.txtDuration_value);
txtDuration.setText(videoItem.getDuration());
TextView txtDateAdded = view.findViewById(R.id.txtDateAdded_value);
txtDateAdded.setText(videoItem.getDate_added());
TextView txtVideoSize = view.findViewById(R.id.txtFileSize_value);
txtVideoSize.setText(videoItem.getFileSize());
TextView txtVideoResolution = view.findViewById(R.id.txResolution_value);
txtVideoResolution.setText(videoItem.getResolution());
builder.setView(view);
AlertDialog dialog = builder.create();
dialog.show();
}
}
| 33,682 | Java | .java | kartikhimself/Simple-Video-Player | 11 | 4 | 0 | 2019-07-03T02:35:28Z | 2019-07-02T15:42:27Z |
KxApp.java | /FileExtraction/Java_unseen/kartikhimself_Simple-Video-Player/app/src/main/java/com/sdcode/videoplayer/KxApp.java | package com.sdcode.videoplayer;
import android.app.Application;
import android.content.Context;
import androidx.multidex.MultiDex;
import com.sdcode.videoplayer.kxUtil.kxUtils;
public class KxApp extends Application {
private static KxApp ourInstance = new KxApp();
public static KxApp getInstance() {
return ourInstance;
}
private String base64PublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmuyWFytTgNJdLhqAKHJv/6GVFNtR0aIURBrXSsjcC8fMJuy5hs4hozEBcqRyJOJzjX5VQCyP8+ir5BM7bies6JFl4HY7yUJrXvrxfjBf27wpmee1O1rGfGhQDkFbFuoBHGsA02OrJEr296PuxW85nZN5eJ4VSOkHebW+AEk7auJ5h8Cu1OW1ng39+w2cXGvRbN5AklElYIEpkWcIoU+XAKmT/S4RCZkSDVBf3CGCPdfPoODL069/ToVISoY/BscnoPnzUaivg0BdYR3M+yH0qYyf6gpc9U+5uW+fK/Hm8/TFSY2kY7C/dgDgl8eKshtKn5pUG2JrK20Kusvkr8Y2OwIDAQAB";
@Override
public void onCreate() {
super.onCreate();
ourInstance = this;
kxUtils.init(this);
}
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
}
| 1,063 | Java | .java | kartikhimself/Simple-Video-Player | 11 | 4 | 0 | 2019-07-03T02:35:28Z | 2019-07-02T15:42:27Z |
SearchActivity.java | /FileExtraction/Java_unseen/kartikhimself_Simple-Video-Player/app/src/main/java/com/sdcode/videoplayer/SearchActivity.java | package com.sdcode.videoplayer;
import androidx.appcompat.widget.SearchView;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import com.sdcode.videoplayer.customizeUI.WrapContentLinearLayoutManager;
import com.sdcode.videoplayer.adapter.VideoAdapter;
import com.sdcode.videoplayer.video.VideoItem;
import java.util.ArrayList;
public class SearchActivity extends BaseActivity implements SearchView.OnQueryTextListener, View.OnTouchListener {
private InputMethodManager mImm;
private String queryString;
private SearchView mSearchView;
private VideoAdapter adapter;
private ArrayList<VideoItem> searchResultList = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
mImm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if(getSupportActionBar()!=null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
RecyclerView recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new WrapContentLinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
adapter = new VideoAdapter(this);
recyclerView.setAdapter(adapter);
}
@Override
public boolean onCreateOptionsMenu(final Menu menu) {
getMenuInflater().inflate(R.menu.search_menu, menu);
MenuItem menuItem = menu.findItem(R.id.action_search);
mSearchView = (SearchView) menuItem.getActionView();
mSearchView.setOnQueryTextListener(this);
mSearchView.setQueryHint(getString(R.string.search_title));
mSearchView.setIconifiedByDefault(false);
mSearchView.setIconified(false);
mSearchView.setMaxWidth( Integer.MAX_VALUE );
menuItem.setOnActionExpandListener(new MenuItem.OnActionExpandListener() {
@Override
public boolean onMenuItemActionExpand(MenuItem item) {
return true;
}
@Override
public boolean onMenuItemActionCollapse(MenuItem item) {
finish();
return false;
}
});
menu.findItem(R.id.action_search).expandActionView();
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(final MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onQueryTextSubmit(String query) {
onQueryTextChange(query);
hideInputManager();
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
if (newText.equals(queryString)) {
return true;
}
queryString = newText;
if (queryString.trim().equals("")) {
searchResultList.clear();
adapter.updateData(searchResultList);
} else {
searchVideo(queryString);
}
return true;
}
@Override
public boolean onTouch(View v, MotionEvent event) {
hideInputManager();
return false;
}
@Override
protected void onDestroy() {
super.onDestroy();
}
public void hideInputManager() {
if (mSearchView != null) {
if (mImm != null) {
mImm.hideSoftInputFromWindow(mSearchView.getWindowToken(), 0);
}
mSearchView.clearFocus();
}
}
private void searchVideo(String queryString){
String regex = "(?i)(bea).*".replace("bea",queryString);
searchResultList = new ArrayList<>();
if(GlobalVar.getInstance().allVideoItems == null || GlobalVar.getInstance().allVideoItems.size() == 0) return;
for (VideoItem video : GlobalVar.getInstance().allVideoItems) {
// higher search result
if(video.getVideoTitle().matches(regex)){
searchResultList.add(video);
}
}
for (VideoItem video : GlobalVar.getInstance().allVideoItems) {
if(video.getVideoTitle().contains(queryString)){
if(!isExist(video.getPath()))
searchResultList.add(video);
}
}
adapter.updateData(searchResultList);
}
private boolean isExist(String path){
if(searchResultList == null) return false;
if(searchResultList.size() == 0) return false;
for (VideoItem videoItem :searchResultList){
if(videoItem.getPath().contains(path)) return true;
}
return false;
}
}
| 5,284 | Java | .java | kartikhimself/Simple-Video-Player | 11 | 4 | 0 | 2019-07-03T02:35:28Z | 2019-07-02T15:42:27Z |
BaseActivity.java | /FileExtraction/Java_unseen/kartikhimself_Simple-Video-Player/app/src/main/java/com/sdcode/videoplayer/BaseActivity.java | package com.sdcode.videoplayer;
import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.sdcode.videoplayer.fragment.FragmentFolderList;
import com.sdcode.videoplayer.fragment.MyFragment;
import com.sdcode.videoplayer.kxUtil.PreferencesUtility;
import com.sdcode.videoplayer.kxUtil.kxUtils;
import com.sdcode.videoplayer.permission.PermissionCallback;
import com.sdcode.videoplayer.videoService.VideoService;
import com.sdcode.videoplayer.video.VideoItem;
import java.util.ArrayList;
public abstract class BaseActivity extends AppCompatActivity {
GlobalVar mGlobalVar = GlobalVar.getInstance();
protected static final int PERMISSION_REQUEST_CODE = 888888888;
boolean isNeedResumePlay = false;
MyFragment currentFragment = new FragmentFolderList();
//protected CastContext castContext;
@Override
protected void onCreate(Bundle savedInstanceState) {
int theme = PreferencesUtility.getInstance(this).getThemeSettings();
if(theme < 0 || theme > 9) theme = 0;
if(theme== 0) {
setTheme(R.style.AppThemeLightBasic0);
}else if(theme== 1) {
setTheme(R.style.AppThemeLightBasic1);
}
if(theme== 2) {
setTheme(R.style.AppThemeLightBasic2);
}
if(theme== 3) {
setTheme(R.style.AppThemeLightBasic3);
}
if(theme== 4) {
setTheme(R.style.AppThemeLightBasic4);
}
if(theme== 5) {
setTheme(R.style.AppThemeLightBasic5);
}
if(theme== 6) {
setTheme(R.style.AppThemeLightBasic6);
}
if(theme== 7) {
setTheme(R.style.AppThemeLightBasic7);
}
if(theme== 8) {
setTheme(R.style.AppThemeLightBasic8);
}
if(theme== 9) {
setTheme(R.style.AppThemeLightBasic9);
}
super.onCreate(savedInstanceState);
inItService();
}
@Override
protected void onStart() {
super.onStart();
}
@Override
protected void onDestroy() {
super.onDestroy();
if(GlobalVar.getInstance().videoService != null)
unbindService(videoServiceConnection);
}
@Override
public void onBackPressed() {
super.onBackPressed();
}
protected ServiceConnection videoServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
VideoService.VideoBinder binder = (VideoService.VideoBinder) service;
GlobalVar.getInstance().videoService = binder.getService();
if(isNeedResumePlay) startPopupMode();
if(mGlobalVar.isOpenFromIntent){
mGlobalVar.isOpenFromIntent = false;
mGlobalVar.videoService.playVideo(0,false);
showFloatingView(BaseActivity.this,true);
finish();
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
isConnection = false;
}
};
boolean isConnection = false;
protected static Intent _playIntent;
public void inItService() {
_playIntent = new Intent(this, VideoService.class);
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(_playIntent);
} else {
startService(_playIntent);
}
}catch (IllegalStateException e){
e.printStackTrace();
return ;
}
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// startForegroundService(_playIntent);
// } else {
// startService(_playIntent);
// }
//startService(_playIntent);
bindService(_playIntent, videoServiceConnection, Context.BIND_AUTO_CREATE);
}
public void startPopupMode() {
if (_playIntent != null) {
GlobalVar.getInstance().videoService.playVideo(mGlobalVar.seekPosition,true);
}
}
@Override
public void onConfigurationChanged(@NonNull Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if(currentFragment != null){
currentFragment.reloadFragment(newConfig.orientation);
}
// Checking the orientation of the screen
}
public void reloadData(){
}
int requestCode = 1;
@Override
@TargetApi(Build.VERSION_CODES.M)
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode,resultCode,data);
if (this.requestCode == resultCode) {
isNeedResumePlay = true;
startPopupMode();
} else {
}
}
@SuppressLint("NewApi")
public void showFloatingView(Context context, boolean isShowOverlayPermission) {
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP_MR1) {
startPopupMode();
return;
}
if (Settings.canDrawOverlays(context)) {
startPopupMode();
return;
}
if (isShowOverlayPermission) {
final Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + context.getPackageName()));
startActivityForResult(intent, requestCode);
}
}
/// permission
protected void checkPermissionAndThenLoad() {
//check for permission
if (kxUtils.checkPermission(Manifest.permission.READ_EXTERNAL_STORAGE) && kxUtils.checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
loadEverything();
} else {
kxUtils.askForPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE, permissionReadStorageCallback);
}
}
protected final PermissionCallback permissionReadStorageCallback = new PermissionCallback() {
@Override
public void permissionGranted() {
if(kxUtils.checkPermission(Manifest.permission.READ_EXTERNAL_STORAGE) && kxUtils.checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
loadEverything();
}else if(!kxUtils.checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE))
kxUtils.askForPermission(BaseActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE, permissionReadStorageCallback);
}
@Override
public void permissionRefused() {
finish();
}
};
@Override
public boolean onSupportNavigateUp() {
finish();
return true;
}
@Override
public void onRequestPermissionsResult(
int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
kxUtils.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
protected void loadEverything(){
}
public void updateMultiSelectedState(){
}
public void updateListAfterDelete(ArrayList<VideoItem> videoItems){
}
// protected void setupCast(){
// try {
// castContext = CastContext.getSharedInstance(this);
// } catch (RuntimeException e) {
// Throwable cause = e.getCause();
// while (cause != null) {
// if (cause instanceof DynamiteModule.LoadingException) {
// return;
// }
// cause = cause.getCause();
// }
// // Unknown error. We propagate it.
// throw e;
// }
// }
}
| 8,241 | Java | .java | kartikhimself/Simple-Video-Player | 11 | 4 | 0 | 2019-07-03T02:35:28Z | 2019-07-02T15:42:27Z |
FirstActivity.java | /FileExtraction/Java_unseen/kartikhimself_Simple-Video-Player/app/src/main/java/com/sdcode/videoplayer/FirstActivity.java | package com.sdcode.videoplayer;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import androidx.appcompat.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.sdcode.videoplayer.fragment.FragmentFolderList;
import com.sdcode.videoplayer.kxUtil.PreferencesUtility;
import com.sdcode.videoplayer.kxUtil.kxUtils;
import com.sdcode.videoplayer.video.VideoItem;
import com.stepstone.apprating.AppRatingDialog;
import com.stepstone.apprating.listener.RatingDialogListener;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.Arrays;
public class FirstActivity extends BaseActivity implements RatingDialogListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
Toolbar toolbar = findViewById(R.id.toolbar);
currentFragment = new FragmentFolderList();
setSupportActionBar(toolbar);
//setupCast();
if(getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
if (kxUtils.isMarshmallow()) checkPermissionAndThenLoad();
else loadEverything();
String action = getIntent().getAction();
if(Intent.ACTION_VIEW.equals(action)) {
Intent receivedIntent = getIntent();
Uri receivedUri = receivedIntent.getData();
assert receivedUri != null;
String _file = receivedUri.toString();
mGlobalVar.playingVideo = new VideoItem();
mGlobalVar.playingVideo.setPath(_file);
mGlobalVar.playingVideo.setVideoTitle(kxUtils.getFileNameFromPath(_file));
mGlobalVar.videoItemsPlaylist = new ArrayList<>();
mGlobalVar.videoItemsPlaylist.add(mGlobalVar.playingVideo);
if(mGlobalVar.videoService == null){
mGlobalVar.isOpenFromIntent = true;
}else {
mGlobalVar.videoService.playVideo(0,false);
showFloatingView(FirstActivity.this,true);
finish();
}
}
createDialog();
int laughtCount = PreferencesUtility.getInstance(this).getlaughCount();
if(laughtCount == 8) showRateDialog();
PreferencesUtility.getInstance(this).setLaughCount(laughtCount+1);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
//No call for super(). Bug on API Level > 11.
}
@Override
protected void loadEverything(){
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,currentFragment).commit();
}
@Override
public void reloadData(){
currentFragment = new FragmentFolderList();
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,currentFragment).commit();
}
@Override
public void onResume() {
super.onResume();
if(mGlobalVar.isNeedRefreshFolder && currentFragment != null){
mGlobalVar.isNeedRefreshFolder = false;
reloadData();
}
// if(castContext == null){
// return;
// }
// if(mGlobalVar.videoService == null || mGlobalVar.videoService.getPlayerManager() == null){
// return;
// }
// mGlobalVar.videoService.getPlayerManager().updateCast(castContext);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.clear();
getMenuInflater().inflate(R.menu.secound, menu);
// if(currentFragment instanceof FragmentVideoList){
// if(PreferencesUtility.getInstance(FirstActivity.this).isAlbumsInGrid())
// getMenuInflater().inflate(R.menu.first, menu);
// else
// getMenuInflater().inflate(R.menu.first1, menu);
// }
// else if (currentFragment instanceof FragmentFolderList)
// {
// getMenuInflater().inflate(R.menu.secound, menu);
// }
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.secound, menu);
// if(currentFragment instanceof FragmentVideoList){
// if(PreferencesUtility.getInstance(FirstActivity.this).isAlbumsInGrid())
// getMenuInflater().inflate(R.menu.first, menu);
// else
// getMenuInflater().inflate(R.menu.first1, menu);
// }
// else if (currentFragment instanceof FragmentFolderList)
// {
// getMenuInflater().inflate(R.menu.secound, menu);
// }
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
Handler handler = new Handler();
//noinspection SimplifiableIfStatement
if(id == R.id.action_search){
if (kxUtils.isMarshmallow())
{
if (kxUtils.checkPermission(Manifest.permission.READ_EXTERNAL_STORAGE)) {
navigateToSearch(this);
}
}
else navigateToSearch(this);
} if(id == R.id.action_setting){
startActivity(new Intent(FirstActivity.this,SettingsActivity.class));
}else if(id == R.id.menu_sort_by_az){
currentFragment.sortAZ();
}else if(id == R.id.menu_sort_by_za){
currentFragment.sortZA();
}else if(id == R.id.menu_sort_by_total_videos){
currentFragment.sortSize();
}else if(id == R.id.action_go_to_playing) {
if (mGlobalVar.videoService == null || mGlobalVar.playingVideo == null) {
Toast.makeText(this, getString(R.string.no_video_playing), Toast.LENGTH_SHORT).show();
return false;
}
final Intent intent = new Intent(FirstActivity.this, PlayVideoActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_in_left,
R.anim.slide_stay_x);
}else if(id == R.id.action_about){
startActivity(new Intent(FirstActivity.this,AboutActivity.class));
}else if(id == R.id.action_sleepTimer){
if(dialog != null) dialog.show();
}else if(id == R.id.action_musicPlayer){
Uri uri = Uri.parse("market://details?id=" + "com.sdcode.etmusicplayer");
Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
goToMarket.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY |
Intent.FLAG_ACTIVITY_NEW_DOCUMENT |
Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
try {
startActivity(goToMarket);
} catch (ActivityNotFoundException e) {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/apps/details?id=" + "com.sdcode.etmusicplayer")));
}
}
return false;
}
public static void navigateToSearch(Activity context) {
final Intent intent = new Intent(context, SearchActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
context.startActivity(intent);
}
AlertDialog dialog;
Button btnDownload;
TextView textView1;
private void createDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.content_download_app,null);
btnDownload = view.findViewById(R.id.btn_download);
textView1 = view.findViewById(R.id.txt_promote_text);
btnDownload.setOnClickListener(view1 -> {
dialog.cancel();
Uri uri = Uri.parse("market://details?id=" + "com.sdcode.timerswitch");
Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
goToMarket.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY |
Intent.FLAG_ACTIVITY_NEW_DOCUMENT |
Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
try {
startActivity(goToMarket);
} catch (ActivityNotFoundException e) {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/apps/details?id=" + "com.sdcode.timerswitch")));
}
});
builder.setView(view);
dialog = builder.create();
}
public void showRateDialog() {
new AppRatingDialog.Builder()
.setPositiveButtonText("Submit")
.setNegativeButtonText("Cancel")
.setNeutralButtonText("Later")
.setNoteDescriptions(Arrays.asList("Very Bad", "Not good", "Normal", "Ok, but need improve more", "Excellent, I like it !!!"))
.setDefaultRating(1)
.setTitle("Rate this application")
.setDescription("Your rating help us understand and keep update the application.")
.setCommentInputEnabled(false)
.setDefaultComment("This app is pretty cool !")
.setStarColor(R.color.nice_pink3)
.setNoteDescriptionTextColor(R.color.blackL)
.setTitleTextColor(R.color.blackL)
.setDescriptionTextColor(R.color.blackL)
.setHint("Please write your comment here ...")
.setHintTextColor(R.color.red)
.setCommentTextColor(R.color.blackl1)
.setCommentBackgroundColor(R.color.colorPrimaryDark)
.setWindowAnimation(R.style.MyDialogFadeAnimation)
.setCancelable(false)
.setCanceledOnTouchOutside(false)
.create(FirstActivity.this)
.show();
}
@Override
public void onNegativeButtonClicked() {
}
@Override
public void onNeutralButtonClicked() {
}
@Override
public void onPositiveButtonClicked(int i, @NotNull String s) {
if(i == 5){
Uri uri = Uri.parse("market://details?id=" + "com.sdcode.videoplayer");
Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
// To count with Play market backstack, After pressing back button,
// to taken back to our application, we need to add following flags to intent.
goToMarket.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY |
Intent.FLAG_ACTIVITY_NEW_DOCUMENT |
Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
try {
startActivity(goToMarket);
} catch (ActivityNotFoundException e) {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/apps/details?id=" + getPackageName())));
}
}else {
Toast.makeText(FirstActivity.this,"Thank you, we will try to improve app",Toast.LENGTH_SHORT).show();
}
}
}
| 11,699 | Java | .java | kartikhimself/Simple-Video-Player | 11 | 4 | 0 | 2019-07-03T02:35:28Z | 2019-07-02T15:42:27Z |
ErrorCause.java | /FileExtraction/Java_unseen/kartikhimself_Simple-Video-Player/app/src/main/java/com/sdcode/videoplayer/storageProcess/ErrorCause.java | package com.sdcode.videoplayer.storageProcess;
import java.util.ArrayList;
import androidx.annotation.Nullable;
class ErrorCause {
private String title;
private ArrayList<String> causes;
public ErrorCause(String title, ArrayList<String> causes) {
this.title = title;
this.causes = causes;
}
public ErrorCause(String title) {
this.title = title;
this.causes = new ArrayList<>(1);
}
public void addCause(String cause) {
this.causes.add(cause);
}
public String getTitle() {
return title;
}
public boolean hasErrors() {
return causes.size() > 0;
}
public @Nullable
ErrorCause get() {
if (hasErrors()) return this;
else return null;
}
public ArrayList<String> getCauses() {
return causes;
}
@Override
public String toString() {
StringBuilder b = new StringBuilder();
b.append(title).append("\n");
for (String cause : causes) {
b.append(cause).append("\n");
}
return b.toString();
}
public static ErrorCause fromThrowable(Throwable throwable) {
if (throwable instanceof ProgressException)
return ((ProgressException) throwable).getError();
else return new ErrorCause(throwable.getMessage());
}
}
| 1,353 | Java | .java | kartikhimself/Simple-Video-Player | 11 | 4 | 0 | 2019-07-03T02:35:28Z | 2019-07-02T15:42:27Z |
RenameVideoDialog.java | /FileExtraction/Java_unseen/kartikhimself_Simple-Video-Player/app/src/main/java/com/sdcode/videoplayer/storageProcess/RenameVideoDialog.java | package com.sdcode.videoplayer.storageProcess;
import android.app.Dialog;
import android.content.Context;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.widget.Toast;
import com.afollestad.materialdialogs.MaterialDialog;
import com.sdcode.videoplayer.GlobalVar;
import com.sdcode.videoplayer.kxUtil.kxUtils;
import com.sdcode.videoplayer.R;
import com.sdcode.videoplayer.adapter.VideoAdapter;
import com.sdcode.videoplayer.video.VideoItem;
import java.io.File;
import androidx.annotation.NonNull;
import androidx.fragment.app.DialogFragment;
public class RenameVideoDialog extends DialogFragment {
static VideoItem videoItem;
static Context context;
static VideoAdapter videoAdapter;
public static RenameVideoDialog newInstance(Context context, VideoAdapter videoAdapter,VideoItem videoItem) {
RenameVideoDialog dialog = new RenameVideoDialog();
RenameVideoDialog.videoItem = videoItem;
RenameVideoDialog.context = context;
RenameVideoDialog.videoAdapter = videoAdapter;
return dialog;
}
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new MaterialDialog.Builder(context).positiveText(getString(R.string.action_rename)).negativeText(getString(R.string.confirm_cancel))
.title(getString(R.string.action_rename)).input(getString(R.string.enter_new_name), "", false, new MaterialDialog.InputCallback() {
@Override
public void onInput(@NonNull MaterialDialog dialog, CharSequence input) {
if(isNewNamePossible(input.toString())){
if(renameMedia(context,input.toString())){
videoAdapter.updateData(videoAdapter.getVideoItems());
}
}else {
Toast.makeText(context,context.getString(R.string.fileNameExist),Toast.LENGTH_LONG).show();
}
}
}).build();
}
public static boolean renameMedia(Context context, String newName) {
boolean success = false;
Uri external = MediaStore.Files.getContentUri("external");
try {
File from = new File(videoItem.getPath());
if(from.exists()) {
File dir = from.getParentFile();
String fileEx = kxUtils.getFileExtension(videoItem.getPath());
File to = new File(dir, newName + "." + fileEx);
if (success = StorageHelper.moveFile(context, from, to)) {
context.getContentResolver().delete(external,
MediaStore.MediaColumns.DATA + "=?", new String[]{from.getPath()});
scanFile(context, new String[]{to.getAbsolutePath()});
videoItem.setVideoTitle(newName);
videoItem.setPath(to.getAbsolutePath());
}
}
} catch (Exception e) {
e.printStackTrace();
}
return success;
}
public static void scanFile(Context context, String[] path) {
MediaScannerConnection.scanFile(context.getApplicationContext(), path, null, null);
}
private boolean isNewNamePossible(String newName){
if(videoItem == null) return false;
String fileEx = kxUtils.getFileExtension(videoItem.getPath());
if(GlobalVar.getInstance().folderItem == null || GlobalVar.getInstance().folderItem.getVideoItems() == null)
return false;
for(VideoItem videoItem: GlobalVar.getInstance().folderItem.getVideoItems()){
if(newName.equals(videoItem.getVideoTitle()) && fileEx.equals(kxUtils.getFileExtension(videoItem.getPath())))
return false;
}
return true;
}
} | 3,935 | Java | .java | kartikhimself/Simple-Video-Player | 11 | 4 | 0 | 2019-07-03T02:35:28Z | 2019-07-02T15:42:27Z |
StorageHelper.java | /FileExtraction/Java_unseen/kartikhimself_Simple-Video-Player/app/src/main/java/com/sdcode/videoplayer/storageProcess/StorageHelper.java | package com.sdcode.videoplayer.storageProcess;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.provider.BaseColumns;
import android.provider.MediaStore;
import android.util.Log;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.FileChannel;
import java.util.HashSet;
import com.orhanobut.hawk.Hawk;
import androidx.annotation.NonNull;
import androidx.core.content.FileProvider;
import androidx.documentfile.provider.DocumentFile;
public class StorageHelper {
private static final String TAG = "StorageHelper";
public static boolean copyFile(Context context, @NonNull final File source, @NonNull final File targetDir) {
InputStream inStream = null;
OutputStream outStream = null;
boolean success = false;
File target = getTargetFile(source, targetDir);
try {
inStream = new FileInputStream(source);
// First try the normal way
if (isWritable(target)) {
// standard way
FileChannel inChannel = new FileInputStream(source).getChannel();
FileChannel outChannel = new FileOutputStream(target).getChannel();
inChannel.transferTo(0, inChannel.size(), outChannel);
success = true;
try { inChannel.close(); } catch (Exception ignored) { }
try { outChannel.close(); } catch (Exception ignored) { }
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//inStream = context.getContentResolver().openInputStream(Uri.fromFile(source));
//outStream = context.getContentResolver().openOutputStream(Uri.fromFile(target));
if (isFileOnSdCard(context, source)) {
DocumentFile sourceDocument = getDocumentFile(context, source, false, false);
if (sourceDocument != null) {
inStream = context.getContentResolver().openInputStream(sourceDocument.getUri());
}
}
// Storage Access Framework
DocumentFile targetDocument = getDocumentFile(context, target, false, false);
if (targetDocument != null) {
outStream = context.getContentResolver().openOutputStream(targetDocument.getUri());
}
}
else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
// TODO: 13/08/16 test this
// Workaround for Kitkat ext SD card
Uri uri = getUriFromFile(context,target.getAbsolutePath());
if (uri != null) {
outStream = context.getContentResolver().openOutputStream(uri);
}
}
if (outStream != null) {
// Both for SAF and for Kitkat, write to output stream.
byte[] buffer = new byte[4096]; // MAGIC_NUMBER
int bytesRead;
while ((bytesRead = inStream.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead);
success = true;
}
}
} catch (Exception e) {
Log.e(TAG, "Error when copying file from " + source.getAbsolutePath() + " to " + target.getAbsolutePath(), e);
return false;
}
finally {
try { inStream.close(); } catch (Exception ignored) { }
try { outStream.close(); } catch (Exception ignored) { }
}
if (success) scanFile(context, new String[] { target.getPath() });
return success;
}
public static boolean moveFile(Context context, @NonNull final File source, @NonNull final File target) {
// the param "target" is a file.
// File target = new File(target, source.getName());
// First try the normal rename.
boolean success = source.renameTo(target);
if (!success) {
success = copyFile(context, source, target);
if (success) {
try {
deleteFile(context, source);
success = true;
} catch (ProgressException e) {
success = false;
}
}
}
//if (success) scanFile(context, new String[]{ source.getPath(), target.getPath() });
return success;
}
public static void deleteFile(Context context, @NonNull final File file) throws ProgressException {
ErrorCause error = new ErrorCause(file.getName());
//W/DocumentFile: Failed getCursor: java.lang.IllegalArgumentException: Failed to determine if A613-F0E1:.android_secure is child of A613-F0E1:: java.io.FileNotFoundException: Missing file for A613-F0E1:.android_secure at /storage/sdcard1/.android_secure
// First try the normal deletion.
boolean success = false;
try {
success = file.delete();
} catch (Exception e) {
error.addCause(e.getLocalizedMessage());
}
// Try with Storage Access Framework.
if (!success && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
DocumentFile document = getDocumentFile(context, file, false, false);
success = document != null && document.delete();
error.addCause("Failed SAF");
}
// Try the Kitkat workaround.
if (!success && Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
ContentResolver resolver = context.getContentResolver();
try {
Uri uri = getUriForFile(context, file);
if (uri != null) {
resolver.delete(uri, null, null);
}
success = !file.exists();
}
catch (Exception e) {
error.addCause(String.format("Failed CP: %s", e.getLocalizedMessage()));
Log.e(TAG, "Error when deleting file " + file.getAbsolutePath(), e);
success = false;
}
}
if (success) scanFile(context, new String[]{file.getPath()});
else throw new ProgressException(error);
}
private static DocumentFile getDocumentFile(Context context, @NonNull final File file, final boolean isDirectory, final boolean createDirectories) {
Uri treeUri = getTreeUri(context);
if (treeUri == null) return null;
DocumentFile document = DocumentFile.fromTreeUri(context, treeUri);
String sdcardPath = getSavedSdcardPath(context);
String suffixPathPart = null;
if (sdcardPath != null) {
if((file.getPath().indexOf(sdcardPath)) != -1)
suffixPathPart = file.getAbsolutePath().substring(sdcardPath.length());
} else {
HashSet<File> storageRoots = StorageHelper.getStorageRoots(context);
for(File root : storageRoots) {
if (root != null) {
if ((file.getPath().indexOf(root.getPath())) != -1)
suffixPathPart = file.getAbsolutePath().substring(file.getPath().length());
}
}
}
if (suffixPathPart == null) {
Log.d(TAG, "unable to find the document file, filePath:"+ file.getPath()+ " root: " + ""+sdcardPath);
return null;
}
if (suffixPathPart.startsWith(File.separator)) suffixPathPart = suffixPathPart.substring(1);
String[] parts = suffixPathPart.split("/");
for (int i = 0; i < parts.length; i++) { // 3 is the
DocumentFile tmp = document.findFile(parts[i]);
if (tmp != null)
document = document.findFile(parts[i]);
else {
if (i < parts.length - 1) {
if (createDirectories) document = document.createDirectory(parts[i]);
else return null;
}
else if (isDirectory) document = document.createDirectory(parts[i]);
else return document.createFile("image", parts[i]);
}
}
return document;
}
private static File getTargetFile(File source, File targetDir) {
File file = new File(targetDir, source.getName());
if (!source.getParentFile().equals(targetDir) && !file.exists())
return file;
return new File(targetDir, StringUtils.incrementFileNameSuffix(source.getName()));
}
private static boolean isWritable(@NonNull final File file) {
boolean isExisting = file.exists();
try {
FileOutputStream output = new FileOutputStream(file, true);
try {
output.close();
}
catch (IOException e) {
// do nothing.
}
}
catch (java.io.FileNotFoundException e) {
return false;
}
boolean result = file.canWrite();
// Ensure that file is not created during this process.
if (!isExisting) {
//noinspection ResultOfMethodCallIgnored
file.delete();
}
return result;
}
private static Uri getTreeUri(Context context) {
String uriString = Hawk.get("uri_extsdcard_photos", null);
if (uriString == null) return null;
return Uri.parse(uriString);
}
private static boolean isFileOnSdCard(Context context, File file) {
String sdcardPath = getSdcardPath(context);
return sdcardPath != null && file.getPath().startsWith(sdcardPath);
}
public static String getSdcardPath(Context context) {
for(File file : context.getExternalFilesDirs("external")) {
if (file != null && !file.equals(context.getExternalFilesDir("external"))) {
int index = file.getAbsolutePath().lastIndexOf("/Android/data");
if (index < 0) Log.w("asd", "Unexpected external file dir: " + file.getAbsolutePath());
else
return new File(file.getAbsolutePath().substring(0, index)).getPath();
}
}
return null;
}
private static String getSavedSdcardPath(Context context) {
return Hawk.get("sd_card_path", null);
}
public static HashSet<File> getStorageRoots(Context context) {
HashSet<File> paths = new HashSet<File>();
for (File file : context.getExternalFilesDirs("external")) {
if (file != null) {
int index = file.getAbsolutePath().lastIndexOf("/Android/data");
if (index < 0) Log.w("asd", "Unexpected external file dir: " + file.getAbsolutePath());
else
paths.add(new File(file.getAbsolutePath().substring(0, index)));
}
}
return paths;
}
private static Uri getUriFromFile(Context context, final String path) {
ContentResolver resolver = context.getContentResolver();
Cursor filecursor = resolver.query(MediaStore.Files.getContentUri("external"),
new String[] {BaseColumns._ID}, MediaStore.MediaColumns.DATA + " = ?",
new String[] {path}, MediaStore.MediaColumns.DATE_ADDED + " desc");
if (filecursor == null) {
return null;
}
filecursor.moveToFirst();
if (filecursor.isAfterLast()) {
filecursor.close();
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, path);
return resolver.insert(MediaStore.Files.getContentUri("external"), values);
}
else {
int imageId = filecursor.getInt(filecursor.getColumnIndex(BaseColumns._ID));
Uri uri = MediaStore.Files.getContentUri("external").buildUpon().appendPath(
Integer.toString(imageId)).build();
filecursor.close();
return uri;
}
}
public static Uri getUriForFile(Context context, File file) {
return FileProvider.getUriForFile(context, context.getPackageName() + ".provider", file);
}
public static void scanFile(Context context, String[] path) {
MediaScannerConnection.scanFile(context.getApplicationContext(), path, null, null);
}
} | 12,694 | Java | .java | kartikhimself/Simple-Video-Player | 11 | 4 | 0 | 2019-07-03T02:35:28Z | 2019-07-02T15:42:27Z |
ProgressException.java | /FileExtraction/Java_unseen/kartikhimself_Simple-Video-Player/app/src/main/java/com/sdcode/videoplayer/storageProcess/ProgressException.java | package com.sdcode.videoplayer.storageProcess;
public class ProgressException extends Exception {
private ErrorCause error;
public ProgressException(ErrorCause error) {
this.error = error;
}
public ProgressException(String error) {
this.error = new ErrorCause(error);
}
public ErrorCause getError() {
return error;
}
@Override
public String toString() {
return error.toString();
}
@Override
public String getMessage() {
return toString();
}
@Override
public String getLocalizedMessage() {
return toString();
}
}
| 633 | Java | .java | kartikhimself/Simple-Video-Player | 11 | 4 | 0 | 2019-07-03T02:35:28Z | 2019-07-02T15:42:27Z |
StringUtils.java | /FileExtraction/Java_unseen/kartikhimself_Simple-Video-Player/app/src/main/java/com/sdcode/videoplayer/storageProcess/StringUtils.java | package com.sdcode.videoplayer.storageProcess;
import android.content.Context;
import android.os.Build;
import android.text.Html;
import android.text.Spanned;
import android.widget.Toast;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import androidx.annotation.NonNull;
public class StringUtils {
public static String[] asArray(String... a) {
return a;
}
public static String getPhotoNameByPath(String path) {
String b[] = path.split("/");
String fi = b[b.length - 1];
return fi.substring(0, fi.lastIndexOf('.'));
}
@SuppressWarnings("deprecation")
public static Spanned html(String s) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
return Html.fromHtml(s, Html.FROM_HTML_MODE_LEGACY);
else return Html.fromHtml(s);
}
public static String getName(String path) {
String b[] = path.split("/");
return b[b.length - 1];
}
public static String getPhotoPathRenamed(String olderPath, String newName) {
StringBuilder c = new StringBuilder();
String b[] = olderPath.split("/");
for (int x = 0; x < b.length - 1; x++) c.append(b[x]).append("/");
c.append(newName);
String name = b[b.length - 1];
c.append(name.substring(name.lastIndexOf('.')));
return c.toString();
}
public static String incrementFileNameSuffix(String name) {
StringBuilder builder = new StringBuilder();
int dot = name.lastIndexOf('.');
String baseName = dot != -1 ? name.subSequence(0, dot).toString() : name;
String nameWoSuffix = baseName;
Matcher matcher = Pattern.compile("_\\d").matcher(baseName);
if (matcher.find()) {
int i = baseName.lastIndexOf("_");
if (i != -1) nameWoSuffix = baseName.subSequence(0, i).toString();
}
builder.append(nameWoSuffix).append("_").append(new Date().getTime());
builder.append(name.substring(dot));
return builder.toString();
}
public static String getPhotoPathRenamedAlbumChange(String olderPath, String albumNewName) {
String c = "", b[] = olderPath.split("/");
for (int x = 0; x < b.length - 2; x++) c += b[x] + "/";
c += albumNewName + "/" + b[b.length - 1];
return c;
}
public static String getAlbumPathRenamed(String olderPath, String newName) {
return olderPath.substring(0, olderPath.lastIndexOf('/')) + "/" + newName;
}
public static String getPhotoPathMoved(String olderPath, String folderPath) {
String b[] = olderPath.split("/");
String fi = b[b.length - 1];
String path = folderPath + "/";
path += fi;
return path;
}
public static String getBucketPathByImagePath(String path) {
String b[] = path.split("/");
String c = "";
for (int x = 0; x < b.length - 1; x++) c += b[x] + "/";
c = c.substring(0, c.length() - 1);
return c;
}
public static void showToast(Context x, String s) {
Toast t = Toast.makeText(x, s, Toast.LENGTH_SHORT);
t.show();
}
public static String humanReadableByteCount(long bytes, boolean si) {
int unit = si ? 1000 : 1024;
if (bytes < unit) return bytes + " B";
int exp = (int) (Math.log(bytes) / Math.log(unit));
String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp - 1) + (si ? "" : "i");
return String.format(Locale.ENGLISH, "%.1f %sB", bytes / Math.pow(unit, exp), pre);
}
public static String b(String content) {
return String.format(Locale.ENGLISH, "<b>%s</b>", content);
}
public static String i(String content) {
return String.format(Locale.ENGLISH, "<i>%s</i>", content);
}
public static String color(String color, String content) {
return String.format(Locale.ENGLISH,
"<font color='%s'>%s</font>",
color, content);
}
/**
* Returns a user-readable date formatted.
* eg: Sunday, 31 December 2017
*
* @param date The date object
* @return A user-readable date string.
*/
public static String getUserReadableDate(@NonNull Date date) {
SimpleDateFormat dateFormatter = new SimpleDateFormat("E, d MMM yyyy", Locale.getDefault());
return dateFormatter.format(date);
}
}
| 4,482 | Java | .java | kartikhimself/Simple-Video-Player | 11 | 4 | 0 | 2019-07-03T02:35:28Z | 2019-07-02T15:42:27Z |
VideoLoadListener.java | /FileExtraction/Java_unseen/kartikhimself_Simple-Video-Player/app/src/main/java/com/sdcode/videoplayer/video/VideoLoadListener.java | package com.sdcode.videoplayer.video;
import java.util.ArrayList;
import java.util.List;
/**
* Created by sudamasayuki on 2017/11/22.
*/
public interface VideoLoadListener {
void onVideoLoaded(ArrayList<VideoItem> videoItems);
void onFailed(Exception e);
}
| 272 | Java | .java | kartikhimself/Simple-Video-Player | 11 | 4 | 0 | 2019-07-03T02:35:28Z | 2019-07-02T15:42:27Z |
VideoLoader.java | /FileExtraction/Java_unseen/kartikhimself_Simple-Video-Player/app/src/main/java/com/sdcode/videoplayer/video/VideoLoader.java | package com.sdcode.videoplayer.video;
import android.content.Context;
import android.database.Cursor;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore;
import android.text.format.DateFormat;
import android.util.Log;
import com.sdcode.videoplayer.kxUtil.kxUtils;
import java.io.File;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Created by sudamasayuki on 2017/11/22.
*/
public class VideoLoader {
private final static String TAG = "VideoLoader";
private final Context context;
private ExecutorService executorService;
public VideoLoader(Context context) {
this.context = context;
}
public void loadDeviceVideos(final VideoLoadListener listener) {
getExecutorService().execute(new VideoLoadRunnable(listener, context));
}
public void abortLoadVideos() {
if (executorService != null) {
executorService.shutdown();
executorService = null;
}
}
private ExecutorService getExecutorService() {
if (executorService == null) {
executorService = Executors.newSingleThreadExecutor();
}
return executorService;
}
private static class VideoLoadRunnable implements Runnable {
private final VideoLoadListener listener;
private final Context context;
private final Handler handler = new Handler(Looper.getMainLooper());
private final String[] projection = new String[]{
MediaStore.Video.Media.DATA,
MediaStore.Video.Media.DURATION,
MediaStore.Video.Media.TITLE,
MediaStore.Video.Media.RESOLUTION,
MediaStore.Video.Media.DATE_TAKEN
};
public VideoLoadRunnable(VideoLoadListener listener, Context context) {
this.listener = listener;
this.context = context;
}
@Override
public void run() {
Cursor cursor = context.getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, projection,
null, null, MediaStore.Video.Media.DEFAULT_SORT_ORDER);
if (cursor == null) {
handler.post(() -> listener.onFailed(new NullPointerException()));
return;
}
final ArrayList<VideoItem> videoItems = new ArrayList<>(cursor.getCount());
if (cursor.moveToLast()) {
do {
String path = cursor.getString(cursor.getColumnIndex(projection[0]));
if (path == null) continue;
Log.d(TAG, "pick video from device path = " + path);
String duration = kxUtils.makeShortTimeString(context,cursor.getLong(cursor.getColumnIndex(projection[1]))/1000);
Log.d(TAG, "pick video from device duration = " + duration);
String title = cursor.getString(cursor.getColumnIndex(projection[2]));
String resolution = cursor.getString(cursor.getColumnIndex(projection[3]));
String date_added = cursor.getString(cursor.getColumnIndex(projection[4]));
date_added = convertDate(date_added,"dd/MM/yyyy hh:mm:ss");
File file = new File(path);
if (file.exists()) {
long fileSize = file.length();
String folderName = "Unknow Folder";
File _parentFile = file.getParentFile();
if (_parentFile.exists()) {
folderName = _parentFile.getName();
}
videoItems.add(new VideoItem(
title,
path,
duration,
folderName, kxUtils.getStringSizeLengthFile(fileSize), resolution, fileSize, date_added));
}
} while (cursor.moveToPrevious());
}
cursor.close();
handler.post(() -> listener.onVideoLoaded(videoItems));
}
}
public static String convertDate(String dateInMilliseconds,String dateFormat) {
return DateFormat.format(dateFormat, Long.parseLong(dateInMilliseconds)).toString();
}
}
| 4,413 | Java | .java | kartikhimself/Simple-Video-Player | 11 | 4 | 0 | 2019-07-03T02:35:28Z | 2019-07-02T15:42:27Z |
VideoItem.java | /FileExtraction/Java_unseen/kartikhimself_Simple-Video-Player/app/src/main/java/com/sdcode/videoplayer/video/VideoItem.java | package com.sdcode.videoplayer.video;
/**
* Created by sudamasayuki on 2017/11/22.
*/
public class VideoItem {
private String videoTitle;
private String path;
private String duration;
private String folderName;
private String fileSize;
private String resolution;
private long fileSizeAsFloat;
private String date_added;
private boolean isLongClick = false;
private boolean isSelected = false;
public VideoItem(String videoTitle, String path, String duration, String folderName, String fileSize, String resolution, long fileSizeAsFloat, String date_added) {
this.path = path;
this.duration = duration;
this.videoTitle = videoTitle;
this.folderName = folderName;
this.fileSize = fileSize;
this.resolution = resolution;
this.fileSizeAsFloat = fileSizeAsFloat;
this.date_added = date_added;
}
public VideoItem() {
this.videoTitle = "";
this.path = "";
this.duration = "";
}
public String getPath() {
return path;
}
public String getDuration() {
return duration;
}
public String getVideoTitle() {
return videoTitle;
}
public void setVideoTitle(String videoTitle) {
this.videoTitle = videoTitle;
}
public String getFolderName() {
return folderName;
}
public void setFolderName(String folderName) {
this.folderName = folderName;
}
public String getFileSize() {
return fileSize;
}
public void setFileSize(String fileSize) {
this.fileSize = fileSize;
}
public void setPath(String value){
this.path = value;
}
public String getResolution() {
return resolution;
}
public void setResolution(String resolution) {
this.resolution = resolution;
}
public String getDate_added() {
return date_added;
}
public void setDate_added(String date_added) {
this.date_added = date_added;
}
public boolean isLongClick() {
return isLongClick;
}
public void setLongClick(boolean longClick) {
isLongClick = longClick;
}
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean selected) {
isSelected = selected;
}
public float getFileSizeAsFloat() {
return fileSizeAsFloat;
}
public void setFileSizeAsFloat(long fileSizeAsFloat) {
this.fileSizeAsFloat = fileSizeAsFloat;
}
}
| 2,558 | Java | .java | kartikhimself/Simple-Video-Player | 11 | 4 | 0 | 2019-07-03T02:35:28Z | 2019-07-02T15:42:27Z |
FolderLoader.java | /FileExtraction/Java_unseen/kartikhimself_Simple-Video-Player/app/src/main/java/com/sdcode/videoplayer/folder/FolderLoader.java | package com.sdcode.videoplayer.folder;
import com.sdcode.videoplayer.video.VideoItem;
import java.io.File;
import java.util.ArrayList;
public class FolderLoader {
public static ArrayList<FolderItem> getFolderList(ArrayList<VideoItem> videoItems){
File file;
ArrayList<FolderItem> folderItems = new ArrayList<>();
if(videoItems != null && videoItems.size() > 0){
for(int i = 0; i < videoItems.size();i ++){
file = new File(videoItems.get(i).getPath());
String filePath = file.getParent();
String fileName = "Unknow Folder";
File _parentFile = file.getParentFile();
if (_parentFile.exists()) {
fileName = _parentFile.getName();
}
if(!isFileExits(folderItems,filePath)){
folderItems.add(new FolderItem(fileName,filePath));
}
for (FolderItem item :folderItems) {
if(item.getFolderPath().contains(filePath)){
item.getVideoItems().add(videoItems.get(i));
}
}
}
}
return folderItems;
}
private static boolean isFileExits(ArrayList<FolderItem> folderItems, String path){
for (FolderItem item :folderItems) {
if(item.getFolderPath().contains(path))
return true;
}
return false;
}
}
| 1,479 | Java | .java | kartikhimself/Simple-Video-Player | 11 | 4 | 0 | 2019-07-03T02:35:28Z | 2019-07-02T15:42:27Z |
FolderItem.java | /FileExtraction/Java_unseen/kartikhimself_Simple-Video-Player/app/src/main/java/com/sdcode/videoplayer/folder/FolderItem.java | package com.sdcode.videoplayer.folder;
import com.sdcode.videoplayer.video.VideoItem;
import java.util.ArrayList;
public class FolderItem {
private String folderName;
private String folderPath;
private ArrayList<VideoItem> videoItems = new ArrayList<>();
public FolderItem(String folderName,String folderPath){
this.folderName = folderName;
this.folderPath = folderPath;
}
public FolderItem(String folderName,String folderPath,ArrayList<VideoItem> videoItems){
this.folderName = folderName;
this.folderPath = folderPath;
this.videoItems = videoItems;
}
public String getFolderName() {
return folderName;
}
public void setFolderName(String folderName) {
this.folderName = folderName;
}
public String getFolderPath() {
return folderPath;
}
public void setFolderPath(String folderPath) {
this.folderPath = folderPath;
}
public ArrayList<VideoItem> getVideoItems() {
return videoItems;
}
public void setVideoItems(ArrayList<VideoItem> videoItems) {
this.videoItems = videoItems;
}
}
| 1,155 | Java | .java | kartikhimself/Simple-Video-Player | 11 | 4 | 0 | 2019-07-03T02:35:28Z | 2019-07-02T15:42:27Z |
VideoPlayingListAdapter.java | /FileExtraction/Java_unseen/kartikhimself_Simple-Video-Player/app/src/main/java/com/sdcode/videoplayer/adapter/VideoPlayingListAdapter.java | package com.sdcode.videoplayer.adapter;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.afollestad.materialdialogs.MaterialDialog;
import com.bumptech.glide.Glide;
import com.sdcode.videoplayer.GlobalVar;
import com.sdcode.videoplayer.R;
import com.sdcode.videoplayer.video.VideoItem;
import net.steamcrafted.materialiconlib.MaterialIconView;
import java.io.File;
import java.util.ArrayList;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
public class VideoPlayingListAdapter extends RecyclerView.Adapter<VideoPlayingListAdapter.ItemHolder> {
Activity context;
private ArrayList<VideoItem> videoItems = new ArrayList<>();
public VideoPlayingListAdapter(Activity context){
this.context = context;
}
@NonNull
@Override
public ItemHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_video_playing, null);
return new ItemHolder(itemView);
}
@Override
public void onBindViewHolder(@NonNull ItemHolder itemHolder, int i) {
VideoItem videoItem = videoItems.get(i);
itemHolder.title.setText(videoItem.getVideoTitle());
itemHolder.duration.setText(videoItem.getDuration());
Glide.with(context.getApplicationContext())
.load(videoItem.getPath())
.into(itemHolder.imageView);
itemHolder.txtVideoPath.setText(videoItem.getPath());
itemHolder.container.setOnClickListener(v -> {
GlobalVar.getInstance().playingVideo = videoItem;
GlobalVar.getInstance().videoService.playVideo(0,false);
});
itemHolder.btnRemove.setOnClickListener(v -> {
videoItems.remove(i);
GlobalVar.getInstance().videoItemsPlaylist = videoItems;
updateData(videoItems);
});
}
public void updateData(ArrayList<VideoItem> items){
if(items == null) items = new ArrayList<>();
ArrayList<VideoItem> r = new ArrayList<>(items);
int currentSize = videoItems.size();
if(currentSize != 0) {
this.videoItems.clear();
this.videoItems.addAll(r);
notifyItemRangeRemoved(0, currentSize);
//tell the recycler view how many new items we added
notifyItemRangeInserted(0, r.size());
}
else {
this.videoItems.addAll(r);
notifyItemRangeInserted(0, r.size());
}
}
@Override
public int getItemCount() {
return videoItems.size();
}
public class ItemHolder extends RecyclerView.ViewHolder {
protected TextView title, duration,txtVideoPath;
protected ImageView imageView;
protected MaterialIconView btnRemove;
View container;
public ItemHolder(View view) {
super(view);
container = view;
this.txtVideoPath = view.findViewById(R.id.txtVideoPath);
this.title = view.findViewById(R.id.txtVideoTitle);
this.imageView = view.findViewById(R.id.imageView);
this.duration = view.findViewById(R.id.txtVideoDuration);
this.btnRemove = view.findViewById(R.id.btn_remove_to_playingList);
}
}
public void deleteVideo(VideoItem videoItem){
new MaterialDialog.Builder(context)
.title(context.getString(R.string.delete_video))
.content(context.getString(R.string.confirm) +" " + videoItem.getVideoTitle() + " ?")
.positiveText(context.getString(R.string.confirm_delete))
.negativeText(context.getString(R.string.confirm_cancel))
.onPositive((dialog1, which) -> {
File deleteFile = new File(videoItem.getPath());
if(deleteFile.exists()){
if(deleteFile.delete()){
GlobalVar.getInstance().isNeedRefreshFolder = true;
if(removeIfPossible(videoItem))
context.finish();
else {
updateData(videoItems);
}
}
}
})
.onNegative((dialog12, which) -> dialog12.dismiss())
.show();
}
private boolean removeIfPossible(VideoItem videoItem){
for(VideoItem video:videoItems) {
if (videoItem.getPath().equals(video.getPath())){
videoItems.remove(videoItem);
break;
}
}
GlobalVar.getInstance().videoItemsPlaylist = new ArrayList<>(videoItems);
if(videoItems.size() == 0){
return true;
}else {
GlobalVar.getInstance().playNext();
}
return false;
}
}
| 5,059 | Java | .java | kartikhimself/Simple-Video-Player | 11 | 4 | 0 | 2019-07-03T02:35:28Z | 2019-07-02T15:42:27Z |
FolderAdapter.java | /FileExtraction/Java_unseen/kartikhimself_Simple-Video-Player/app/src/main/java/com/sdcode/videoplayer/adapter/FolderAdapter.java | package com.sdcode.videoplayer.adapter;
import android.app.Activity;
import android.content.Intent;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.sdcode.videoplayer.GlobalVar;
import com.sdcode.videoplayer.folder.FolderItem;
import com.sdcode.videoplayer.FolderDetailActivity;
import com.sdcode.videoplayer.kxUtil.PreferencesUtility;
import com.sdcode.videoplayer.PlayVideoActivity;
import com.sdcode.videoplayer.R;
import java.util.ArrayList;
public class FolderAdapter extends RecyclerView.Adapter<FolderAdapter.ItemHolder> {
Activity context;
private ArrayList<FolderItem> folderItems = new ArrayList<>();
public FolderAdapter(Activity context) {
this.context = context;
}
@NonNull
@Override
public ItemHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View itemView
= LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_folder, null);
return new ItemHolder(itemView);
}
@Override
public void onBindViewHolder(@NonNull ItemHolder itemHolder, int i) {
FolderItem folderItem = folderItems.get(i);
itemHolder.folderTitle.setText(folderItem.getFolderName());
itemHolder.folderPath.setText(folderItem.getFolderPath());
itemHolder.folderSize.setText(String.valueOf(folderItem.getVideoItems().size()).concat(" ").concat(context.getString(R.string.video)));
itemHolder.container.setOnClickListener(v -> {
GlobalVar.getInstance().folderItem = folderItem;
Intent intent = new Intent(context, FolderDetailActivity.class);
context.startActivity(intent);
context.overridePendingTransition(R.anim.slide_in_left,
R.anim.slide_stay_x);
});
itemHolder.imageViewOption.setOnClickListener(v -> showBottomDialog(folderItem));
}
public void updateData(ArrayList<FolderItem> items) {
if (items == null) items = new ArrayList<>();
int currentSize = folderItems.size();
if(currentSize != 0) {
this.folderItems.clear();
this.folderItems.addAll(items);
notifyItemRangeRemoved(0, currentSize);
//tell the recycler view how many new items we added
notifyItemRangeInserted(0, items.size());
}
else {
this.folderItems.addAll(items);
notifyItemRangeInserted(0, items.size());
}
}
@Override
public int getItemCount() {
return folderItems.size();
}
public class ItemHolder extends RecyclerView.ViewHolder {
protected TextView folderTitle, folderPath, folderSize;
protected ImageView imageViewOption;
View container;
public ItemHolder(View view) {
super(view);
container = view;
this.folderTitle = view.findViewById(R.id.txtFolderName);
this.folderPath = view.findViewById(R.id.txtFolderPath);
this.folderSize = view.findViewById(R.id.txtFolderSize);
this.imageViewOption = view.findViewById(R.id.imageViewOption);
}
}
private void showBottomDialog(FolderItem folderItem) {
View view = context.getLayoutInflater().inflate(R.layout.folder_option_dialog, null);
BottomSheetDialog dialog = new BottomSheetDialog(context);
LinearLayout option_play = view.findViewById(R.id.option_play);
option_play.setOnClickListener(v -> {
if (folderItem == null || folderItem.getVideoItems() == null || folderItem.getVideoItems().size() == 0)
return;
GlobalVar.getInstance().videoItemsPlaylist = folderItem.getVideoItems();
GlobalVar.getInstance().folderItem = folderItem;
GlobalVar.getInstance().playingVideo = folderItem.getVideoItems().get(0);
GlobalVar.getInstance().videoService.playVideo(GlobalVar.getInstance().seekPosition, false);
Intent intent = new Intent(context, PlayVideoActivity.class);
context.startActivity(intent);
if (GlobalVar.getInstance().videoService != null)
GlobalVar.getInstance().videoService.releasePlayerView();
dialog.dismiss();
});
LinearLayout option_play_audio = view.findViewById(R.id.option_play_audio);
option_play_audio.setOnClickListener(v -> {
if (folderItem == null || folderItem.getVideoItems() == null || folderItem.getVideoItems().size() == 0)
return;
PreferencesUtility.getInstance(context).setAllowBackgroundAudio(true);
GlobalVar.getInstance().folderItem = folderItem;
GlobalVar.getInstance().videoItemsPlaylist = folderItem.getVideoItems();
GlobalVar.getInstance().playingVideo = folderItem.getVideoItems().get(0);
GlobalVar.getInstance().videoService.playVideo(GlobalVar.getInstance().seekPosition, false);
dialog.dismiss();
});
dialog.setContentView(view);
dialog.show();
}
}
| 5,357 | Java | .java | kartikhimself/Simple-Video-Player | 11 | 4 | 0 | 2019-07-03T02:35:28Z | 2019-07-02T15:42:27Z |
ThemeChoiceItemAdapter.java | /FileExtraction/Java_unseen/kartikhimself_Simple-Video-Player/app/src/main/java/com/sdcode/videoplayer/adapter/ThemeChoiceItemAdapter.java | package com.sdcode.videoplayer.adapter;
import android.app.Activity;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import com.sdcode.videoplayer.kxUtil.PreferencesUtility;
import com.sdcode.videoplayer.customizeUI.ThemeChoiceItem;
import com.sdcode.videoplayer.R;
import net.steamcrafted.materialiconlib.MaterialIconView;
import java.util.ArrayList;
import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;
public class ThemeChoiceItemAdapter extends RecyclerView.Adapter<ThemeChoiceItemAdapter.ItemHolder> {
Activity context;
ArrayList<ThemeChoiceItem> themeChoiceItems = new ArrayList<>();
int choiceId = 0;
PreferencesUtility preferencesUtility;
public ThemeChoiceItemAdapter(Activity context){
this.context = context;
preferencesUtility = new PreferencesUtility(context);
choiceId = preferencesUtility.getThemeSettings();
}
@NonNull
@Override
public ItemHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.theme_choice_item, null);
return new ItemHolder(itemView);
}
@Override
public void onBindViewHolder(@NonNull ItemHolder itemHolder, int i) {
ThemeChoiceItem themeChoiceItem = themeChoiceItems.get(i);
itemHolder.layoutContainer.setBackgroundColor(ContextCompat.getColor(context,themeChoiceItem.getColor()));
itemHolder.imageView.setColor(themeChoiceItem.getId() == choiceId ? Color.GREEN : Color.WHITE);
itemHolder.imageView.setVisibility(themeChoiceItem.getId() == choiceId ? View.VISIBLE:View.INVISIBLE);
itemHolder.container.setOnClickListener(v -> {
choiceId = themeChoiceItem.getId();
updateData(themeChoiceItems);
preferencesUtility.setThemSettings(themeChoiceItem.getId());
});
}
public void updateData(ArrayList<ThemeChoiceItem> items){
if(items == null) items = new ArrayList<>();
ArrayList<ThemeChoiceItem> r = new ArrayList<>(items);
int currentSize = themeChoiceItems.size();
if(currentSize != 0) {
this.themeChoiceItems.clear();
this.themeChoiceItems.addAll(r);
notifyDataSetChanged();
}
else {
this.themeChoiceItems.addAll(r);
notifyDataSetChanged();
}
}
@Override
public int getItemCount() {
return themeChoiceItems.size();
}
public class ItemHolder extends RecyclerView.ViewHolder {
protected RelativeLayout layoutContainer;
protected MaterialIconView imageView;
View container;
public ItemHolder(View view) {
super(view);
container = view;
this.layoutContainer = view.findViewById(R.id.layout_root);
this.imageView = view.findViewById(R.id.btn_choice);
}
}
}
| 3,101 | Java | .java | kartikhimself/Simple-Video-Player | 11 | 4 | 0 | 2019-07-03T02:35:28Z | 2019-07-02T15:42:27Z |
VideoAdapter.java | /FileExtraction/Java_unseen/kartikhimself_Simple-Video-Player/app/src/main/java/com/sdcode/videoplayer/adapter/VideoAdapter.java | package com.sdcode.videoplayer.adapter;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.afollestad.materialdialogs.MaterialDialog;
import com.bumptech.glide.Glide;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.sdcode.videoplayer.GlobalVar;
import com.sdcode.videoplayer.BaseActivity;
import com.sdcode.videoplayer.customizeUI.FastScroller;
import com.sdcode.videoplayer.FolderDetailActivity;
import com.sdcode.videoplayer.kxUtil.PreferencesUtility;
import com.sdcode.videoplayer.kxUtil.kxUtils;
import com.sdcode.videoplayer.PlayVideoActivity;
import com.sdcode.videoplayer.R;
import com.sdcode.videoplayer.SearchActivity;
import com.sdcode.videoplayer.storageProcess.RenameVideoDialog;
import com.sdcode.videoplayer.video.VideoItem;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class VideoAdapter extends RecyclerView.Adapter<VideoAdapter.ItemHolder> implements FastScroller.BubbleTextGetter {
Activity context;
private ArrayList<VideoItem> videoItems = new ArrayList<>();
public VideoAdapter(Activity context){
this.context = context;
}
@NonNull
@Override
public ItemHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View itemView;
if(context instanceof SearchActivity)
itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_video, null);
else if(PreferencesUtility.getInstance(context).isAlbumsInGrid())
itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_video_grid, null);
else
itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_video, null);
return new ItemHolder(itemView);
}
@Override
public void onBindViewHolder(@NonNull ItemHolder itemHolder, int i) {
VideoItem videoItem = videoItems.get(i);
itemHolder.title.setText(videoItem.getVideoTitle());
itemHolder.duration.setText(videoItem.getDuration());
Glide.with(context.getApplicationContext())
.load(videoItem.getPath())
.into(itemHolder.imageView);
itemHolder.txtVideoPath.setText("/".concat(videoItem.getFolderName()).concat(" ").concat(videoItem.getFileSize()));
itemHolder.container.setBackgroundColor(videoItem.isSelected() ? ContextCompat.getColor(context,R.color.multiselected) : Color.TRANSPARENT);
itemHolder.container.setOnLongClickListener(v -> {
if(context instanceof FolderDetailActivity) {
GlobalVar.getInstance().isMutilSelectEnalble = true;
videoItem.setLongClick(true);
videoItem.setSelected(!videoItem.isSelected());
itemHolder.container.setBackgroundColor(videoItem.isSelected() ? ContextCompat.getColor(context, R.color.multiselected) : Color.TRANSPARENT);
if (context instanceof BaseActivity) {
((BaseActivity) context).updateMultiSelectedState();
}
}
return false;
});
itemHolder.container.setOnClickListener(v -> {
GlobalVar.getInstance().videoItemsPlaylist = videoItems;
GlobalVar.getInstance().playingVideo = videoItem;
GlobalVar.getInstance().seekPosition = 0;
if(GlobalVar.getInstance().getPlayer() == null){
return;
}else if(!GlobalVar.getInstance().isMutilSelectEnalble) {
if(!GlobalVar.getInstance().isPlayingAsPopup()){
GlobalVar.getInstance().videoService.playVideo(GlobalVar.getInstance().seekPosition,false);
Intent intent = new Intent(context, PlayVideoActivity.class);
context.startActivity(intent);
if(GlobalVar.getInstance().videoService != null)
GlobalVar.getInstance().videoService.releasePlayerView();
}else {
((BaseActivity) context).showFloatingView(context,true);
}
}else if(checkError(videoItems,i) && !videoItems.get(i).isLongClick()) {
videoItem.setSelected(!videoItem.isSelected());
itemHolder.container.setBackgroundColor(videoItem.isSelected() ? ContextCompat.getColor(context,R.color.multiselected) : Color.TRANSPARENT);
if(context instanceof BaseActivity){
((BaseActivity) context).updateMultiSelectedState();
}
}
try {
videoItem.setLongClick(false);
}catch (IndexOutOfBoundsException e){
e.printStackTrace();
}
});
itemHolder.imageViewOption.setOnClickListener(v -> {
showBottomDialog(videoItem);
});
}
public void updateData(ArrayList<VideoItem> items){
if(items == null) items = new ArrayList<>();
ArrayList<VideoItem> r = new ArrayList<>(items);
int currentSize = videoItems.size();
if(currentSize != 0) {
this.videoItems.clear();
this.videoItems.addAll(r);
notifyItemRangeRemoved(0, currentSize);
//tell the recycler view how many new items we added
notifyItemRangeInserted(0, r.size());
}
else {
this.videoItems.addAll(r);
notifyItemRangeInserted(0, r.size());
}
}
@Override
public int getItemCount() {
return videoItems.size();
}
public ArrayList<VideoItem> getVideoItems(){
if(videoItems == null) return new ArrayList<>();
return videoItems;
}
@Override
public String getTextToShowInBubble(int pos) {
return null;
}
public class ItemHolder extends RecyclerView.ViewHolder {
protected TextView title, duration,txtVideoPath;
protected ImageView imageView,imageViewOption;
View container;
public ItemHolder(View view) {
super(view);
container = view;
this.txtVideoPath = view.findViewById(R.id.txtVideoPath);
this.title = view.findViewById(R.id.txtVideoTitle);
this.imageView = view.findViewById(R.id.imageView);
this.duration = view.findViewById(R.id.txtVideoDuration);
this.imageViewOption = view.findViewById(R.id.imageViewOption);
}
}
private void showBottomDialog(VideoItem videoItem) {
View view = context.getLayoutInflater().inflate(R.layout.video_option_dialog, null);
BottomSheetDialog dialog = new BottomSheetDialog(context);
LinearLayout option_playPopup = view.findViewById(R.id.option_play_popup);
option_playPopup.setOnClickListener(v -> {
GlobalVar.getInstance().playingVideo = videoItem;
GlobalVar.getInstance().videoItemsPlaylist = videoItems;
if (context instanceof BaseActivity) {
((BaseActivity) context).showFloatingView(context, true);
}
dialog.dismiss();
});
LinearLayout option_play_audio = view.findViewById(R.id.option_play_audio);
option_play_audio.setOnClickListener(v -> {
PreferencesUtility.getInstance(context).setAllowBackgroundAudio(true);
GlobalVar.getInstance().videoItemsPlaylist = videoItems;
GlobalVar.getInstance().playingVideo = videoItem;
GlobalVar.getInstance().videoService.playVideo(GlobalVar.getInstance().seekPosition, false);
dialog.dismiss();
});
LinearLayout option_share = view.findViewById(R.id.option_share);
option_share.setOnClickListener(v -> {
context.startActivity(Intent.createChooser(kxUtils.shareVideo(context,videoItem),context.getString(R.string.action_share)));
dialog.dismiss();
});
LinearLayout option_rename = view.findViewById(R.id.option_rename);
option_rename.setOnClickListener(v -> {
RenameVideoDialog renamePlaylistDialog = RenameVideoDialog.newInstance(context,this,videoItem);
renamePlaylistDialog.show(((AppCompatActivity) context).getSupportFragmentManager(),"");
dialog.dismiss();
});
LinearLayout option_info = view.findViewById(R.id.option_info);
option_info.setOnClickListener(v -> {
dialog.dismiss();
createDialog(videoItem);
});
LinearLayout option_delete = view.findViewById(R.id.option_delete);
option_delete.setOnClickListener(v -> {
dialog.dismiss();
new MaterialDialog.Builder(context)
.title(context.getString(R.string.delete_video))
.content(context.getString(R.string.confirm) +" " + videoItem.getVideoTitle() + " ?")
.positiveText(context.getString(R.string.confirm_delete))
.negativeText(context.getString(R.string.confirm_cancel))
.onPositive((dialog1, which) -> {
File deleteFile = new File(videoItem.getPath());
if(deleteFile.exists()){
if(deleteFile.delete()){
videoItems.remove(videoItem);
updateData(videoItems);
if(context instanceof BaseActivity){
((BaseActivity) context).updateListAfterDelete(videoItems);
}
}
}
})
.onNegative((dialog12, which) -> dialog12.dismiss())
.show();
});
dialog.setContentView(view);
dialog.show();
}
private void createDialog(VideoItem videoItem){
AlertDialog.Builder builder = new AlertDialog.Builder(context);
final LayoutInflater inflater = context.getLayoutInflater();
View view = inflater.inflate(R.layout.content_video_info,null);
TextView txtVideoTitle = view.findViewById(R.id.txtVideoTitle);
txtVideoTitle.setText(videoItem.getVideoTitle());
TextView txtLocation = view.findViewById(R.id.txtLocation_value);
txtLocation.setText(videoItem.getPath());
TextView txtVideoFormat = view.findViewById(R.id.txtFormat_value);
txtVideoFormat.setText(kxUtils.getFileExtension(videoItem.getPath()));
TextView txtDuration = view.findViewById(R.id.txtDuration_value);
txtDuration.setText(videoItem.getDuration());
TextView txtDateAdded = view.findViewById(R.id.txtDateAdded_value);
txtDateAdded.setText(videoItem.getDate_added());
TextView txtVideoSize = view.findViewById(R.id.txtFileSize_value);
txtVideoSize.setText(videoItem.getFileSize());
TextView txtVideoResolution = view.findViewById(R.id.txResolution_value);
txtVideoResolution.setText(videoItem.getResolution());
builder.setView(view);
AlertDialog dialog = builder.create();
dialog.show();
}
private boolean checkError(List<VideoItem> songs, int position){
if(songs.size() >= position && position >= 0) return true;
return false;
}
public int getTotalVideoSelected(){
int totalVideoSelected = 0;
if(videoItems == null || videoItems.size() == 0) return 0;
for (VideoItem videoItem: videoItems){
if(videoItem.isSelected()) totalVideoSelected += 1;
}
return totalVideoSelected;
}
public ArrayList<VideoItem> getVideoItemsSelected(){
ArrayList<VideoItem> resultList = new ArrayList<>();
for (VideoItem videoItem: videoItems){
if(videoItem.isSelected()) resultList.add(videoItem);
}
return resultList;
}
public void deleteListVideoSelected(){
ArrayList<VideoItem> deletedList = getVideoItemsSelected();
new MaterialDialog.Builder(context)
.title(context.getString(R.string.delete_video))
.content(context.getString(R.string.confirm) +" " + String.valueOf(deletedList.size()) + " " + context.getString(R.string.video) + " ?")
.positiveText(context.getString(R.string.confirm_delete))
.negativeText(context.getString(R.string.confirm_cancel))
.onPositive((dialog1, which) -> {
for(VideoItem item :deletedList){
File deleteFile = new File(item.getPath());
if (deleteFile.exists()) {
if (deleteFile.delete()) {
videoItems.remove(item);
}
}
}
updateData(videoItems);
})
.onNegative((dialog12, which) -> dialog12.dismiss())
.show();
}
}
| 13,448 | Java | .java | kartikhimself/Simple-Video-Player | 11 | 4 | 0 | 2019-07-03T02:35:28Z | 2019-07-02T15:42:27Z |
VideoService.java | /FileExtraction/Java_unseen/kartikhimself_Simple-Video-Player/app/src/main/java/com/sdcode/videoplayer/videoService/VideoService.java | package com.sdcode.videoplayer.videoService;
import android.Manifest;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.media.AudioManager;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationManagerCompat;
import android.provider.Settings;
import android.support.v4.media.session.MediaSessionCompat;
import androidx.media.app.NotificationCompat;
import androidx.palette.graphics.Palette;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.google.android.exoplayer2.ExoPlaybackException;
import com.google.android.exoplayer2.PlaybackParameters;
import com.google.android.exoplayer2.Player;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.Timeline;
import com.google.android.exoplayer2.source.TrackGroupArray;
import com.google.android.exoplayer2.trackselection.TrackSelectionArray;
import com.google.android.exoplayer2.ui.PlayerView;
import com.sdcode.videoplayer.GlobalVar;
import com.sdcode.videoplayer.customizeUI.PlayPauseDrawable;
import com.sdcode.videoplayer.FirstActivity;
import com.sdcode.videoplayer.kxUtil.MediaButtonIntentReceiver;
import com.sdcode.videoplayer.kxUtil.PreferencesUtility;
import com.sdcode.videoplayer.kxUtil.kxUtils;
import com.sdcode.videoplayer.PlayVideoActivity;
import com.sdcode.videoplayer.PlayerManager;
import com.sdcode.videoplayer.R;
import com.sdcode.videoplayer.video.VideoItem;
import java.util.Random;
public class VideoService extends Service implements AudioManager.OnAudioFocusChangeListener{
PreferencesUtility preferencesUtility;
private PlayerManager playerManager;
//private SimpleExoPlayer simpleExoPlayer;
private VideoItem currentVideoPlaying = new VideoItem();
PlayPauseDrawable playPauseDrawable = new PlayPauseDrawable();
PlayerView playerView;
View layout_drag;
private WindowManager windowManager;
private WindowManager.LayoutParams params;
private FrameLayout container;
private static final int CONTROL_HIDE_TIMEOUT = 4000;
private long lastTouchTime;
ImageButton btnPausePlay;
ImageView btnFullScreenMode,btnClose,btnResize;
RelativeLayout relativeLayout;
int popup_params;
PopupSize popupsize = PopupSize.SMALL;
boolean isVideoPlaying = false;
private AudioManager mAudioManager;
private boolean mPlayOnAudioFocus = false;
private static final float MEDIA_VOLUME_DEFAULT = 1.0f;
private static final float MEDIA_VOLUME_DUCK = 0.2f;
GlobalVar mGlobalVar = GlobalVar.getInstance();
private IntentFilter becomingNoisyReceiverIntentFilter = new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
private final BroadcastReceiver becomingNoisyReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, @NonNull Intent intent) {
if(intent.getAction() != null)
if (intent.getAction().equals(AudioManager.ACTION_AUDIO_BECOMING_NOISY)) {
if(isPlaying())
pause();
}
}
};
public static final String NOTIFICATIONCHANNELID = "id";
private NotificationManagerCompat mNotificationManager;
private long mNotificationPostTime = 0;
private MediaSessionCompat mSession;
public static final String SDCODEMUSICPLAYERPACKAGE = "com.sdcdoe.videoplayer";
public static final String SERVICECMD = SDCODEMUSICPLAYERPACKAGE +".video_service_blutooth";
public static final String TOGGLEPAUSE_ACTION = SDCODEMUSICPLAYERPACKAGE +".togglepause";
public static final String PREVIOUS_ACTION = SDCODEMUSICPLAYERPACKAGE +".previous";
public static final String PREVIOUS_FORCE_ACTION = SDCODEMUSICPLAYERPACKAGE +".previous.force";
public static final String NEXT_ACTION = SDCODEMUSICPLAYERPACKAGE +".next";
public static final String CLOSE_ACTION = SDCODEMUSICPLAYERPACKAGE +".close";
public static final String REPEAT_ACTION = SDCODEMUSICPLAYERPACKAGE + ".repeat";
public static final String SHUFFLE_ACTION = SDCODEMUSICPLAYERPACKAGE + ".shuffle";
public static final String STOP_ACTION = SDCODEMUSICPLAYERPACKAGE + ".stop";
public static final String PAUSE_ACTION = SDCODEMUSICPLAYERPACKAGE + "pause";
public static final String PLAY_ACTION = SDCODEMUSICPLAYERPACKAGE + "play";
public static final String CMDNAME = "command";
int notificationId = hashCode();
@Override
public void onAudioFocusChange(int focusChange) {
switch (focusChange) {
case AudioManager.AUDIOFOCUS_GAIN:
if (mPlayOnAudioFocus && !isPlaying()) {
handleAction(PLAY_ACTION);
} else if (isPlaying()) {
setVolume(MEDIA_VOLUME_DEFAULT);
}
mPlayOnAudioFocus = false;
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
setVolume(MEDIA_VOLUME_DUCK);
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
if (isPlaying()) {
mPlayOnAudioFocus = true;
handleAction(PAUSE_ACTION);
}
break;
case AudioManager.AUDIOFOCUS_LOSS:
mAudioManager.abandonAudioFocus(this);
mPlayOnAudioFocus = false;
handleAction(PAUSE_ACTION);
break;
}
}
public enum PopupSize {
SMALL,
NORMAL,
LARGE
}
public void onCreate() {
super.onCreate();
initExoPlayer();
setUpMediaSession();
preferencesUtility = PreferencesUtility.getInstance(this);
mNotificationManager = NotificationManagerCompat.from(this);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
createChannelId();
Notification notification = new Notification.Builder(this, NOTIFICATIONCHANNELID)
.setContentTitle("")
.setContentText("").build();
startForeground(1, notification);
}
mAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
registerReceiver(becomingNoisyReceiver,becomingNoisyReceiverIntentFilter);
}
public boolean isPlaying(){
if(playerManager == null) return false;
return playerManager.getPlayWhenReady();
}
public void setVolume(float volume){
if(playerManager != null) playerManager.setVolume(volume);
}
public void initExoPlayer(){
if(playerManager == null) playerManager = new PlayerManager(getApplicationContext());
playerManager.getSimpleExoPlayer().addListener(new Player.EventListener() {
@Override
public void onTimelineChanged(Timeline timeline, Object manifest, int reason) {
}
@Override
public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
}
@Override
public void onLoadingChanged(boolean isLoading) {
}
@Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
if(playbackState == Player.STATE_ENDED){
if(mGlobalVar.videoItemsPlaylist.size() == 0 || getNextPosition() == -1)
return ;
if(getNextPosition() >= mGlobalVar.videoItemsPlaylist.size())
return;
mGlobalVar.playingVideo = mGlobalVar.videoItemsPlaylist.get(getNextPosition());
playVideo(0,false);
}
}
@Override
public void onRepeatModeChanged(int repeatMode) {
}
@Override
public void onShuffleModeEnabledChanged(boolean shuffleModeEnabled) {
createShuffleArray();
}
@Override
public void onPlayerError(ExoPlaybackException error) {
Log.d("ZZ", error.getCause().toString());
handleAction(NEXT_ACTION);
}
@Override
public void onPositionDiscontinuity(int reason) {
}
@Override
public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) {
}
@Override
public void onSeekProcessed() {
GlobalVar.getInstance().isSeekBarProcessing = false;
}
});
}
private boolean canDrawPopup(){
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP_MR1 ) {
return true;
}
if(Settings.canDrawOverlays(getApplicationContext())){
return true;
}
return false;
}
private void addPopupView(){
removePopupView();
container = new FrameLayout(this) {
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return super.onInterceptTouchEvent(ev);
}
};
LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.popup_video, container);
playerView = view.findViewById(R.id.player_view);
playerView.setPlayer(playerManager.getCurrentPlayer());
layout_drag = view.findViewById(R.id.layout_all_control_container);
relativeLayout = view.findViewById(R.id.layout_control_top);
btnFullScreenMode = view.findViewById(R.id.btnFullScreenMode);
btnFullScreenMode.setOnClickListener(v -> {
playerManager.onFullScreen();
removePopup();
Intent intent = new Intent(VideoService.this, PlayVideoActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
});
btnClose = view.findViewById(R.id.btnClosePopUp);
btnClose.setOnClickListener(v -> removePopup());
btnResize = view.findViewById(R.id.btnResize);
btnResize.setOnClickListener(v -> changePopUpSize());
btnPausePlay = view.findViewById(R.id.btnPlayPause);
btnPausePlay.setImageDrawable(playPauseDrawable);
playPauseDrawable.transformToPause(false);
btnPausePlay.setOnClickListener(v -> {
if(playerManager != null) isVideoPlaying = playerManager.getPlayWhenReady();
handleAction(TOGGLEPAUSE_ACTION);
});
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
popup_params = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
} else {
popup_params = WindowManager.LayoutParams.TYPE_PHONE;
}
setPopupSize(0,0);
windowManager.addView(container, params);
container.setVisibility(View.GONE);
setDragListeners();
Runnable r = new Runnable() {
@Override
public void run() {
if (System.currentTimeMillis() - lastTouchTime > CONTROL_HIDE_TIMEOUT) {
hideControlContainer();
}
if(playerManager != null){
if(isVideoPlaying != playerManager.getPlayWhenReady()){
isVideoPlaying = playerManager.getPlayWhenReady();
if (isVideoPlaying)
playPauseDrawable.transformToPause(false);
else playPauseDrawable.transformToPlay(false);
}
}
layout_drag.postDelayed(this, 1000);
}
};
layout_drag.postDelayed(r,500);
}
private void showControl(){
if(btnPausePlay != null) btnPausePlay.setVisibility(View.VISIBLE);
if(relativeLayout != null) relativeLayout.setVisibility(View.VISIBLE);
}
private void hideControlContainer(){
if(btnPausePlay != null) btnPausePlay.setVisibility(View.GONE);
if(relativeLayout != null) relativeLayout.setVisibility(View.GONE);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
String action = intent.getAction();
if(action!= null && action.equals(SERVICECMD))
if(intent.getExtras() != null) action = intent.getExtras().getString(CMDNAME);
handleAction(action);
return START_NOT_STICKY;
}
public void handleAction(String action){
if(action != null && playerManager != null){
if (action.equals(NEXT_ACTION)) {
gotoNext();
}else if(action.equals(PREVIOUS_ACTION)){
prev();
}else if(action.equals(TOGGLEPAUSE_ACTION)){
if(playerManager.getPlayWhenReady()) pause();
else play();
lastTouchTime = System.currentTimeMillis();
if(container != null) {
if (playerManager.getPlayWhenReady())
playPauseDrawable.transformToPause(false);
else playPauseDrawable.transformToPlay(false);
}
}else if(action.equals(CLOSE_ACTION)){
releasePlayerView();
mNotificationManager.cancel(notificationId);
stopForeground(true);
playerManager.setPlayWhenReady(false);
return;
}else if(action.equals(PAUSE_ACTION)){
pause();
playPauseDrawable.transformToPlay(false);
}else if(action.equals(PLAY_ACTION)){
play();
playPauseDrawable.transformToPause(false);
}
if(buildNotification() != null && preferencesUtility.isAllowBackgroundAudio())
startForeground(notificationId, buildNotification());
}
}
public SimpleExoPlayer getVideoPlayer(){
return playerManager.getCurrentPlayer();
}
public PlayerManager getPlayerManager(){
return playerManager;
}
@Override
public IBinder onBind(Intent arg0){
return new VideoBinder();
}
@Override
public boolean onUnbind(Intent intent){
return true;
}
@Override
public void onDestroy() {
super.onDestroy();
mSession.release();
unregisterReceiver(becomingNoisyReceiver);
playerManager.releasePlayer();
stopForeground(true);
if(mAudioManager != null)
mAudioManager.abandonAudioFocus(this);
releasePlayerView();
}
public class VideoBinder extends Binder {
public VideoService getService(){
return VideoService.this;
}
}
private Notification buildNotification() {
if(artWork == null) {
loadImage(mGlobalVar.playingVideo);
return null;
}
if (GlobalVar.getInstance().playingVideo == null) return null;
VideoItem videoItem = GlobalVar.getInstance().playingVideo;
final String content = videoItem.getPath();
final boolean isPlaying = playerManager.getPlayWhenReady();
int playButtonResId = isPlaying
? R.drawable.ic_pause_white : R.drawable.ic_play_white;
Intent nowPlayingIntent = new Intent(this, FirstActivity.class);
PendingIntent clickIntent = PendingIntent.getActivity(this, 0, nowPlayingIntent, PendingIntent.FLAG_UPDATE_CURRENT);
if (mNotificationPostTime == 0) {
mNotificationPostTime = System.currentTimeMillis();
}
androidx.core.app.NotificationCompat.Builder builder = new androidx.core.app.NotificationCompat.Builder(this, NOTIFICATIONCHANNELID)
.setSmallIcon(R.drawable.ic_stat_name)
.setLargeIcon(artWork)
.setContentIntent(clickIntent)
.setContentTitle(videoItem.getVideoTitle())
.setContentText(content)
.setWhen(mNotificationPostTime)
.addAction(R.drawable.ic_skip_previous_white,
"",
retrievePlaybackAction(PREVIOUS_ACTION))
.addAction(playButtonResId, "",
retrievePlaybackAction(TOGGLEPAUSE_ACTION))
.addAction(R.drawable.ic_skip_next_white,
"",
retrievePlaybackAction(NEXT_ACTION))
.addAction(R.drawable.ic_btn_delete, "",
retrievePlaybackAction(CLOSE_ACTION));
builder.setShowWhen(false);
builder.setVisibility(androidx.core.app.NotificationCompat.VISIBILITY_PUBLIC);
NotificationCompat.MediaStyle style = new NotificationCompat.MediaStyle()
.setMediaSession(mSession.getSessionToken())
.setShowActionsInCompactView(1, 2, 3, 0);
builder.setStyle(style);
if (artWork != null )
builder.setColor(Palette.from(artWork).generate().getVibrantColor(Color.parseColor("#403f4d")));
Notification n = builder.build();
return n;
}
Bitmap artWork;
private void loadImage(VideoItem videoItem){
Glide.with(this).asBitmap()
.load(videoItem.getPath())
.listener(new RequestListener<Bitmap>() {
@Override
public boolean onLoadFailed(@Nullable GlideException e, Object o, Target<Bitmap> target, boolean b) {
//Toast.makeText(cxt, getResources().getString(R.string.unexpected_error_occurred_try_again), Toast.LENGTH_SHORT).show();
return false;
}
@Override
public boolean onResourceReady(Bitmap resource, Object model, Target<Bitmap> target, com.bumptech.glide.load.DataSource dataSource, boolean isFirstResource) {
artWork = resource;
if(preferencesUtility.isAllowBackgroundAudio())
startForeground(notificationId, buildNotification());
return false;
}
}
).submit();
}
private void setUpMediaSession() {
ComponentName mediaButtonReceiverComponentName = new ComponentName(getApplicationContext(), MediaButtonIntentReceiver.class);
Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
mediaButtonIntent.setComponent(mediaButtonReceiverComponentName);
PendingIntent mediaButtonReceiverPendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, mediaButtonIntent, 0);
mSession = new MediaSessionCompat(this, "Music Player");
mSession.setCallback(new MediaSessionCompat.Callback() {
@Override
public void onPause() {
pause();
//mPausedByTransientLossOfFocus = false;
}
@Override
public void onPlay() {
play();
}
@Override
public void onSkipToNext() {
gotoNext();
}
@Override
public void onSkipToPrevious() {
prev();
}
@Override
public void onStop() {
releasePlayerView();
}
@Override
public boolean onMediaButtonEvent(Intent mediaButtonEvent) {
return MediaButtonIntentReceiver.handleIntent(VideoService.this, mediaButtonEvent);
}
});
mSession.setFlags(MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS| MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS);
mSession.setMediaButtonReceiver(mediaButtonReceiverPendingIntent);
}
private void pause() {
if(playerManager != null)
playerManager.setPlayWhenReady(false);
}
private void play(){
if(playerManager != null && reQuestAudioFocus())
playerManager.setPlayWhenReady(true);
}
private void prev(){
VideoItem videoItem = getPreviousVideo();
if(videoItem == null) return;
mGlobalVar.playingVideo = videoItem;
playVideo(0,false);
}
private VideoItem getPreviousVideo(){
int prPos = getPrePosition();
if(mGlobalVar.videoItemsPlaylist.size() == 0 || prPos == -1) return null;
return mGlobalVar.videoItemsPlaylist.get(prPos);
}
private int getPrePosition(){
int previousPosition = 0;
if(playerManager.getCurrentPlayer().getShuffleModeEnabled()){
if(getCurrentShufflePosition() <= 0) return shuffleArray[shuffleArray.length - 1];
return shuffleArray[getCurrentShufflePosition() - 1];
}else{
previousPosition = getCurrentPosition() -1;
if(previousPosition < 0) previousPosition = mGlobalVar.videoItemsPlaylist.size() - 1;
//if(currentPosition < 0) currentPosition = (simpleExoPlayer.getRepeatMode() == Player.REPEAT_MODE_ONE)? -1: mGlobalVar.videoItemsPlaylist.size() - 1;
}
return previousPosition;
}
public int getCurrentPosition(){
int currentPosition = 0;
if(mGlobalVar.videoItemsPlaylist.size() == 0) return -1;
for(int i = 0; i < mGlobalVar.videoItemsPlaylist.size(); i++){
if(mGlobalVar.playingVideo.getPath().equals(mGlobalVar.videoItemsPlaylist.get(i).getPath())){
currentPosition = i ;
}
}
return currentPosition;
}
private void gotoNext(){
if(getNextVideo() == null) return;
mGlobalVar.playingVideo = getNextVideo();
playVideo(0,false);
}
private VideoItem getNextVideo(){
if(mGlobalVar.videoItemsPlaylist.size() == 0 || getForceNextPosition() <= -1) return null;
if(getForceNextPosition() >= mGlobalVar.videoItemsPlaylist.size()) return null;
return mGlobalVar.videoItemsPlaylist.get(getForceNextPosition());
}
private int getForceNextPosition(){
int nextPosition = 0;
if(playerManager.getCurrentPlayer().getShuffleModeEnabled()){
if(getCurrentShufflePosition() >= shuffleArray.length - 1) return shuffleArray[0];
return shuffleArray[getCurrentShufflePosition() + 1];
}else{
nextPosition = getCurrentPosition() + 1;
if(nextPosition >= mGlobalVar.videoItemsPlaylist.size()) nextPosition = 0;
}
return nextPosition;
}
private int getNextPosition(){
int currentPosition = 0;
if(playerManager.getCurrentPlayer().getShuffleModeEnabled()){
if(getCurrentShufflePosition() >= shuffleArray.length - 1) return -1;
return shuffleArray[getCurrentShufflePosition() + 1];
}else{
for(int i = 0; i < mGlobalVar.videoItemsPlaylist.size(); i++){
if(mGlobalVar.playingVideo.getPath().equals(mGlobalVar.videoItemsPlaylist.get(i).getPath())){
currentPosition = i + 1;
if(currentPosition >= mGlobalVar.videoItemsPlaylist.size()) currentPosition = (playerManager.getCurrentPlayer().getRepeatMode() == Player.REPEAT_MODE_ONE)? -1: 0;
}
}
}
return currentPosition;
}
private PendingIntent retrievePlaybackAction(final String action) {
final ComponentName serviceName = new ComponentName(this, VideoService.class);
Intent intent = new Intent(action);
intent.setComponent(serviceName);
return PendingIntent.getService(this, 0, intent, 0);
}
public boolean reQuestAudioFocus(){
int status = mAudioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
return status == AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
}
public void playVideo(long seekPosition, boolean playAsPopup){
if(!reQuestAudioFocus()) return;
if(playerManager == null)
initExoPlayer();
if(!currentVideoPlaying.getPath().contains(GlobalVar.getInstance().getPath())){
currentVideoPlaying = GlobalVar.getInstance().playingVideo;
playerManager.prepare(true, false);
//if(seekPosition >0) simpleExoPlayer.seekTo(seekPosition);
playerManager.setPlayWhenReady(GlobalVar.getInstance().isPlaying);
if (playerManager.getPlayWhenReady()) {
playPauseDrawable.transformToPause(true);
} else {
playPauseDrawable.transformToPlay(true);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (kxUtils.checkPermission(Manifest.permission.READ_EXTERNAL_STORAGE)) {
loadImage(GlobalVar.getInstance().playingVideo);
} else artWork = null;
} else loadImage(GlobalVar.getInstance().playingVideo);
}
if(playAsPopup && container == null) if (canDrawPopup()) {
addPopupView();
if(container != null) container.setVisibility(View.VISIBLE);
}
}
private void setDragListeners() {
layout_drag.setOnTouchListener(new View.OnTouchListener() {
private int initialX;
private int initialY;
private float initialTouchX;
private float initialTouchY;
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
initialX = params.x;
initialY = params.y;
initialTouchX = event.getRawX();
initialTouchY = event.getRawY();
lastTouchTime = System.currentTimeMillis();
showControl();
break;
case MotionEvent.ACTION_MOVE:
params.x = initialX
+ (int) (event.getRawX() - initialTouchX);
params.y = initialY
+ (int) (event.getRawY() - initialTouchY);
if(container != null)
windowManager.updateViewLayout(container, params);
v.performClick();
break;
default:
return false;
}
return true;
}
});
}
private void changePopUpSize(){
if(params != null)
setPopupSize(params.x, params.y);
else
setPopupSize(0, 0);
windowManager.updateViewLayout(container, params);
}
private void setPopupSize(int x, int y){
int baseSize = Resources.getSystem().getDisplayMetrics().widthPixels;
if(getApplicationContext().getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
baseSize = Resources.getSystem().getDisplayMetrics().heightPixels;
if(popupsize == PopupSize.SMALL){
popupsize = PopupSize.NORMAL;
params = new WindowManager.LayoutParams(
(baseSize / 2),
(baseSize / (2*3/2)),
popup_params,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.TOP | Gravity.START;
params.x = x;
params.y = y;
}else if(popupsize == PopupSize.NORMAL){
popupsize = PopupSize.LARGE;
params = new WindowManager.LayoutParams(
(int) (baseSize / 1.6),
(int)(baseSize / (1.6*3/2)),
popup_params,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.TOP | Gravity.START;
params.x = x;
params.y = y;
}else if(popupsize == PopupSize.LARGE){
popupsize = PopupSize.SMALL;
params = new WindowManager.LayoutParams(
(int) (baseSize / 1.3),
(int)(baseSize / (1.3*1.5)),
popup_params,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.TOP | Gravity.START;
params.x = x;
params.y = y;
}
}
public void closeBackgroundMode(){
if(playerManager.getCurrentPlayer().getPlaybackState() != Player.STATE_READY) return;
if(mNotificationManager != null){
stopForeground(true);
mNotificationManager.cancel(notificationId);
playerManager.getCurrentPlayer().setPlayWhenReady(false);
play();
}
}
public void openBackgroundMode(){
if(playerManager.getCurrentPlayer().getPlaybackState() != Player.STATE_READY) return;
if(buildNotification() != null)
startForeground(notificationId, buildNotification());
}
public void removePopup(){
if(preferencesUtility.isAllowBackgroundAudio()){
removePopupView();
}else handleAction(CLOSE_ACTION);
}
private void removePopupView(){
if(windowManager != null && container!= null) {
windowManager.removeView(container);
container = null;
}
}
public boolean isPlayingAsPopup(){
if(container != null) return true;
return false;
}
public void releasePlayerView() {
if(playerView != null){
playerView.setPlayer(null);
playerView = null;
}
removePopupView();
}
@RequiresApi(Build.VERSION_CODES.O)
private void createChannelId(){
String channelName = "Music Player Background Service";
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATIONCHANNELID,
channelName, NotificationManager.IMPORTANCE_LOW);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setShowBadge(true);
notificationChannel.enableVibration(false);
notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
assert manager != null;
manager.createNotificationChannel(notificationChannel);
}
public int[] shuffleArray = new int[10];
public void createShuffleArray(){
if(mGlobalVar.videoItemsPlaylist.size() <= 1) return;
shuffleArray = new int[mGlobalVar.videoItemsPlaylist.size()];
for(int i = 0; i< mGlobalVar.videoItemsPlaylist.size(); i++){
shuffleArray[i] = i;
}
shuffleArray(shuffleArray);
}
private void shuffleArray(int[] ar)
{
// If running on Java 6 or older, use `new Random()` on RHS here
Random rand = new Random();
for (int i = ar.length - 1; i > 0; i--)
{
int index = rand.nextInt(i + 1);
// Simple swap
int a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
}
private int getCurrentShufflePosition() {
int currentPlayingPosition = -1;
if(shuffleArray.length != mGlobalVar.videoItemsPlaylist.size()) createShuffleArray();
if (mGlobalVar.videoItemsPlaylist.size() == 0)
return -1;
for (int i = 0; i < mGlobalVar.videoItemsPlaylist.size(); i++) {
if (mGlobalVar.playingVideo.getPath().equals(mGlobalVar.videoItemsPlaylist.get(i).getPath()))
currentPlayingPosition = i;
}
if (currentPlayingPosition == -1 || shuffleArray.length == 0)
return -1;
for (int j = 0; j < shuffleArray.length; j++)
if (currentPlayingPosition == shuffleArray[j])
return j;
return -1;
}
}
| 33,533 | Java | .java | kartikhimself/Simple-Video-Player | 11 | 4 | 0 | 2019-07-03T02:35:28Z | 2019-07-02T15:42:27Z |
MediaButtonIntentReceiver.java | /FileExtraction/Java_unseen/kartikhimself_Simple-Video-Player/app/src/main/java/com/sdcode/videoplayer/kxUtil/MediaButtonIntentReceiver.java |
package com.sdcode.videoplayer.kxUtil;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.Log;
import android.view.KeyEvent;
import com.sdcode.videoplayer.BuildConfig;
import com.sdcode.videoplayer.videoService.VideoService;
/**
* Used to control headset playback.
* Single press: pause/resume
* Double press: next track
* Triple press: previous track
* Long press: voice search
*/
public class MediaButtonIntentReceiver extends BroadcastReceiver {
private static final boolean DEBUG = BuildConfig.DEBUG;
public static final String TAG = MediaButtonIntentReceiver.class.getSimpleName();
private static final int MSG_HEADSET_DOUBLE_CLICK_TIMEOUT = 2;
private static final int DOUBLE_CLICK = 400;
private static WakeLock mWakeLock = null;
private static int mClickCounter = 0;
private static long mLastClickTime = 0;
@SuppressLint("HandlerLeak") // false alarm, handler is already static
private static Handler mHandler = new Handler() {
@Override
public void handleMessage(final Message msg) {
switch (msg.what) {
case MSG_HEADSET_DOUBLE_CLICK_TIMEOUT:
final int clickCount = msg.arg1;
final String command;
if (DEBUG) Log.v(TAG, "Handling headset click, count = " + clickCount);
switch (clickCount) {
case 1:
command = VideoService.TOGGLEPAUSE_ACTION;
break;
case 2:
command = VideoService.NEXT_ACTION;
break;
case 3:
command = VideoService.PREVIOUS_ACTION;
break;
default:
command = null;
break;
}
if (command != null) {
final Context context = (Context) msg.obj;
startService(context, command);
}
break;
}
releaseWakeLockIfHandlerIdle();
}
};
@Override
public void onReceive(final Context context, final Intent intent) {
if (DEBUG) Log.v(TAG, "Received intent: " + intent);
if (handleIntent(context, intent) && isOrderedBroadcast()) {
abortBroadcast();
}
}
public static boolean handleIntent(final Context context, final Intent intent) {
final String intentAction = intent.getAction();
if (Intent.ACTION_MEDIA_BUTTON.equals(intentAction)) {
final KeyEvent event = intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if (event == null) {
return false;
}
final int keycode = event.getKeyCode();
final int action = event.getAction();
final long eventTime = event.getEventTime();
String command = null;
switch (keycode) {
case KeyEvent.KEYCODE_MEDIA_STOP:
command = VideoService.STOP_ACTION;
break;
case KeyEvent.KEYCODE_HEADSETHOOK:
case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
command = VideoService.TOGGLEPAUSE_ACTION;
break;
case KeyEvent.KEYCODE_MEDIA_NEXT:
command = VideoService.NEXT_ACTION;
break;
case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
command = VideoService.PREVIOUS_ACTION;
break;
case KeyEvent.KEYCODE_MEDIA_PAUSE:
command = VideoService.TOGGLEPAUSE_ACTION;
break;
case KeyEvent.KEYCODE_MEDIA_PLAY:
command = VideoService.TOGGLEPAUSE_ACTION;
break;
}
if (command != null) {
if (action == KeyEvent.ACTION_DOWN) {
if (event.getRepeatCount() == 0) {
// Only consider the first event in a sequence, not the repeat events,
// so that we don't trigger in cases where the first event went to
// a different app (e.g. when the user ends a phone call by
// long pressing the headset button)
// The service may or may not be running, but we need to send it
// a command.
if (keycode == KeyEvent.KEYCODE_HEADSETHOOK || keycode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE) {
if (eventTime - mLastClickTime >= DOUBLE_CLICK) {
mClickCounter = 0;
}
mClickCounter++;
if (DEBUG) Log.v(TAG, "Got headset click, count = " + mClickCounter);
mHandler.removeMessages(MSG_HEADSET_DOUBLE_CLICK_TIMEOUT);
Message msg = mHandler.obtainMessage(
MSG_HEADSET_DOUBLE_CLICK_TIMEOUT, mClickCounter, 0, context);
long delay = mClickCounter < 3 ? DOUBLE_CLICK : 0;
if (mClickCounter >= 3) {
mClickCounter = 0;
}
mLastClickTime = eventTime;
acquireWakeLockAndSendMessage(context, msg, delay);
} else {
startService(context, command);
}
return true;
}
}
}
}
return false;
}
private static void startService(Context context, String command) {
final Intent intent = new Intent(context, VideoService.class);
intent.setAction(VideoService.SERVICECMD);
intent.putExtra(VideoService.CMDNAME, command);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(intent);
} else {
context.startService(intent);
}
}
@SuppressLint("InvalidWakeLockTag")
private static void acquireWakeLockAndSendMessage(Context context, Message msg, long delay) {
if (mWakeLock == null) {
Context appContext = context.getApplicationContext();
PowerManager pm = (PowerManager) appContext.getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Music Player headset button");
mWakeLock.setReferenceCounted(false);
}
if (DEBUG) Log.v(TAG, "Acquiring wake lock and sending " + msg.what);
// Make sure we don't indefinitely hold the wake lock under any circumstances
mWakeLock.acquire(10000);
mHandler.sendMessageDelayed(msg, delay);
}
private static void releaseWakeLockIfHandlerIdle() {
if (mHandler.hasMessages(MSG_HEADSET_DOUBLE_CLICK_TIMEOUT)) {
if (DEBUG) Log.v(TAG, "Handler still has messages pending, not releasing wake lock");
return;
}
if (mWakeLock != null) {
if (DEBUG) Log.v(TAG, "Releasing wake lock");
mWakeLock.release();
mWakeLock = null;
}
}
}
| 7,728 | Java | .java | kartikhimself/Simple-Video-Player | 11 | 4 | 0 | 2019-07-03T02:35:28Z | 2019-07-02T15:42:27Z |
PreferencesUtility.java | /FileExtraction/Java_unseen/kartikhimself_Simple-Video-Player/app/src/main/java/com/sdcode/videoplayer/kxUtil/PreferencesUtility.java | package com.sdcode.videoplayer.kxUtil;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
public class PreferencesUtility {
private static final String TOGGLE_ALBUM_GRID = "TOGGLE_ALBUM_GRID" ;
private static final String BACKGROUND_AUDIO = "BACKGROUND_AUDIO" ;
private static final String SCEENORIENTATITION = "screen_orientation";
private static final String REPEATMODE = "repeat_mode";
private static final String KEY_THEME_SETTING = "key_theme_setting";
private static PreferencesUtility sInstance;
private static final String KEY_LAUGH_COUNT = "key_laugh_count";
private static SharedPreferences mPreferences;
public PreferencesUtility(final Context context) {
mPreferences = PreferenceManager.getDefaultSharedPreferences(context);
}
public static final PreferencesUtility getInstance(final Context context) {
if (sInstance == null) {
sInstance = new PreferencesUtility(context.getApplicationContext());
}
return sInstance;
}
public boolean isAlbumsInGrid() {
return mPreferences.getBoolean(TOGGLE_ALBUM_GRID, true);
}
public void setAlbumsInGrid(final boolean b) {
final SharedPreferences.Editor editor = mPreferences.edit();
editor.putBoolean(TOGGLE_ALBUM_GRID, b);
editor.apply();
}
public boolean isAllowBackgroundAudio() {
return mPreferences.getBoolean(BACKGROUND_AUDIO, true);
}
public void setAllowBackgroundAudio(final boolean b) {
final SharedPreferences.Editor editor = mPreferences.edit();
editor.putBoolean(BACKGROUND_AUDIO, b);
editor.apply();
}
public int getScreenOrientation() {
return mPreferences.getInt(SCEENORIENTATITION, 10);
}
public void setScreenOrientation(final int value) {
final SharedPreferences.Editor editor = mPreferences.edit();
editor.putInt(SCEENORIENTATITION, value);
editor.apply();
}
public int getRepeatMode() {
return mPreferences.getInt(REPEATMODE, 10);
}
public void setRepeatmode(final int value) {
final SharedPreferences.Editor editor = mPreferences.edit();
editor.putInt(REPEATMODE, value);
editor.apply();
}
public int getThemeSettings() {
return mPreferences.getInt(KEY_THEME_SETTING ,0);
}
public void setThemSettings(final int i) {
final SharedPreferences.Editor editor = mPreferences.edit();
editor.putInt(KEY_THEME_SETTING, i);
editor.apply();
}
public int getlaughCount() {
return mPreferences.getInt(KEY_LAUGH_COUNT ,0);
}
public void setLaughCount(final int i) {
final SharedPreferences.Editor editor = mPreferences.edit();
editor.putInt(KEY_LAUGH_COUNT, i);
editor.apply();
}
}
| 2,904 | Java | .java | kartikhimself/Simple-Video-Player | 11 | 4 | 0 | 2019-07-03T02:35:28Z | 2019-07-02T15:42:27Z |
kxUtils.java | /FileExtraction/Java_unseen/kartikhimself_Simple-Video-Player/app/src/main/java/com/sdcode/videoplayer/kxUtil/kxUtils.java | /*
* The MIT License (MIT)
* Copyright (c) 2015 Michal Tajchert
* permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.sdcode.videoplayer.kxUtil;
import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.widget.Toast;
import com.sdcode.videoplayer.permission.PermissionCallback;
import com.sdcode.videoplayer.permission.PermissionListener;
import com.sdcode.videoplayer.permission.PermissionRequest;
import com.sdcode.videoplayer.R;
import com.sdcode.videoplayer.video.VideoItem;
import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class kxUtils {
private static final String TAG = kxUtils.class.getSimpleName();
private static final String KEY_PREV_PERMISSIONS = "previous_permissions";
private static final String KEY_IGNORED_PERMISSIONS = "ignored_permissions";
private static Context context;
private static SharedPreferences sharedPreferences;
private static ArrayList<PermissionRequest> permissionRequests = new ArrayList<>();
public static void init(Context context) {
sharedPreferences = context.getSharedPreferences("pl.tajchert.runtimepermissionhelper", Context.MODE_PRIVATE);
kxUtils.context = context;
}
/**
* Check that all given permissions have been granted by verifying that each entry in the
* given array is of the value {@link PackageManager#PERMISSION_GRANTED}.
*/
public static boolean verifyPermissions(int[] grantResults) {
for (int result : grantResults) {
if (result != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
return true;
}
/**
* Returns true if the Activity has access to given permissions.
*/
@TargetApi(Build.VERSION_CODES.M)
public static boolean hasPermission(Activity activity, String permission) {
return activity.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED;
}
/**
* Returns true if the Activity has access to a all given permission.
*/
@TargetApi(Build.VERSION_CODES.M)
public static boolean hasPermission(Activity activity, String[] permissions) {
for (String permission : permissions) {
if (activity.checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
return true;
}
/*
* If we override other methods, lets do it as well, and keep name same as it is already weird enough.
* Returns true if we should show explanation why we need this permission.
*/
@TargetApi(Build.VERSION_CODES.M)
public static boolean shouldShowRequestPermissionRationale(Activity activity, String permissions) {
return activity.shouldShowRequestPermissionRationale(permissions);
}
public static void askForPermission(Activity activity, String permission, PermissionCallback permissionCallback) {
askForPermission(activity, new String[]{permission}, permissionCallback);
}
@TargetApi(Build.VERSION_CODES.M)
public static void askForPermission(Activity activity, String[] permissions, PermissionCallback permissionCallback) {
if (permissionCallback == null) {
return;
}
if (hasPermission(activity, permissions)) {
permissionCallback.permissionGranted();
return;
}
PermissionRequest permissionRequest = new PermissionRequest(new ArrayList<>(Arrays.asList(permissions)), permissionCallback);
permissionRequests.add(permissionRequest);
activity.requestPermissions(permissions, permissionRequest.getRequestCode());
}
public static void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
PermissionRequest requestResult = new PermissionRequest(requestCode);
if (permissionRequests.contains(requestResult)) {
PermissionRequest permissionRequest = permissionRequests.get(permissionRequests.indexOf(requestResult));
if (verifyPermissions(grantResults)) {
//permission has been granted
permissionRequest.getPermissionCallback().permissionGranted();
} else {
permissionRequest.getPermissionCallback().permissionRefused();
}
permissionRequests.remove(requestResult);
}
refreshMonitoredList();
}
//permission monitoring part below
/**
* Get list of currently granted permissions, without saving it inside kxUtils
*
* @return currently granted permissions
*/
@TargetApi(Build.VERSION_CODES.M)
public static ArrayList<String> getGrantedPermissions() {
if (context == null) {
throw new RuntimeException("Must call init() earlier");
}
ArrayList<String> permissions = new ArrayList<>();
ArrayList<String> permissionsGranted = new ArrayList<>();
//Group location
permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
//Group Calendar
permissions.add(Manifest.permission.WRITE_CALENDAR);
permissions.add(Manifest.permission.READ_CALENDAR);
//Group Camera
permissions.add(Manifest.permission.CAMERA);
//Group Contacts
permissions.add(Manifest.permission.WRITE_CONTACTS);
permissions.add(Manifest.permission.READ_CONTACTS);
permissions.add(Manifest.permission.GET_ACCOUNTS);
//Group Microphone
permissions.add(Manifest.permission.RECORD_AUDIO);
//Group Phone
permissions.add(Manifest.permission.CALL_PHONE);
permissions.add(Manifest.permission.READ_PHONE_STATE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
permissions.add(Manifest.permission.READ_CALL_LOG);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
permissions.add(Manifest.permission.WRITE_CALL_LOG);
}
permissions.add(Manifest.permission.ADD_VOICEMAIL);
permissions.add(Manifest.permission.USE_SIP);
permissions.add(Manifest.permission.PROCESS_OUTGOING_CALLS);
//Group Body sensors
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
permissions.add(Manifest.permission.BODY_SENSORS);
}
//Group SMS
permissions.add(Manifest.permission.SEND_SMS);
permissions.add(Manifest.permission.READ_SMS);
permissions.add(Manifest.permission.RECEIVE_SMS);
permissions.add(Manifest.permission.RECEIVE_WAP_PUSH);
permissions.add(Manifest.permission.RECEIVE_MMS);
//Group Storage
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
permissions.add(Manifest.permission.READ_EXTERNAL_STORAGE);
}
permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
for (String permission : permissions) {
if (context.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED) {
permissionsGranted.add(permission);
}
}
return permissionsGranted;
}
/**
* Refresh currently granted permission list, and save it for later comparing using @permissionCompare()
*/
public static void refreshMonitoredList() {
ArrayList<String> permissions = getGrantedPermissions();
Set<String> set = new HashSet<>();
for (String perm : permissions) {
set.add(perm);
}
sharedPreferences.edit().putStringSet(KEY_PREV_PERMISSIONS, set).apply();
}
/**
* Get list of previous Permissions, from last refreshMonitoredList() call and they may be outdated,
* use getGrantedPermissions() to get current
*/
public static ArrayList<String> getPreviousPermissions() {
ArrayList<String> prevPermissions = new ArrayList<>();
prevPermissions.addAll(sharedPreferences.getStringSet(KEY_PREV_PERMISSIONS, new HashSet<String>()));
return prevPermissions;
}
public static ArrayList<String> getIgnoredPermissions() {
ArrayList<String> ignoredPermissions = new ArrayList<>();
ignoredPermissions.addAll(sharedPreferences.getStringSet(KEY_IGNORED_PERMISSIONS, new HashSet<String>()));
return ignoredPermissions;
}
/**
* Lets see if we already ignore this permission
*/
public static boolean isIgnoredPermission(String permission) {
if (permission == null) {
return false;
}
return getIgnoredPermissions().contains(permission);
}
/**
* Use to ignore to particular permission - even if user will deny or add it we won't receive a callback.
*
* @param permission permission to ignore
*/
public static void ignorePermission(String permission) {
if (!isIgnoredPermission(permission)) {
ArrayList<String> ignoredPermissions = getIgnoredPermissions();
ignoredPermissions.add(permission);
Set<String> set = new HashSet<>();
set.addAll(ignoredPermissions);
sharedPreferences.edit().putStringSet(KEY_IGNORED_PERMISSIONS, set).apply();
}
}
/**
* Used to trigger comparing process - @permissionListener will be called each time permission was revoked, or added (but only once).
*
* @param permissionListener Callback that handles all permission changes
*/
public static void permissionCompare(PermissionListener permissionListener) {
if (context == null) {
throw new RuntimeException("Before comparing permissions you need to call kxUtils.init(context)");
}
ArrayList<String> previouslyGranted = getPreviousPermissions();
ArrayList<String> currentPermissions = getGrantedPermissions();
ArrayList<String> ignoredPermissions = getIgnoredPermissions();
for (String permission : ignoredPermissions) {
if (previouslyGranted != null && !previouslyGranted.isEmpty()) {
if (previouslyGranted.contains(permission)) {
previouslyGranted.remove(permission);
}
}
if (currentPermissions != null && !currentPermissions.isEmpty()) {
if (currentPermissions.contains(permission)) {
currentPermissions.remove(permission);
}
}
}
for (String permission : currentPermissions) {
if (previouslyGranted.contains(permission)) {
//All is fine, was granted and still is
previouslyGranted.remove(permission);
} else {
//We didn't have it last time
if (permissionListener != null) {
permissionListener.permissionsChanged(permission);
permissionListener.permissionsGranted(permission);
}
}
}
if (previouslyGranted != null && !previouslyGranted.isEmpty()) {
//Something was granted and removed
for (String permission : previouslyGranted) {
if (permissionListener != null) {
permissionListener.permissionsChanged(permission);
permissionListener.permissionsRemoved(permission);
}
}
}
refreshMonitoredList();
}
/**
* Not that needed method but if we override others it is good to keep same.
*/
@TargetApi(Build.VERSION_CODES.M)
public static boolean checkPermission(String permissionName) {
if (context == null) {
throw new RuntimeException("Before comparing permissions you need to call kxUtils.init(context)");
}
return PackageManager.PERMISSION_GRANTED == context.checkSelfPermission(permissionName);
}
public static String makeShortTimeString(final Context context, long secs) {
long hours, mins;
hours = secs / 3600;
secs %= 3600;
mins = secs / 60;
secs %= 60;
final String durationFormat = context.getResources().getString(
hours == 0 ? R.string.durationformatshort : R.string.durationformatlong);
return String.format(durationFormat, hours, mins, secs);
}
public static String getStringSizeLengthFile(long size) {
DecimalFormat df = new DecimalFormat("0.00");
float sizeKb = 1024.0f;
float sizeMb = sizeKb * sizeKb;
float sizeGb = sizeMb * sizeKb;
float sizeTerra = sizeGb * sizeKb;
if(size < sizeMb)
return df.format(size / sizeKb)+ " Kb";
else if(size < sizeGb)
return df.format(size / sizeMb) + " Mb";
else if(size < sizeTerra)
return df.format(size / sizeGb) + " Gb";
return "";
}
public static boolean isMarshmallow() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M;
}
public static String getFileExtension(String fileName) {
String fileNameArray[] = fileName.split("\\.");
return fileNameArray[fileNameArray.length-1];
}
public static String getFileNameFromPath(String path){
if(path == null) return "Unknown File";
int i = path.lastIndexOf("/");
if(i == 0) return path;
return path.substring(i);
}
public static Intent shareVideo(final Context context, VideoItem videoItem) {
if (videoItem == null) return new Intent();
String filePath = videoItem.getPath();
if (filePath == null) return new Intent();
File shareFile = new File(filePath);
if (!shareFile.exists()) return new Intent();
String fileType = getFileExtension(filePath);
if (shareFile.exists()) {
try {
if(fileType.equals("Mp4") || filePath.equals("mp4") || filePath.equals("MP4"))
return new Intent()
.setAction(Intent.ACTION_SEND)
.putExtra(Intent.EXTRA_STREAM, VideoPlayerProvider.getUri(context, shareFile))
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
.setType("video/mp4");
else {
return new Intent()
.setAction(Intent.ACTION_SEND)
.putExtra(Intent.EXTRA_STREAM, VideoPlayerProvider.getUri(context, shareFile))
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
.setType("file/*");
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();
return new Intent();
}
}
//Toast.makeText(context, "File cannot share, (:", Toast.LENGTH_SHORT).show();
return new Intent();
}
public static void shareMultiVideo(final Context context, List<VideoItem> videoItems) {
ArrayList<Uri> files = new ArrayList<>();
File f;
for (VideoItem videoItem:videoItems){
f = new File(videoItem.getPath());
if(f.exists()) {
Uri uri;
try {
uri = VideoPlayerProvider.getUri(context, f);
}catch (IllegalArgumentException e){
uri = null;
e.printStackTrace();
}
if(uri != null) files.add(uri);
}
}
if(files.size() > 0) {
try {
Intent share = new Intent(Intent.ACTION_SEND_MULTIPLE);
share.putExtra(Intent.EXTRA_SUBJECT, "Share all video files.");
share.putParcelableArrayListExtra(Intent.EXTRA_STREAM, files);
share.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
share.setType("file/*");
context.startActivity(Intent.createChooser(share, "Share To"));
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
}
public static final String about = "";
} | 17,647 | Java | .java | kartikhimself/Simple-Video-Player | 11 | 4 | 0 | 2019-07-03T02:35:28Z | 2019-07-02T15:42:27Z |
VideoPlayerProvider.java | /FileExtraction/Java_unseen/kartikhimself_Simple-Video-Player/app/src/main/java/com/sdcode/videoplayer/kxUtil/VideoPlayerProvider.java | package com.sdcode.videoplayer.kxUtil;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import com.commonsware.cwac.provider.LegacyCompatCursorWrapper;
import java.io.File;
import java.util.Objects;
import androidx.annotation.NonNull;
import androidx.core.content.FileProvider;
public class VideoPlayerProvider extends FileProvider {
@Override
public Cursor query(@NonNull Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
return(new LegacyCompatCursorWrapper(Objects.requireNonNull(super.query(uri, projection, selection, selectionArgs, sortOrder))));
}
public static Uri getUri(Context context, File file) {
return getUriForFile(context, "com.sdcode.videoplayer.provider", file);
}
}
| 811 | Java | .java | kartikhimself/Simple-Video-Player | 11 | 4 | 0 | 2019-07-03T02:35:28Z | 2019-07-02T15:42:27Z |
MyFragment.java | /FileExtraction/Java_unseen/kartikhimself_Simple-Video-Player/app/src/main/java/com/sdcode/videoplayer/fragment/MyFragment.java | package com.sdcode.videoplayer.fragment;
import com.sdcode.videoplayer.video.VideoItem;
import java.util.ArrayList;
public abstract class MyFragment extends BaseFragment {
public void reloadFragment(int orientation){}
public int getTotalSelected(){
return 0;
}
public void releaseUI(){ }
public void playItemSelected(){}
public void shareSelected(){}
public void deleteSelected(){}
public void updateVideoList(ArrayList<VideoItem> videoItems){}
public void sortAZ(){ }
public void sortZA(){}
public void sortSize(){}
}
| 575 | Java | .java | kartikhimself/Simple-Video-Player | 11 | 4 | 0 | 2019-07-03T02:35:28Z | 2019-07-02T15:42:27Z |
BaseFragment.java | /FileExtraction/Java_unseen/kartikhimself_Simple-Video-Player/app/src/main/java/com/sdcode/videoplayer/fragment/BaseFragment.java | package com.sdcode.videoplayer.fragment;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
public class BaseFragment extends Fragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
} | 275 | Java | .java | kartikhimself/Simple-Video-Player | 11 | 4 | 0 | 2019-07-03T02:35:28Z | 2019-07-02T15:42:27Z |
FragmentVideoList.java | /FileExtraction/Java_unseen/kartikhimself_Simple-Video-Player/app/src/main/java/com/sdcode/videoplayer/fragment/FragmentVideoList.java | package com.sdcode.videoplayer.fragment;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.sdcode.videoplayer.GlobalVar;
import com.sdcode.videoplayer.BaseActivity;
import com.sdcode.videoplayer.customizeUI.WrapContentGridLayoutManager;
import com.sdcode.videoplayer.customizeUI.WrapContentLinearLayoutManager;
import com.sdcode.videoplayer.FirstActivity;
import com.sdcode.videoplayer.FolderDetailActivity;
import com.sdcode.videoplayer.kxUtil.PreferencesUtility;
import com.sdcode.videoplayer.PlayVideoActivity;
import com.sdcode.videoplayer.R;
import com.sdcode.videoplayer.SearchActivity;
import com.sdcode.videoplayer.adapter.VideoAdapter;
import com.sdcode.videoplayer.kxUtil.kxUtils;
import com.sdcode.videoplayer.video.VideoItem;
import com.sdcode.videoplayer.video.VideoLoadListener;
import com.sdcode.videoplayer.video.VideoLoader;
import java.util.ArrayList;
import java.util.Collections;
public class FragmentVideoList extends MyFragment{
RecyclerView recyclerView;
VideoAdapter videoAdapter;
VideoLoader videoLoader;
ArrayList<VideoItem> videoItems = new ArrayList<>();
public FragmentVideoList() {
// Required empty public constructor
}
public static FragmentVideoList newInstance(String param1, String param2) {
FragmentVideoList fragment = new FragmentVideoList();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_video_list, container, false);
recyclerView = rootView.findViewById(R.id.recyclerView);
setLayoutManager(getCurrentOrientation());
videoAdapter = new VideoAdapter(getActivity());
recyclerView.setAdapter(videoAdapter);
loadEveryThing();
return rootView;
}
@Override
public void reloadFragment(int orientation){
doLayoutChange(orientation);
}
@Override
public int getTotalSelected(){
if(videoAdapter == null)
return 0;
return videoAdapter.getTotalVideoSelected();
}
@Override
public void playItemSelected(){
ArrayList<VideoItem> videoItems = videoAdapter.getVideoItemsSelected();
if(videoItems.size() > 0 && getActivity() != null){
GlobalVar.getInstance().videoItemsPlaylist = videoItems;
GlobalVar.getInstance().playingVideo = videoItems.get(0);
if(!GlobalVar.getInstance().isPlayingAsPopup()){
GlobalVar.getInstance().videoService.playVideo(GlobalVar.getInstance().seekPosition,false);
Intent intent = new Intent(getActivity(), PlayVideoActivity.class);
getActivity().startActivity(intent);
if(GlobalVar.getInstance().videoService != null)
GlobalVar.getInstance().videoService.releasePlayerView();
}else {
((BaseActivity) getActivity()).showFloatingView(getActivity(),true);
}
}
}
@Override
public void sortAZ(){
if(videoItems != null && videoItems.size() > 0){
videoItems = sortVideoAZ(videoItems);
videoAdapter.updateData(videoItems);
}
}
@Override
public void sortZA(){
if(videoItems != null && videoItems.size() > 0){
videoItems = sortVideoZA(videoItems);
videoAdapter.updateData(videoItems);
}
}
@Override
public void sortSize(){
if(videoItems != null && videoItems.size() > 0){
videoItems = sortSongSize();
videoAdapter.updateData(videoItems);
}
}
@Override
public void shareSelected(){
if(videoAdapter == null || getActivity() == null) return;
ArrayList<VideoItem> videoItems = videoAdapter.getVideoItemsSelected();
kxUtils.shareMultiVideo(getActivity(),videoItems);
}
@Override
public void deleteSelected(){
videoAdapter.deleteListVideoSelected();
}
@Override
public void updateVideoList(ArrayList<VideoItem> videoItems){
if(videoItems == null) return;
this.videoItems = videoItems;
GlobalVar.getInstance().folderItem.setVideoItems(videoItems);
GlobalVar.getInstance().isNeedRefreshFolder = true;
}
@Override
public void releaseUI(){
for(VideoItem videoItem:videoItems){
videoItem.setSelected(false);
}
videoAdapter.updateData(videoItems);
}
private void doLayoutChange(int orientation){
if(getActivity() instanceof FirstActivity || getActivity() instanceof FolderDetailActivity) {
if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
if (PreferencesUtility.getInstance(getActivity()).isAlbumsInGrid()) {
recyclerView.setLayoutManager(new WrapContentGridLayoutManager(getActivity(), 4));
} else {
recyclerView.setLayoutManager(new WrapContentLinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
}
} else if (orientation == Configuration.ORIENTATION_PORTRAIT) {
if (PreferencesUtility.getInstance(getActivity()).isAlbumsInGrid()) {
recyclerView.setLayoutManager(new WrapContentGridLayoutManager(getActivity(), 2));
} else {
recyclerView.setLayoutManager(new WrapContentLinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
}
}
videoAdapter.updateData(videoItems);
}
}
private int getCurrentOrientation(){
return getResources().getConfiguration().orientation;
}
private void setLayoutManager(int orientation) {
if(getActivity() instanceof FirstActivity || getActivity() instanceof FolderDetailActivity) {
if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
if (PreferencesUtility.getInstance(getActivity()).isAlbumsInGrid()) {
recyclerView.setLayoutManager(new WrapContentGridLayoutManager(getActivity(), 4));
} else {
recyclerView.setLayoutManager(new WrapContentLinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
}
} else if (orientation == Configuration.ORIENTATION_PORTRAIT) {
if (PreferencesUtility.getInstance(getActivity()).isAlbumsInGrid()) {
recyclerView.setLayoutManager(new WrapContentGridLayoutManager(getActivity(), 2));
} else {
recyclerView.setLayoutManager(new WrapContentLinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
}
}
}
}
private void loadEveryThing(){
if(getActivity() instanceof FirstActivity) {
videoLoader = new VideoLoader(getActivity());
videoLoader.loadDeviceVideos(new VideoLoadListener() {
@Override
public void onVideoLoaded(final ArrayList<VideoItem> items) {
videoItems = items;
GlobalVar.getInstance().allVideoItems = videoItems;
videoAdapter.updateData(items);
}
@Override
public void onFailed(Exception e) {
e.printStackTrace();
}
});
}else if(getActivity() instanceof FolderDetailActivity){
videoItems = GlobalVar.getInstance().folderItem.getVideoItems();
videoAdapter.updateData(videoItems);
}else if(getActivity() instanceof SearchActivity){
}
}
private ArrayList<VideoItem> sortVideoAZ(ArrayList<VideoItem> videoItems){
ArrayList<VideoItem> m_videos = new ArrayList<>();
ArrayList<String> names = new ArrayList<>();
for (int i = 0; i < videoItems.size();i++){
names.add(videoItems.get(i).getFolderName() + "_" + videoItems.get(i).getPath());
}
Collections.sort(names, String::compareToIgnoreCase);
for(int i = 0; i < names.size(); i ++){
String path = names.get(i);
for (int j = 0; j < videoItems.size();j++){
if(path.equals(videoItems.get(j).getFolderName() + "_" + videoItems.get(j).getPath())){
m_videos.add(videoItems.get(j));
}
}
}
return m_videos;
}
private ArrayList<VideoItem> sortVideoZA(ArrayList<VideoItem> videoItems){
ArrayList<VideoItem> m_videos = sortVideoAZ(videoItems);
Collections.reverse(m_videos);
return m_videos;
}
private ArrayList<VideoItem> sortSongSize() throws NumberFormatException{
ArrayList<VideoItem> m_videos = videoItems;
for (int i = 0; i < m_videos.size() -1;i++) {
for(int j = 0; j < m_videos.size() - 1 - i; j++){
if(m_videos.get(j).getFileSizeAsFloat() < m_videos.get(j+1).getFileSizeAsFloat()){
Collections.swap(m_videos,j,j+1);
}
}
}
return m_videos;
}
}
| 9,694 | Java | .java | kartikhimself/Simple-Video-Player | 11 | 4 | 0 | 2019-07-03T02:35:28Z | 2019-07-02T15:42:27Z |
FragmentFolderList.java | /FileExtraction/Java_unseen/kartikhimself_Simple-Video-Player/app/src/main/java/com/sdcode/videoplayer/fragment/FragmentFolderList.java | package com.sdcode.videoplayer.fragment;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.sdcode.videoplayer.GlobalVar;
import com.sdcode.videoplayer.customizeUI.WrapContentLinearLayoutManager;
import com.sdcode.videoplayer.adapter.FolderAdapter;
import com.sdcode.videoplayer.folder.FolderItem;
import com.sdcode.videoplayer.folder.FolderLoader;
import com.sdcode.videoplayer.R;
import com.sdcode.videoplayer.video.VideoItem;
import com.sdcode.videoplayer.video.VideoLoadListener;
import com.sdcode.videoplayer.video.VideoLoader;
import java.util.ArrayList;
import java.util.Collections;
public class FragmentFolderList extends MyFragment {
RecyclerView recyclerView;
FolderAdapter folderAdapter;
ArrayList<FolderItem> folderItems;
public FragmentFolderList() {
}
public static FragmentFolderList newInstance() {
FragmentFolderList fragment = new FragmentFolderList();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_folder_list, container, false);
recyclerView = rootView.findViewById(R.id.recyclerView);
setLayoutManager();
folderAdapter = new FolderAdapter(getActivity());
recyclerView.setAdapter(folderAdapter);
loadEveryThing();
return rootView;
}
private void setLayoutManager() {
recyclerView.setLayoutManager(new WrapContentLinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
}
private void loadEveryThing(){
VideoLoader videoLoader = new VideoLoader(getActivity());
videoLoader.loadDeviceVideos(new VideoLoadListener() {
@Override
public void onVideoLoaded(final ArrayList<VideoItem> items) {
GlobalVar.getInstance().allVideoItems = items;
folderItems = FolderLoader.getFolderList(items);
folderAdapter.updateData(folderItems);
}
@Override
public void onFailed(Exception e) {
e.printStackTrace();
}
});
}
@Override
public void sortAZ(){
if(folderItems != null && folderItems.size() > 0){
folderItems = sortFolderAZ(folderItems);
folderAdapter.updateData(folderItems);
}
}
@Override
public void sortZA(){
if(folderItems != null && folderItems.size() > 0){
folderItems = sortFolderZA(folderItems);
folderAdapter.updateData(folderItems);
}
}
@Override
public void sortSize(){
if(folderItems != null && folderItems.size() > 0){
folderItems = sortFolderNumberSong();
folderAdapter.updateData(folderItems);
}
}
private ArrayList<FolderItem> sortFolderAZ(ArrayList<FolderItem> folders){
ArrayList<FolderItem> m_folders = new ArrayList<>();
ArrayList<String> names = new ArrayList<>();
for (int i = 0; i < folders.size();i++){
names.add(folders.get(i).getFolderName() + "_" + folders.get(i).getFolderPath());
}
Collections.sort(names, String::compareToIgnoreCase);
for(int i = 0; i < names.size(); i ++){
String path = names.get(i);
for (int j = 0; j < folders.size();j++){
if(path.equals(folders.get(j).getFolderName() + "_" + folders.get(j).getFolderPath())){
m_folders.add(folders.get(j));
}
}
}
return m_folders;
}
private ArrayList<FolderItem> sortFolderZA(ArrayList<FolderItem> folders){
ArrayList<FolderItem> m_folders = sortFolderAZ(folders);
Collections.reverse(m_folders);
return m_folders;
}
private ArrayList<FolderItem> sortFolderNumberSong(){
ArrayList<FolderItem> m_folders = folderItems;
for (int i = 0; i < m_folders.size() -1;i++) {
for(int j = 0; j < m_folders.size() - 1 - i; j++){
if(m_folders.get(j).getVideoItems().size() < m_folders.get(j+1).getVideoItems().size()){
Collections.swap(m_folders,j,j+1);
}
}
}
return m_folders;
}
} | 4,762 | Java | .java | kartikhimself/Simple-Video-Player | 11 | 4 | 0 | 2019-07-03T02:35:28Z | 2019-07-02T15:42:27Z |
WrapContentGridLayoutManager.java | /FileExtraction/Java_unseen/kartikhimself_Simple-Video-Player/app/src/main/java/com/sdcode/videoplayer/customizeUI/WrapContentGridLayoutManager.java | package com.sdcode.videoplayer.customizeUI;
import android.content.Context;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
/**
* Created by Xi developer on 6/23/2017.
*/
public class WrapContentGridLayoutManager extends GridLayoutManager {
public WrapContentGridLayoutManager(Context context, int spanCount) {
super(context, spanCount);
}
@Override
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
try {
super.onLayoutChildren(recycler, state);
} catch (IndexOutOfBoundsException e) {
}
}
@Override
public boolean supportsPredictiveItemAnimations() {
return false;
}
}
| 788 | Java | .java | kartikhimself/Simple-Video-Player | 11 | 4 | 0 | 2019-07-03T02:35:28Z | 2019-07-02T15:42:27Z |
NonScrollImageView.java | /FileExtraction/Java_unseen/kartikhimself_Simple-Video-Player/app/src/main/java/com/sdcode/videoplayer/customizeUI/NonScrollImageView.java | package com.sdcode.videoplayer.customizeUI;
import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import net.steamcrafted.materialiconlib.MaterialIconView;
public class NonScrollImageView extends MaterialIconView {
public NonScrollImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
return false;
}
}
| 495 | Java | .java | kartikhimself/Simple-Video-Player | 11 | 4 | 0 | 2019-07-03T02:35:28Z | 2019-07-02T15:42:27Z |
PlayPauseDrawable.java | /FileExtraction/Java_unseen/kartikhimself_Simple-Video-Player/app/src/main/java/com/sdcode/videoplayer/customizeUI/PlayPauseDrawable.java | package com.sdcode.videoplayer.customizeUI;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import android.util.Log;
import android.util.Property;
import android.view.animation.DecelerateInterpolator;
public class PlayPauseDrawable extends Drawable {
private static final String TAG = PlayPauseDrawable.class.getSimpleName();
private final Path leftPauseBar = new Path();
private final Path rightPauseBar = new Path();
private final Paint paint = new Paint();
private float progress;
private static final Property<PlayPauseDrawable, Float> PROGRESS =
new Property<PlayPauseDrawable, Float>(Float.class, "progress") {
@Override
public Float get(PlayPauseDrawable d) {
return d.getProgress();
}
@Override
public void set(PlayPauseDrawable d, Float value) {
d.setProgress(value);
}
};
private boolean isPlay;
@Nullable
private Animator animator;
public PlayPauseDrawable() {
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.WHITE);
}
/**
* Linear interpolate between a and b with parameter t.
*/
private static float interpolate(float a, float b, float t) {
return a + (b - a) * t;
}
@Override
public void draw(@NonNull Canvas canvas) {
long startDraw = System.currentTimeMillis();
leftPauseBar.rewind();
rightPauseBar.rewind();
// move to center of canvas
canvas.translate(getBounds().left, getBounds().top);
float pauseBarHeight = 7.0F / 12.0F * ((float) getBounds().height());
float pauseBarWidth = pauseBarHeight / 3.0F;
float pauseBarDistance = pauseBarHeight / 3.6F;
// The current distance between the two pause bars.
final float barDist = interpolate(pauseBarDistance, 0.0F, progress);
// The current width of each pause bar.
final float barWidth = interpolate(pauseBarWidth, pauseBarHeight / 1.75F, progress);
// The current position of the left pause bar's top left coordinate.
final float firstBarTopLeft = interpolate(0.0F, barWidth, progress);
// The current position of the right pause bar's top right coordinate.
final float secondBarTopRight = interpolate(2.0F * barWidth + barDist, barWidth + barDist, progress);
// Draw the left pause bar. The left pause bar transforms into the
// top half of the play button triangle by animating the position of the
// rectangle's top left coordinate and expanding its bottom width.
leftPauseBar.moveTo(0.0F, 0.0F);
leftPauseBar.lineTo(firstBarTopLeft, -pauseBarHeight);
leftPauseBar.lineTo(barWidth, -pauseBarHeight);
leftPauseBar.lineTo(barWidth, 0.0F);
leftPauseBar.close();
// Draw the right pause bar. The right pause bar transforms into the
// bottom half of the play button triangle by animating the position of the
// rectangle's top right coordinate and expanding its bottom width.
rightPauseBar.moveTo(barWidth + barDist, 0.0F);
rightPauseBar.lineTo(barWidth + barDist, -pauseBarHeight);
rightPauseBar.lineTo(secondBarTopRight, -pauseBarHeight);
rightPauseBar.lineTo(2.0F * barWidth + barDist, 0.0F);
rightPauseBar.close();
canvas.save();
// Translate the play button a tiny bit to the right so it looks more centered.
canvas.translate(interpolate(0.0F, pauseBarHeight / 8.0F, progress), 0.0F);
// (1) Pause --> Play: rotate 0 to 90 degrees clockwise.
// (2) Play --> Pause: rotate 90 to 180 degrees clockwise.
final float rotationProgress = isPlay ? 1.0F - progress : progress;
final float startingRotation = isPlay ? 90.0F : 0.0F;
canvas.rotate(interpolate(startingRotation, startingRotation + 90.0F, rotationProgress), getBounds().width() / 2.0F, getBounds().height() / 2.0F);
// Position the pause/play button in the center of the drawable's bounds.
canvas.translate(getBounds().width() / 2.0F - ((2.0F * barWidth + barDist) / 2.0F), getBounds().height() / 2.0F + (pauseBarHeight / 2.0F));
// Draw the two bars that form the animated pause/play button.
canvas.drawPath(leftPauseBar, paint);
canvas.drawPath(rightPauseBar, paint);
canvas.restore();
long timeElapsed = System.currentTimeMillis() - startDraw;
if (timeElapsed > 16) {
Log.e(TAG, "Drawing took too long=" + timeElapsed);
}
}
public void transformToPause(boolean animated) {
if (isPlay) {
if (animated) {
toggle();
} else {
isPlay = false;
setProgress(0.0F);
}
}
}
@Override
public void jumpToCurrentState() {
Log.v(TAG, "jumpToCurrentState()");
if (animator != null) {
animator.cancel();
}
setProgress(isPlay ? 1.0F : 0.0F);
}
public void transformToPlay(boolean animated) {
if (!isPlay) {
if (animated) {
toggle();
} else {
isPlay = true;
setProgress(1.0F);
}
}
}
private void toggle() {
if (animator != null) {
animator.cancel();
}
animator = ObjectAnimator.ofFloat(this, PROGRESS, isPlay ? 1.0F : 0.0F, isPlay ? 0.0F : 1.0F);
animator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
isPlay = !isPlay;
}
});
animator.setInterpolator(new DecelerateInterpolator());
animator.setDuration(200);
animator.start();
}
private float getProgress() {
return progress;
}
private void setProgress(float progress) {
this.progress = progress;
invalidateSelf();
}
@Override
public void setAlpha(int alpha) {
paint.setAlpha(alpha);
invalidateSelf();
}
@Override
public void setColorFilter(ColorFilter cf) {
paint.setColorFilter(cf);
invalidateSelf();
}
@Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
}
| 6,849 | Java | .java | kartikhimself/Simple-Video-Player | 11 | 4 | 0 | 2019-07-03T02:35:28Z | 2019-07-02T15:42:27Z |
ThemeChoiceItem.java | /FileExtraction/Java_unseen/kartikhimself_Simple-Video-Player/app/src/main/java/com/sdcode/videoplayer/customizeUI/ThemeChoiceItem.java | package com.sdcode.videoplayer.customizeUI;
public class ThemeChoiceItem {
int color;
int id;
public ThemeChoiceItem(int color,int id){
this.color = color;
this.id = id;
}
public int getColor(){
return color;
}
public int getId(){
return id;
}
public void setColor(int value){
this.color = value;
}
public void setId(int value){
this.id = value;
}
}
| 448 | Java | .java | kartikhimself/Simple-Video-Player | 11 | 4 | 0 | 2019-07-03T02:35:28Z | 2019-07-02T15:42:27Z |
FastScroller.java | /FileExtraction/Java_unseen/kartikhimself_Simple-Video-Player/app/src/main/java/com/sdcode/videoplayer/customizeUI/FastScroller.java | package com.sdcode.videoplayer.customizeUI;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.content.Context;
import androidx.annotation.IdRes;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.core.view.ViewCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
/**
* Created by Xi developer on 8/23/2017.
*/
public class FastScroller extends LinearLayout {
private static final int BUBBLE_ANIMATION_DURATION = 100;
private static final int TRACK_SNAP_RANGE = 5;
private TextView bubble;
private View handle;
private RecyclerView recyclerView;
private int height;
private boolean isInitialized = false;
private ObjectAnimator currentAnimator = null;
private final RecyclerView.OnScrollListener onScrollListener = new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(final RecyclerView recyclerView, final int dx, final int dy) {
updateBubbleAndHandlePosition();
}
};
public interface BubbleTextGetter {
String getTextToShowInBubble(int pos);
}
public FastScroller(final Context context, final AttributeSet attrs, final int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
public FastScroller(final Context context) {
super(context);
init(context);
}
public FastScroller(final Context context, final AttributeSet attrs) {
super(context, attrs);
init(context);
}
protected void init(Context context) {
if (isInitialized)
return;
isInitialized = true;
setOrientation(HORIZONTAL);
setClipChildren(false);
}
public void setViewsToUse(@LayoutRes int layoutResId, @IdRes int bubbleResId, @IdRes int handleResId) {
final LayoutInflater inflater = LayoutInflater.from(getContext());
inflater.inflate(layoutResId, this, true);
bubble = findViewById(bubbleResId);
if (bubble != null)
bubble.setVisibility(INVISIBLE);
handle = findViewById(handleResId);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
height = h;
updateBubbleAndHandlePosition();
}
@Override
public boolean onTouchEvent(@NonNull MotionEvent event) {
final int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
if (event.getX() < handle.getX() - ViewCompat.getPaddingStart(handle))
return false;
if (currentAnimator != null)
currentAnimator.cancel();
if (bubble != null && bubble.getVisibility() == INVISIBLE)
showBubble();
handle.setSelected(true);
case MotionEvent.ACTION_MOVE:
final float y = event.getY();
setBubbleAndHandlePosition(y);
setRecyclerViewPosition(y);
return true;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
handle.setSelected(false);
hideBubble();
return true;
}
return super.onTouchEvent(event);
}
public void setRecyclerView(final RecyclerView recyclerView) {
if (this.recyclerView != recyclerView) {
if (this.recyclerView != null)
this.recyclerView.removeOnScrollListener(onScrollListener);
this.recyclerView = recyclerView;
if (this.recyclerView == null)
return;
recyclerView.addOnScrollListener(onScrollListener);
}
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
if (recyclerView != null) {
recyclerView.removeOnScrollListener(onScrollListener);
recyclerView = null;
}
}
private void setRecyclerViewPosition(float y) {
if (recyclerView != null) {
final int itemCount = recyclerView.getAdapter().getItemCount();
float proportion;
if (handle.getY() == 0)
proportion = 0f;
else if (handle.getY() + handle.getHeight() >= height - TRACK_SNAP_RANGE)
proportion = 1f;
else
proportion = y / (float) height;
final int targetPos = getValueInRange(0, itemCount - 1, (int) (proportion * (float) itemCount));
((LinearLayoutManager) recyclerView.getLayoutManager()).scrollToPositionWithOffset(targetPos, 0);
final String bubbleText = ((BubbleTextGetter) recyclerView.getAdapter()).getTextToShowInBubble(targetPos);
if (bubble != null)
bubble.setText(bubbleText);
}
}
private int getValueInRange(int min, int max, int value) {
int minimum = Math.max(min, value);
return Math.min(minimum, max);
}
private void updateBubbleAndHandlePosition() {
if (bubble == null || handle.isSelected())
return;
final int verticalScrollOffset = recyclerView.computeVerticalScrollOffset();
final int verticalScrollRange = recyclerView.computeVerticalScrollRange();
float proportion = (float) verticalScrollOffset / ((float) verticalScrollRange - height);
setBubbleAndHandlePosition(height * proportion);
}
private void setBubbleAndHandlePosition(float y) {
final int handleHeight = handle.getHeight();
handle.setY(getValueInRange(0, height - handleHeight, (int) (y - handleHeight / 2)));
if (bubble != null) {
int bubbleHeight = bubble.getHeight();
bubble.setY(getValueInRange(0, height - bubbleHeight - handleHeight / 2, (int) (y - bubbleHeight)));
}
}
private void showBubble() {
if (bubble == null)
return;
bubble.setVisibility(VISIBLE);
if (currentAnimator != null)
currentAnimator.cancel();
currentAnimator = ObjectAnimator.ofFloat(bubble, "alpha", 0f, 1f).setDuration(BUBBLE_ANIMATION_DURATION);
currentAnimator.start();
}
private void hideBubble() {
if (bubble == null)
return;
if (currentAnimator != null)
currentAnimator.cancel();
currentAnimator = ObjectAnimator.ofFloat(bubble, "alpha", 1f, 0f).setDuration(BUBBLE_ANIMATION_DURATION);
currentAnimator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
bubble.setVisibility(INVISIBLE);
currentAnimator = null;
}
@Override
public void onAnimationCancel(Animator animation) {
super.onAnimationCancel(animation);
bubble.setVisibility(INVISIBLE);
currentAnimator = null;
}
});
currentAnimator.start();
}
}
| 7,664 | Java | .java | kartikhimself/Simple-Video-Player | 11 | 4 | 0 | 2019-07-03T02:35:28Z | 2019-07-02T15:42:27Z |
WrapContentLinearLayoutManager.java | /FileExtraction/Java_unseen/kartikhimself_Simple-Video-Player/app/src/main/java/com/sdcode/videoplayer/customizeUI/WrapContentLinearLayoutManager.java | package com.sdcode.videoplayer.customizeUI;
import android.content.Context;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.AttributeSet;
/**
* Created by Xi developer on 6/23/2017.
*/
public class WrapContentLinearLayoutManager extends LinearLayoutManager {
public WrapContentLinearLayoutManager(Context context) {
super(context);
}
public WrapContentLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
super(context, orientation, reverseLayout);
}
public WrapContentLinearLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
//... constructor
@Override
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
try {
super.onLayoutChildren(recycler, state);
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
}
}
@Override
public boolean supportsPredictiveItemAnimations() {
return false;
}
}
| 1,215 | Java | .java | kartikhimself/Simple-Video-Player | 11 | 4 | 0 | 2019-07-03T02:35:28Z | 2019-07-02T15:42:27Z |
SquareImageView.java | /FileExtraction/Java_unseen/kartikhimself_Simple-Video-Player/app/src/main/java/com/sdcode/videoplayer/customizeUI/SquareImageView.java | package com.sdcode.videoplayer.customizeUI;
import android.content.Context;
import android.util.AttributeSet;
/**
* Created by Xi developer on 3/29/2017.
*/
public class SquareImageView extends androidx.appcompat.widget.AppCompatImageView {
public SquareImageView(Context context) {
super(context);
}
public SquareImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SquareImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(getMeasuredWidth(), getMeasuredWidth());
}
} | 815 | Java | .java | kartikhimself/Simple-Video-Player | 11 | 4 | 0 | 2019-07-03T02:35:28Z | 2019-07-02T15:42:27Z |
PermissionCallback.java | /FileExtraction/Java_unseen/kartikhimself_Simple-Video-Player/app/src/main/java/com/sdcode/videoplayer/permission/PermissionCallback.java | /*
* The MIT License (MIT)
* Copyright (c) 2015 Michal Tajchert
* permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.sdcode.videoplayer.permission;
public interface PermissionCallback {
void permissionGranted();
void permissionRefused();
} | 1,269 | Java | .java | kartikhimself/Simple-Video-Player | 11 | 4 | 0 | 2019-07-03T02:35:28Z | 2019-07-02T15:42:27Z |
PermissionRequest.java | /FileExtraction/Java_unseen/kartikhimself_Simple-Video-Player/app/src/main/java/com/sdcode/videoplayer/permission/PermissionRequest.java | /*
* The MIT License (MIT)
* Copyright (c) 2015 Michal Tajchert
* permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.sdcode.videoplayer.permission;
import java.util.ArrayList;
import java.util.Random;
public class PermissionRequest {
private static Random random;
private ArrayList<String> permissions;
private int requestCode;
private PermissionCallback permissionCallback;
public PermissionRequest(int requestCode) {
this.requestCode = requestCode;
}
public PermissionRequest(ArrayList<String> permissions, PermissionCallback permissionCallback) {
this.permissions = permissions;
this.permissionCallback = permissionCallback;
if (random == null) {
random = new Random();
}
this.requestCode = random.nextInt(32768);
}
public ArrayList<String> getPermissions() {
return permissions;
}
public int getRequestCode() {
return requestCode;
}
public PermissionCallback getPermissionCallback() {
return permissionCallback;
}
public boolean equals(Object object) {
if (object == null) {
return false;
}
if (object instanceof PermissionRequest) {
return ((PermissionRequest) object).requestCode == this.requestCode;
}
return false;
}
@Override
public int hashCode() {
return requestCode;
}
} | 2,443 | Java | .java | kartikhimself/Simple-Video-Player | 11 | 4 | 0 | 2019-07-03T02:35:28Z | 2019-07-02T15:42:27Z |
PermissionListener.java | /FileExtraction/Java_unseen/kartikhimself_Simple-Video-Player/app/src/main/java/com/sdcode/videoplayer/permission/PermissionListener.java | /*
* The MIT License (MIT)
* Copyright (c) 2015 Michal Tajchert
* permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.sdcode.videoplayer.permission;
public interface PermissionListener {
/**
* Gets called each time we run kxUtils.permissionCompare() and some permission is revoke/granted to us
*
* @param permissionChanged
*/
void permissionsChanged(String permissionChanged);
/**
* Gets called each time we run kxUtils.permissionCompare() and some permission is granted
*
* @param permissionGranted
*/
void permissionsGranted(String permissionGranted);
/**
* Gets called each time we run kxUtils.permissionCompare() and some permission is removed
*
* @param permissionRemoved
*/
void permissionsRemoved(String permissionRemoved);
} | 1,838 | Java | .java | kartikhimself/Simple-Video-Player | 11 | 4 | 0 | 2019-07-03T02:35:28Z | 2019-07-02T15:42:27Z |
ExampleInstrumentedTest.java | /FileExtraction/Java_unseen/kartikhimself_Simple-Video-Player/app/src/androidTest/java/com/sdcode/videoplayer/ExampleInstrumentedTest.java | package com.sdcode.videoplayer;
import android.content.Context;
import androidx.test.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.sdcode.videoplayer", appContext.getPackageName());
}
}
| 714 | Java | .java | kartikhimself/Simple-Video-Player | 11 | 4 | 0 | 2019-07-03T02:35:28Z | 2019-07-02T15:42:27Z |
ApexTafApplicationTests.java | /FileExtraction/Java_unseen/dataconsulting-pl_APEX-Low-Test-Framework/src/test/java/pl/dataconsulting/APEX_TAF/ApexTafApplicationTests.java | package pl.dataconsulting.APEX_TAF;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class ApexTafApplicationTests {
@Test
void contextLoads() {
}
}
| 219 | Java | .java | dataconsulting-pl/APEX-Low-Test-Framework | 11 | 0 | 13 | 2022-06-28T07:57:50Z | 2023-02-27T10:25:42Z |
TestNGTest.java | /FileExtraction/Java_unseen/dataconsulting-pl_APEX-Low-Test-Framework/src/test/java/pl/dataconsulting/APEX_TAF/TestNGTest.java | package pl.dataconsulting.APEX_TAF;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
@SpringBootTest
public class TestNGTest extends AbstractTestNGSpringContextTests {
}
| 266 | Java | .java | dataconsulting-pl/APEX-Low-Test-Framework | 11 | 0 | 13 | 2022-06-28T07:57:50Z | 2023-02-27T10:25:42Z |
CucumberRunner.java | /FileExtraction/Java_unseen/dataconsulting-pl_APEX-Low-Test-Framework/src/test/java/pl/dataconsulting/APEX_TAF/CucumberRunner.java | package pl.dataconsulting.APEX_TAF;
import io.cucumber.testng.AbstractTestNGCucumberTests;
import io.cucumber.testng.CucumberOptions;
import org.testng.annotations.DataProvider;
@CucumberOptions(
features = {"src/test/java/pl/dataconsulting/APEX_TAF/exampleFeatures"},
tags = "@unit",
glue = {"pl.dataconsulting.APEX_TAF.stepDefinitions" },
monochrome = false,
dryRun = false,
plugin = {"pretty","html:target/cucumber.html", "json:target/cucumber.json"})
public class CucumberRunner extends AbstractTestNGCucumberTests {
@Override
@DataProvider(parallel = true)
public Object[][] scenarios(){
return super.scenarios();
}
} | 698 | Java | .java | dataconsulting-pl/APEX-Low-Test-Framework | 11 | 0 | 13 | 2022-06-28T07:57:50Z | 2023-02-27T10:25:42Z |
ApexTafApplication.java | /FileExtraction/Java_unseen/dataconsulting-pl_APEX-Low-Test-Framework/src/main/java/pl/dataconsulting/APEX_TAF/ApexTafApplication.java | package pl.dataconsulting.APEX_TAF;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ApexTafApplication {
public static void main(String[] args) {
SpringApplication.run(ApexTafApplication.class, args);
}
}
| 321 | Java | .java | dataconsulting-pl/APEX-Low-Test-Framework | 11 | 0 | 13 | 2022-06-28T07:57:50Z | 2023-02-27T10:25:42Z |
IRComponent.java | /FileExtraction/Java_unseen/dataconsulting-pl_APEX-Low-Test-Framework/src/main/java/pl/dataconsulting/APEX_TAF/APEXComponents/IRComponent.java | package pl.dataconsulting.APEX_TAF.APEXComponents;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.springframework.beans.factory.annotation.Autowired;
import org.testng.Assert;
import pl.dataconsulting.APEX_TAF.framework.annotation.APEXComponent;
import pl.dataconsulting.APEX_TAF.framework.util.Asserts;
import java.util.List;
import java.util.Map;
@APEXComponent
public class IRComponent extends BaseComponent {
//== XPATH Templates ==//
private String IR_TEMPLATE_XPATH = "//div[@aria-label='%s' and contains(@class, 't-IRR-region')]";
private String CELL_XPATH_TEMPLATE = ".//tr[%d]/td[@class=' u-tL' or @class=' u-tR'][%d]";
private String IR_HEADER_XPATH_TEMPLATE = ".//table[@class='a-IRR-table']/tr/th/a[text()='%s']";
private String SEARCH_WINDOW_XPATH_TEMPLATE = "//input[@class='a-IRR-sortWidget-searchField']";
private String WORKSHEET_RECORDS_XPATH_TEMPLATE = ".//table[@class='a-IRR-table']/tbody/tr";
private String COLUMNS_IDX_XPATH_TEMPLATE = ".//table[@class='a-IRR-table']/tr/th/a";
//== variables ==//
@Autowired
private Asserts asserts;
//== Methods ==//
/**
* Sets main IR Filter
*
* @param IRName - name of the IR component
* @param filter - Filter to be set. List of Maps, where k = header and v = value to set
*/
public void setMainIRGFilter(String IRName, List<Map<String, String>> filter) {
switchToMainFrame();
for (Map<String, String> row : filter) {
row.forEach((k, v) -> setIRFilter(getWorksheetByName(IRName), k, v));
}
}
/**
* Verifies that at least one record is dsiplayed in IR
*
* @param IRName - name of the IR component
*/
public void verifyAtLeastOneRowExists(String IRName) {
verifyAtLeastOneRecord(getWorksheetByName(IRName));
}
/**
* Compares values in IR cell
*
* @param IRName - name of the IR component
* @param expected - expected value. List of Maps, where k = header and v = value to compare
* @param startIdx - row from which comparison should be start
*/
public void compareMainIRValues(String IRName, List<Map<String, String>> expected, int startIdx) {
String action = "Compare Activities IR Values. ";
for (Map<String, String> row : expected) {
row.forEach((k, v) -> {
// if cell is empty, the value is passed as null by cucumber. Change it to empty string before comparison
if (v == null) {
v = "";
}
asserts.assertEqualRegexp(action, k, v, getCellValue(getWorksheetByName(IRName), startIdx - 1, k));
});
}
}
/**
* Gets the value from cell
*
* @param worksheet - IR component element
* @param row - row number
* @param columnName - column name
* @return - returns value from cell
*/
private String getCellValue(WebElement worksheet, int row, String columnName) {
int columnNumber = getColumnIdx(worksheet, columnName);
String xpathFinal = String.format(CELL_XPATH_TEMPLATE, row + 2, columnNumber + 1);
WebElement cell = worksheet.findElement(By.xpath(xpathFinal));
return cell.getText();
}
/**
* Sets main IR Filter
*
* @param worksheet - IR component element
* @param columnName - column name
* @param value - value to be set
*/
private void setIRFilter(WebElement worksheet, String columnName, String value) {
waitForApex();
String description = "Setting the filter for the column: %s with value %s";
WebElement element = worksheet.findElement(By.xpath(String.format(IR_HEADER_XPATH_TEMPLATE, columnName.toString())));
wait.until(ExpectedConditions.elementToBeClickable(element)).click();
waitForApex();
WebElement searchWindow = worksheet.findElement(By.xpath(SEARCH_WINDOW_XPATH_TEMPLATE));
sendKeys(searchWindow, value);
sendKey(Keys.ENTER);
waitForApex();
}
/**
* Verifies that at least one record is displayed in IR
*
* @param worksheet - IR component element
*/
private void verifyAtLeastOneRecord(WebElement worksheet) {
List<WebElement> elements = worksheet.findElements(By.xpath(WORKSHEET_RECORDS_XPATH_TEMPLATE));
Assert.assertTrue(elements.size() >= 2, "Verify that at least one record has been found in IR");
}
/**
* Get column index
*
* @param worksheet - IR component element
* @param columnName - name of the column to search
* @return - returns an index of the column
*/
private int getColumnIdx(WebElement worksheet, String columnName) {
String action = "Get Column Idx";
int idx = -1;
try {
List<WebElement> elements = worksheet.findElements(By.xpath(COLUMNS_IDX_XPATH_TEMPLATE));
for (int i = 0; i < elements.size(); i++) {
String tmp = elements.get(i).getText();
if (elements.get(i).getText().split("\n")[0].equalsIgnoreCase(columnName)) {
return i;
}
}
} catch (NumberFormatException e) {
Assert.fail("Number format exception by getting column index:" + e);
}
return idx;
}
/**
* Gets the Worksheet by name
*
* @param IRName - name of the IR
* @return - IR component webElement
*/
private WebElement getWorksheetByName(String IRName) {
WebElement searchedWebElement = driver.findElement(By.xpath(String.format(IR_TEMPLATE_XPATH, IRName)));
return searchedWebElement;
}
}
| 5,845 | Java | .java | dataconsulting-pl/APEX-Low-Test-Framework | 11 | 0 | 13 | 2022-06-28T07:57:50Z | 2023-02-27T10:25:42Z |
ButtonComponent.java | /FileExtraction/Java_unseen/dataconsulting-pl_APEX-Low-Test-Framework/src/main/java/pl/dataconsulting/APEX_TAF/APEXComponents/ButtonComponent.java | package pl.dataconsulting.APEX_TAF.APEXComponents;
import org.openqa.selenium.By;
import org.openqa.selenium.support.ui.ExpectedConditions;
import pl.dataconsulting.APEX_TAF.framework.annotation.APEXComponent;
@APEXComponent
public class ButtonComponent extends BaseComponent {
/**
* Presses the pop-up button
*
* @param frameName - name of the frame
* @param buttonName - button name
*/
public void pressPopUpButton(String frameName, String buttonName) {
switchToFrame(frameName);
String xpath = String.format("//button/span[text()='%s']", buttonName);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath(xpath))).click();
waitForApex();
}
/**
* Presses the button
*
* @param buttonName - button name
*/
public void pressButton(String buttonName) {
String xpath = String.format("//button/span[text()='%s']", buttonName);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath(xpath))).click();
waitForApex();
}
}
| 1,057 | Java | .java | dataconsulting-pl/APEX-Low-Test-Framework | 11 | 0 | 13 | 2022-06-28T07:57:50Z | 2023-02-27T10:25:42Z |
CheckboxComponent.java | /FileExtraction/Java_unseen/dataconsulting-pl_APEX-Low-Test-Framework/src/main/java/pl/dataconsulting/APEX_TAF/APEXComponents/CheckboxComponent.java | package pl.dataconsulting.APEX_TAF.APEXComponents;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.testng.Assert;
import org.testng.Reporter;
import pl.dataconsulting.APEX_TAF.framework.annotation.APEXComponent;
import java.util.List;
@APEXComponent
public class CheckboxComponent extends BaseComponent {
// == Checkbox Item action functions ==
/**
* Sets checkbox items on the checkbox component. As result, option given in the list will be set.
*
* @param itemName name (label) of the checkbox component
* @param optionNamesToSelect list of option to be selected
*/
public void setCheckboxesByOptionName(String itemName, List<String> optionNamesToSelect) {
WebElement element = getWebElementByLabel(itemName);
List<WebElement> options =
element.findElements(By.xpath("//*[@class='apex-item-option']/input[@type = 'checkbox']"));
List<String> notMatch = optionNamesToSelect.stream().filter(
s -> options.stream().noneMatch(name -> name.getAttribute("data-display").trim().equals(s.trim()))).toList();
List<WebElement> match = options.stream().filter(
s -> optionNamesToSelect.stream().anyMatch(name -> name.trim().equals(s.getAttribute("data-display").trim()))).toList();
if (!notMatch.isEmpty()) {
String log = String.join("; ", notMatch);
Assert.assertEquals("Not all checkbox options could be found", "All checkbox options could be found",
"Checkbox option not found: " + log);
}
if (match.isEmpty()) {
Reporter.log("Could not find any checkbox elements to select. Element list: " + String.join("; ", optionNamesToSelect));
}
String checkboxValuesToSelect = match.stream().map(e -> e.getAttribute("value")).reduce("", (a, b) -> a + ":" + b).substring(1);
setValueJS(element.getAttribute("id"), checkboxValuesToSelect);
}
/**
* Unsets checkbox items on the checkbox component. As result, option given in the list will be unset.
*
* @param itemName name (label) of the checkbox component
* @param optionNamesToUnset list of option to be unset
*/
public void unsetCheckboxesByOptionName(String itemName, List<String> optionNamesToUnset) {
WebElement element = getWebElementByLabel(itemName);
// get all the options
List<WebElement> options =
element.findElements(By.xpath("//*[@class='apex-item-option']/input[@type = 'checkbox']"));
// get selected options
List<String> selectedOptions = getSelectedOptions(element);
// get list of option that should be set after the action
List<String> toSelect = selectedOptions.stream().filter(
s -> optionNamesToUnset.stream().noneMatch(name -> name.trim().equals(s.trim()))).toList();
setCheckboxesByOptionName(itemName, toSelect);
}
// == String Item verification functions ==
/**
* Verifies selected checkbox items on the checkbox component.
*
* @param itemName name (label) of the checkbox component
* @param expectedOptionNames list of option that should be selected
*/
public void verifyCheckboxesByOptionName(String itemName, List<String> expectedOptionNames) {
WebElement element = getWebElementByLabel(itemName);
List<String> selectedOptions = getSelectedOptions(element);
List<String> notMatch = expectedOptionNames.stream().filter(
s -> selectedOptions.stream().noneMatch(name -> name.trim().equals(s.trim()))).toList();
if (!notMatch.isEmpty()) {
String log = String.join("; ", notMatch);
Assert.assertEquals("Not all checkbox are set", "All checkboxes are set",
"Checkbox option not set: " + log);
} else {
Assert.assertEquals("All checkbox options are set", "All checkbox options are set",
itemName + " Checkbox options set: " + String.join(";", expectedOptionNames));
}
}
}
| 4,157 | Java | .java | dataconsulting-pl/APEX-Low-Test-Framework | 11 | 0 | 13 | 2022-06-28T07:57:50Z | 2023-02-27T10:25:42Z |
RadioButtonComponent.java | /FileExtraction/Java_unseen/dataconsulting-pl_APEX-Low-Test-Framework/src/main/java/pl/dataconsulting/APEX_TAF/APEXComponents/RadioButtonComponent.java | package pl.dataconsulting.APEX_TAF.APEXComponents;
import org.apache.commons.lang3.ObjectUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.testng.Assert;
import org.testng.Reporter;
import pl.dataconsulting.APEX_TAF.framework.annotation.APEXComponent;
import java.util.List;
@APEXComponent
public class RadioButtonComponent extends BaseComponent {
// == RadioButton Item action functions ==
/**
* Sets radioButton items on the radioButton component. As result, option given in the list will be set.
*
* @param itemName name (label) of the radioButton component
* @param optionToSelect name of the option to be selected
*/
public void setRadioButtonByOptionName(String itemName, String optionToSelect) {
WebElement element = getWebElementByLabel(itemName);
WebElement option = element.findElement(By.xpath(
String.format("//*[@class='apex-item-option']/input[@type = 'radio' and @data-display='%s']", optionToSelect)));
if (option == null) {
Assert.assertEquals("A radioButton option could not be found", "A radioButton option could be found",
"RadioButton option not found: " + optionToSelect);
}
assert option != null;
String radioButtonValuesToSelect = option.getAttribute("value");
setValueJS(element.getAttribute("id"), radioButtonValuesToSelect);
}
// == String Item verification functions ==
/**
* Verifies selected radioButton items on the radioButton component.
*
* @param itemName name (label) of the radioButton component
* @param expectedOptionName name of the option that should be selected
*/
public void verifyRadioButtonsByOptionName(String itemName, String expectedOptionName) {
WebElement element = getWebElementByLabel(itemName);
String selectedOptions = getSelectedOption(element);
if (selectedOptions.equals(expectedOptionName)) {
Assert.assertEquals("Expected radioButton option set", "Expected radioButton option set",
itemName + " Expected radioButton option set: " + expectedOptionName);
} else {
Assert.assertEquals("Expected radioButton option not set", "Expected radioButton option set",
itemName + " Expected radioButton option not set: " + expectedOptionName);
}
}
}
| 2,456 | Java | .java | dataconsulting-pl/APEX-Low-Test-Framework | 11 | 0 | 13 | 2022-06-28T07:57:50Z | 2023-02-27T10:25:42Z |
SwitchItemComponent.java | /FileExtraction/Java_unseen/dataconsulting-pl_APEX-Low-Test-Framework/src/main/java/pl/dataconsulting/APEX_TAF/APEXComponents/SwitchItemComponent.java | package pl.dataconsulting.APEX_TAF.APEXComponents;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.testng.Assert;
import pl.dataconsulting.APEX_TAF.framework.annotation.APEXComponent;
@APEXComponent
public class SwitchItemComponent extends BaseComponent {
/**
* Switches switch item to on
*
* @param switchItemName - name of the switch item
* @param frameTitle - name of the frame
*/
public void switchItemOn(String switchItemName, String frameTitle) {
switchToFrame(frameTitle);
switchItem(getWebElementByLabel(switchItemName), true);
}
/**
* Switches switch item to on
*
* @param switchItemName - name of the switch item
*/
public void switchItemOn(String switchItemName) {
switchItem(getWebElementByLabel(switchItemName), true);
}
/**
* Switches switch item to off
*
* @param switchItemName - name of the switch item
* @param frameTitle - name of the frame
*/
public void switchItemOff(String switchItemName, String frameTitle) {
switchToFrame(frameTitle);
switchItem(getWebElementByLabel(switchItemName), false);
}
/**
* Switches switch item to off
*
* @param switchItemName - name of the switch item
*/
public void switchItemOff(String switchItemName) {
switchItem(getWebElementByLabel(switchItemName), false);
}
/**
* Verifies switch item
*
* @param switchItemName - name of the switch item
* @param expected - expected value. True - element is switched to on
*/
public void verifySwitchItem(String switchItemName, boolean expected) {
String message = "Verify Switch item: " + switchItemName;
if (expected) {
Assert.assertEquals(getValueJS(getWebElementByLabel(switchItemName)),
"Y", message);
} else {
Assert.assertEquals(getValueJS(getWebElementByLabel(switchItemName)),
"N", message);
}
}
/**
* Switches item value using JS
* @param switchItemElement - WebElement of the switch item
* @param switchTo - target switch option. Y or N.
*/
private void switchItem(WebElement switchItemElement, boolean switchTo) {
if (switchTo)
setValueJS(switchItemElement, "Y");
else
setValueJS(switchItemElement, "N");
}
}
| 2,570 | Java | .java | dataconsulting-pl/APEX-Low-Test-Framework | 11 | 0 | 13 | 2022-06-28T07:57:50Z | 2023-02-27T10:25:42Z |
SelectItemComponent.java | /FileExtraction/Java_unseen/dataconsulting-pl_APEX-Low-Test-Framework/src/main/java/pl/dataconsulting/APEX_TAF/APEXComponents/SelectItemComponent.java | package pl.dataconsulting.APEX_TAF.APEXComponents;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.testng.Assert;
import pl.dataconsulting.APEX_TAF.framework.annotation.APEXComponent;
@APEXComponent
public class SelectItemComponent extends BaseComponent {
/**
* Selects value in select item
*
* @param frameTitle - name of the frame where select item is located
* @param value - value to be selected
* @param fieldName - name of the field
*/
public void selectItem(String frameTitle, String value, String fieldName) {
switchToFrame(frameTitle);
selectItemsValue(getWebElementByLabel(fieldName), value);
}
/**
* Selects value in select item
*
* @param value - value to be selected
* @param fieldName - name of the
*/
public void selectItem(String value, String fieldName) {
selectItemsValue(getWebElementByLabel(fieldName), value);
}
/**
* Verifies value in select item
*
* @param expectedValue - value to be verified
* @param fieldName - name of the field
*/
public void verifySelectItemValue(String expectedValue, String fieldName) {
WebElement selectItem = getWebElementByLabel(fieldName);
final Select selectBox = new Select(selectItem);
String selectedOption = selectBox.getFirstSelectedOption().getText();
Assert.assertEquals(selectedOption.trim(), expectedValue.trim(), "Compare selected value in select item filed: " + fieldName);
}
/**
* Select value in select List
*
* @param element - WebElement of the select item item
* @param value - value to be selected
*/
private void selectItemsValue(WebElement element, String value) {
wait.until(ExpectedConditions.elementToBeClickable(element));
final Select selectBox = new Select(element);
selectBox.selectByVisibleText(value);
}
}
| 2,051 | Java | .java | dataconsulting-pl/APEX-Low-Test-Framework | 11 | 0 | 13 | 2022-06-28T07:57:50Z | 2023-02-27T10:25:42Z |
MenuComponent.java | /FileExtraction/Java_unseen/dataconsulting-pl_APEX-Low-Test-Framework/src/main/java/pl/dataconsulting/APEX_TAF/APEXComponents/MenuComponent.java | package pl.dataconsulting.APEX_TAF.APEXComponents;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.testng.Assert;
import pl.dataconsulting.APEX_TAF.framework.annotation.APEXComponent;
import java.util.ArrayList;
import java.util.List;
@APEXComponent
public class MenuComponent extends BaseComponent {
private final String MAIN_MENU_TEMPLATE_XPATH_MAIN = "//*[@aria-level=1][contains(text(),'%s')]";
private final String MAIN_MENU_TEMPLATE_XPATH_SUB = "/../..//*[@aria-level=%d][contains(text(),'%s')]";
private @FindBy(id = "t_Button_navControl")
WebElement navButton;
/**
* Navigates to menu element.
*
* @param menuOptions - List of menu and sub-menu elements counted from top.
*/
public void navigateToMenu(List<String> menuOptions) {
// click on the main menu
if (menuOptions.size() > 0) {
extendMenu();
List<String> menuWebElements = getMenuElementsXpath(menuOptions);
for (int i = 0; i < menuWebElements.size(); i++) {
WebElement menuElement = driver.findElement(By.xpath(menuWebElements.get(i)));
wait.until(ExpectedConditions.elementToBeClickable(menuElement)).click();
// get Again menu element
menuElement = driver.findElement(By.xpath(menuWebElements.get(i)));
if (menuElement.getAttribute("aria-expanded") != null &&
menuElement.getAttribute("aria-expanded").equals("false") &&
i < menuWebElements.size() - 1) {
wait.until(ExpectedConditions.elementToBeClickable(
menuElement.findElement(By.xpath("../../span[@class='a-TreeView-toggle']")))
).click();
}
}
}
}
/**
* Verifies, if menu option is selected
*
* @param menuOption - List of menu and sub-menu elements counted from top.
*/
public void verifyMenuOption(List<String> menuOption) {
String lastOptionXpath = getMenuElementsXpath(menuOption).get(getMenuElementsXpath(menuOption).size() - 1);
WebElement menuElement = driver.findElement(By.xpath(lastOptionXpath));
if (menuElement.getAttribute("aria-selected") != null &&
menuElement.getAttribute("aria-selected").equals("true")) {
Assert.assertEquals("Menu element selected", "Menu element selected", "Menu element: "
+ menuElement.getText());
} else {
Assert.assertEquals("Menu element selected", "Menu element not selected", "Menu element: "
+ menuElement.getText());
}
}
/**
* Gets xpaths of menu options
*
* @param menuOption - List of menu and sub-menu elements counted from top.
* @return - List contains xpath of menu options
*/
private List<String> getMenuElementsXpath(List<String> menuOption) {
List<String> menuElements = new ArrayList<>();
String elementXpath = String.format(MAIN_MENU_TEMPLATE_XPATH_MAIN, menuOption.get(0));
menuElements.add(elementXpath);
for (int i = 1; i < menuOption.size(); i++) {
elementXpath = elementXpath + String.format(MAIN_MENU_TEMPLATE_XPATH_SUB, i + 1, menuOption.get(i));
menuElements.add(elementXpath);
}
return menuElements;
}
/**
* Extend main APEX menu
*/
private void extendMenu() {
String ariaExtendedIs = navButton.getAttribute("aria-expanded");
if (ariaExtendedIs.equalsIgnoreCase("false")) {
wait.until(ExpectedConditions.elementToBeClickable(navButton)).click();
}
}
}
| 3,845 | Java | .java | dataconsulting-pl/APEX-Low-Test-Framework | 11 | 0 | 13 | 2022-06-28T07:57:50Z | 2023-02-27T10:25:42Z |
ShuttleComponent.java | /FileExtraction/Java_unseen/dataconsulting-pl_APEX-Low-Test-Framework/src/main/java/pl/dataconsulting/APEX_TAF/APEXComponents/ShuttleComponent.java | package pl.dataconsulting.APEX_TAF.APEXComponents;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.testng.Assert;
import org.testng.Reporter;
import pl.dataconsulting.APEX_TAF.framework.annotation.APEXComponent;
import java.util.List;
@APEXComponent
public class ShuttleComponent extends BaseComponent {
// == Radio Item action functions ==
/**
* Sets shuttle options in the shuttle component. As result, option given in the list will be set.
*
* @param radioItemName name (label) of the radiobox component
* @param optionNamesToSelect list of option to be selected
*/
public void moveShuttleOptionName(String radioItemName, List<String> optionNamesToSelect) {
WebElement element = getWebElementByLabel(radioItemName);
List<WebElement> optionToBeSelected =
element.findElements(By.xpath("//*[contains(@class, 'apex-item-select') and contains(@class, 'shuttle')]/option[not(@disabled)]"));
List<String> notMatch = optionNamesToSelect.stream().filter(
s -> optionToBeSelected.stream().noneMatch(name -> name.getText().trim().equals(s.trim()))).toList();
List<WebElement> match = optionToBeSelected.stream().filter(
s -> optionNamesToSelect.stream().anyMatch(name -> name.trim().equals(s.getText().trim()))).toList();
if (!notMatch.isEmpty()) {
String log = String.join("; ", notMatch);
Assert.assertEquals("Not all Shuttle options could be found", "All Shuttle options could be found",
"Checkbox option not found: " + log);
}
if (match.isEmpty()) {
Reporter.log("Could not find any Shuttle elements to select. Element list: " + String.join("; ", optionNamesToSelect));
}
String radioValuesToSelect = match.stream().map(e -> e.getAttribute("value")).reduce("", (a, b) -> a + ":" + b).substring(1);
setValueJS(element.getAttribute("id"), radioValuesToSelect);
}
/**
* Move all shuttle options in the shuttle component. As result, option given in the list will be set.
*
* @param radioItemName name (label) of the radiobox component
*/
public void moveAllShuttleOptions(String radioItemName) {
WebElement element = getWebElementByLabel(radioItemName);
List<WebElement> optionToBeSelected =
element.findElements(By.xpath("//*[contains(@class, 'apex-item-select') and contains(@class, 'shuttle')]/option[not(@disabled)]"));
String radioValuesToSelect = optionToBeSelected.stream().map(e -> e.getAttribute("value")).reduce("", (a, b) -> a + ":" + b).substring(1);
setValueJS(element.getAttribute("id"), radioValuesToSelect);
}
/**
* Remove selections from shuttle component. As result, option given in the list will be removed.
*
* @param itemName name (label) of the radiobox component
* @param optionNamesToRemove list of option to be removed
*/
public void removeShuttleOptionName(String itemName, List<String> optionNamesToRemove) {
WebElement element = getWebElementByLabel(itemName);
// get all the options
List<WebElement> options =
element.findElements(By.xpath("//*[contains(@class, 'apex-item-select') and contains(@class, 'shuttle')]/option[not(@disabled)]"));
// get selected options
List<String> selectedOptions = getSelectedOptions(element);
// get list of option that should be set after the action
List<String> toSelect = selectedOptions.stream().filter(
s -> optionNamesToRemove.stream().noneMatch(name -> name.trim().equals(s.trim()))).toList();
moveShuttleOptionName(itemName, toSelect);
}
/**
* Move all shuttle options in the shuttle component. As result, option given in the list will be set.
*
* @param radioItemName name (label) of the radiobox component
*/
public void removeAllShuttleOptions(String radioItemName) {
WebElement element = getWebElementByLabel(radioItemName);
setValueJS(element.getAttribute("id"), "");
}
// == String Item verification functions ==
/**
* Verifies chooses shuttle items in the shuttle component.
*
* @param itemName name (label) of the shuttle component
* @param expectedOptionNames list of option that should be chosen
*/
public void verifyShuttleByOptionName(String itemName, List<String> expectedOptionNames) {
WebElement element = getWebElementByLabel(itemName);
List<String> selectedOptions = getSelectedOptions(element);
List<String> notMatch = expectedOptionNames.stream().filter(
s -> selectedOptions.stream().noneMatch(name -> name.trim().equals(s.trim()))).toList();
if (!notMatch.isEmpty()) {
String log = String.join("; ", notMatch);
Assert.assertEquals("Not all shuttle options are chosen on shuttle item ", "All checkboxes are set",
itemName + " Shuttle options not set : " + log);
} else {
Assert.assertEquals("All shuttle options are chosen on shuttle item", "All shuttle options are chosen on shuttle item",
itemName + " Shuttle options set : " + String.join(";", expectedOptionNames));
}
}
/**
* Verifies that no elements are chooses sin in the shuttle component.
*
* @param itemName name (label) of the shuttle component
*/
public void verifyNoShuttleOptionChosen(String itemName) {
WebElement element = getWebElementByLabel(itemName);
List<String> selectedOptions = getSelectedOptions(element);
if (!selectedOptions.isEmpty()) {
String log = String.join("; ", selectedOptions);
Assert.assertEquals("Some shuttle options are chosen in shuttle item ", "No shuttle options are chosen in shuttle item",
itemName + " Shuttle options chosen : " + log);
} else {
Assert.assertEquals("No shuttle options are chosen in shuttle item", "No shuttle options are chosen in shuttle item",
"No option chosen on shuttle item: " + itemName);
}
}
/**
* Moves all values in shuttle item
*
* @param itemName name (label) of the shuttle component
*/
public void moveAllValues(String itemName) {
WebElement element = getWebElementByLabel(itemName);
}
}
| 6,551 | Java | .java | dataconsulting-pl/APEX-Low-Test-Framework | 11 | 0 | 13 | 2022-06-28T07:57:50Z | 2023-02-27T10:25:42Z |
FormComponent.java | /FileExtraction/Java_unseen/dataconsulting-pl_APEX-Low-Test-Framework/src/main/java/pl/dataconsulting/APEX_TAF/APEXComponents/FormComponent.java | package pl.dataconsulting.APEX_TAF.APEXComponents;
import org.testng.Assert;
import pl.dataconsulting.APEX_TAF.framework.annotation.APEXComponent;
@APEXComponent
public class FormComponent extends BaseComponent {
// == String Item action functions ==
/**
* Enters text to the text item component
*
* @param frameTitle - name of the frame
* @param fieldName - name of the field
* @param text - text to enter
*/
public void enterStringIntoTextItem(String frameTitle, String fieldName, String text) {
switchToFrame(frameTitle);
sendKeys(getWebElementByLabel(fieldName), text);
}
/**
* Enters text to the text item component
*
* @param fieldName - name of the field
* @param text - text to enter
*/
public void enterStringIntoTextItem(String fieldName, String text) {
sendKeys(getWebElementByLabel(fieldName), text);
}
// == String Item verification functions ==
/**
* Verifies text in the text field
*
* @param fieldName - name of the filed
* @param expectedValue - expected value
*/
public void verifyTextItemValue(String fieldName, String expectedValue) {
Assert.assertEquals(getTextFromWebElement(getWebElementByLabel(fieldName)), expectedValue);
}
/**
* Verifies validation message of the corresponding field
*
* @param frameName - name of the frame
* @param fieldName - field name
* @param expectedMessage - expected message
*/
public void verifyValidationMessage(String frameName, String fieldName, String expectedMessage) {
switchToFrame(frameName);
Assert.assertEquals(getValidationWebElementByLabel(fieldName).getText(), expectedMessage);
}
/**
* Verifies validation message of the corresponding field
*
* @param fieldName - field name
* @param expectedMessage - expected message
*/
public void verifyValidationMessage(String fieldName, String expectedMessage) {
Assert.assertEquals(getValidationWebElementByLabel(fieldName).getText(), expectedMessage);
}
}
| 2,170 | Java | .java | dataconsulting-pl/APEX-Low-Test-Framework | 11 | 0 | 13 | 2022-06-28T07:57:50Z | 2023-02-27T10:25:42Z |
BaseComponent.java | /FileExtraction/Java_unseen/dataconsulting-pl_APEX-Low-Test-Framework/src/main/java/pl/dataconsulting/APEX_TAF/APEXComponents/BaseComponent.java | package pl.dataconsulting.APEX_TAF.APEXComponents;
import org.openqa.selenium.*;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.springframework.beans.factory.annotation.Autowired;
import org.testng.Assert;
import pl.dataconsulting.APEX_TAF.framework.annotation.APEXComponent;
import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@APEXComponent
public class BaseComponent {
@Autowired
protected WebDriver driver;
@Autowired
protected WebDriverWait wait;
@PostConstruct
private void init() {
PageFactory.initElements(this.driver, this);
}
public void navigateToUrl(String url) {
driver.get(url);
}
protected void sendKeys(By by, String textToSend) {
wait.until(ExpectedConditions.elementToBeClickable(by)).sendKeys(textToSend);
}
/**
* Switches content back to main frame
*/
public void switchToMainFrame() {
driver.switchTo().defaultContent();
}
/**
* Switches content back to given frame
*
* @param frameTitle - title of the iframe
*/
public void switchToFrame(String frameTitle) {
final List<WebElement> iframes = driver.findElements(By.tagName("iframe"));
for (WebElement iframe : iframes) {
if (iframe.getAttribute("title").equalsIgnoreCase(frameTitle)) {
driver.switchTo().frame(iframe);
break;
}
}
}
/**
* Sends keys to webElement
*
* @param element - webElement to where the key must be sent
* @param textToSend - text to be sent
*/
protected void sendKeys(WebElement element, String textToSend) {
wait.until(ExpectedConditions.elementToBeClickable(element)).sendKeys(textToSend);
}
/**
* Sends key to driver
*
* @param key - key to be sent
*/
protected void sendKey(Keys key) {
Actions actions = new Actions(driver);
actions.sendKeys(key);
actions.perform();
}
/**
* Gets text from webElement
*
* @param element - webElement from which text should be returend
* @return - returns text of the given webElement
*/
protected String getTextFromWebElement(WebElement element) {
wait.until(ExpectedConditions.visibilityOf(element));
return element.getAttribute("value");
}
/**
* Gets webElement by its label
*
* @param label - label of the APEX component
* @return - returns webElement of the corresponding label
*/
protected WebElement getWebElementByLabel(String label) {
String action = "Search element by its label";
String ELEMENT_TEMPLATE_XPATH_STARTS_WITH = "//*[contains(@class,'t-Form-label') and starts-with(text(),'%s')]/.";
String ELEMENT_TEMPLATE_XPATH_CONTAINS = "//*[contains(@class,'t-Form-label') and starts-with(text(),'%s')]/.";
String xpath = String.format(ELEMENT_TEMPLATE_XPATH_STARTS_WITH, label);
WebElement element = driver.findElement(By.xpath(xpath));
if (element == null) {
// try to find element using CONTAINS
xpath = String.format(ELEMENT_TEMPLATE_XPATH_CONTAINS, label);
element = driver.findElement(By.xpath(xpath));
}
String searchElementId = element.getAttribute("for");
if (searchElementId == null) {
Assert.assertEquals("Web element could not be found", "Web element can be found",
"Searched webElement: " + label);
return null;
}
WebElement searchedWebElement = driver.findElement(By.id(searchElementId));
return searchedWebElement;
}
/**
* Gets validation webElement by its label
*
* @param label - label of the APEX component
* @return - returns validation webElement of the corresponding label
*/
protected WebElement getValidationWebElementByLabel(String label) {
String action = "Search element by its label";
String ELEMENT_TEMPLATE_XPATH = "//*[contains(@class,'t-Form-label') and starts-with(text(),'%s')]/.";
String xpath = String.format(ELEMENT_TEMPLATE_XPATH, label);
WebElement element = driver.findElement(By.xpath(xpath));
String searchElementId = element.getAttribute("for");
if (searchElementId == null) {
Assert.assertEquals("Web element could not be found", "Web element can be found",
"Searched webElement: " + label);
return null;
}
WebElement searchedWebElement = driver.findElement(By.id(searchElementId + "_error"));
return searchedWebElement;
}
/**
* Waits until u-Processing class is visible
*/
protected void waitForApex() {
try {
while (driver.findElements(By.className("u-Processing")).size() > 0) {
Thread.sleep(200);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* Gets selected options of APEX item using JS
*
* @param element - corresponding webElement
* @return - returns list of selected option
*/
protected List<String> getSelectedOptions(WebElement element) {
String script = String.format("return apex.item( \"%s\" ).displayValueFor( apex.item( \"%s\").getValue() )",
element.getAttribute("id"),
element.getAttribute("id"));
JavascriptExecutor js = (JavascriptExecutor) driver;
Object jsResult = js.executeScript(script, " ");
if (jsResult instanceof String stringResult) {
return Arrays.stream(stringResult.split(",")).toList();
} else if (jsResult instanceof ArrayList<?>) {
return (List<String>) jsResult;
} else
return null;
}
/**
* Gets selected option of APEX item using JS
*
* @param element - corresponding webElement
* @return - returns selected option
*/
protected String getSelectedOption(WebElement element) {
String script = String.format("return apex.item( \"%s\" ).displayValueFor( apex.item( \"%s\").getValue() )",
element.getAttribute("id"),
element.getAttribute("id"));
JavascriptExecutor js = (JavascriptExecutor) driver;
Object jsResult = js.executeScript(script, " ");
if (jsResult instanceof String stringResult) {
return stringResult;
} else if (jsResult instanceof ArrayList<?>) {
return jsResult.toString();
} else
return null;
}
/**
* Gets value of APEX item using JS
*
* @param element - corresponding webElement
* @return - returns value of the APEX item
*/
protected String getValueJS(WebElement element) {
String script = String.format("return apex.item( \"%s\" ).getValue()",
element.getAttribute("id"));
JavascriptExecutor js = (JavascriptExecutor) driver;
Object jsResult = js.executeScript(script, " ");
if (jsResult instanceof String stringResult) {
return stringResult;
} else {
Assert.assertEquals("Value read from APEX element: " + element.getAttribute("id") + " is not String value",
"Value read from APEX element " + element.getAttribute("id") + " is String value",
"Verify value returned by APEX element.");
return null;
}
}
// == private functions ==
/**
* Sets the Value of APEX item using JS
*
* @param item - name of the APEX item
* @param elementId - id of the element
*/
protected void setValueJS(String item, String elementId) {
JavascriptExecutor js = (JavascriptExecutor) driver;
String SetValueTemplate = "apex.item( \"%s\").setValue(\"%s\")";
js.executeScript(String.format(SetValueTemplate, item, elementId), "");
}
/**
* Sets the Value of APEX item using JS
*
* @param element
* @param elementId
*/
protected void setValueJS(WebElement element, String elementId) {
String item = element.getAttribute("id");
setValueJS(item, elementId);
}
}
| 8,499 | Java | .java | dataconsulting-pl/APEX-Low-Test-Framework | 11 | 0 | 13 | 2022-06-28T07:57:50Z | 2023-02-27T10:25:42Z |
RadioButtonItemSteps.java | /FileExtraction/Java_unseen/dataconsulting-pl_APEX-Low-Test-Framework/src/main/java/pl/dataconsulting/APEX_TAF/stepDefinitions/RadioButtonItemSteps.java | package pl.dataconsulting.APEX_TAF.stepDefinitions;
import io.cucumber.java.ParameterType;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import org.springframework.beans.factory.annotation.Autowired;
import pl.dataconsulting.APEX_TAF.APEXComponents.RadioButtonComponent;
import java.util.Arrays;
import java.util.List;
public class RadioButtonItemSteps {
@Autowired
private RadioButtonComponent radioButtonComponent;
/**
* Step sets radioButton for radioButton item.
*
* @param options - option to be selected
* @param itemName - the name of a radioButton item
*/
@When("user sets radioButton {string} for {string} radioButton item")
public void user_sets_radioButton(String options, String itemName) {
radioButtonComponent.setRadioButtonByOptionName(itemName, options);
}
/**
* Step verifies, if given radioButton is selected
* @param option - expected selected option
* @param itemName - the name of the radioButton item
*/
@Then("radioButton {string} in {string} radioButton is selected")
public void verify_selected_radioButton(String option, String itemName) {
radioButtonComponent.verifyRadioButtonsByOptionName(itemName, option);
}
}
| 1,271 | Java | .java | dataconsulting-pl/APEX-Low-Test-Framework | 11 | 0 | 13 | 2022-06-28T07:57:50Z | 2023-02-27T10:25:42Z |
ButtonItemSteps.java | /FileExtraction/Java_unseen/dataconsulting-pl_APEX-Low-Test-Framework/src/main/java/pl/dataconsulting/APEX_TAF/stepDefinitions/ButtonItemSteps.java | package pl.dataconsulting.APEX_TAF.stepDefinitions;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.When;
import org.springframework.beans.factory.annotation.Autowired;
import pl.dataconsulting.APEX_TAF.APEXComponents.ButtonComponent;
public class ButtonItemSteps {
@Autowired
private ButtonComponent buttonComponent;
/**
* Step presses the button on pop-up by its name
* @param buttonName - name of the button
* @param frameName - iframe name (pop-up name)
*/
@When("user presses the {string} button on {string} pop-up")
public void user_presses_the_button_on_popup(String buttonName, String frameName) {
buttonComponent.pressPopUpButton(frameName, buttonName);
}
/**
* Step presses the button by its name
* @param buttonName - name of the button
*/
@Given("user clicked on the {string} button")
@When("user presses the {string} button")
public void user_presses_the_button(String buttonName) {
buttonComponent.pressButton(buttonName);
}
}
| 1,056 | Java | .java | dataconsulting-pl/APEX-Low-Test-Framework | 11 | 0 | 13 | 2022-06-28T07:57:50Z | 2023-02-27T10:25:42Z |
CheckboxItemSteps.java | /FileExtraction/Java_unseen/dataconsulting-pl_APEX-Low-Test-Framework/src/main/java/pl/dataconsulting/APEX_TAF/stepDefinitions/CheckboxItemSteps.java | package pl.dataconsulting.APEX_TAF.stepDefinitions;
import io.cucumber.java.ParameterType;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import org.springframework.beans.factory.annotation.Autowired;
import pl.dataconsulting.APEX_TAF.APEXComponents.CheckboxComponent;
import java.util.Arrays;
import java.util.List;
public class CheckboxItemSteps {
@Autowired
private CheckboxComponent checkboxComponent;
/**
* Step sets checkboxes for checkbox item. Only given checkboxes will be set and the rest present checkboxes will be unset
*
* @param options - list of checkboxes separated by comma to be selected, for example: item1, item2, item3
* @param itemName - the name of a checkbox item
*/
@When("user sets checkbox(es) {listOfStrings} for {string} checkbox item")
public void user_sets_checkboxes(List<String> options, String itemName) {
checkboxComponent.setCheckboxesByOptionName(itemName, options);
}
/**
* Step Verifies selected checkbox items
*
* @param options - List of options (separated by comma) that should be selected.
* @param itemName - name of the item
*/
@Then("checkbox(es) {listOfStrings} in {string} checkbox are/is selected")
public void verify_selected_checkboxes(List<String> options, String itemName) {
checkboxComponent.verifyCheckboxesByOptionName(itemName, options);
}
/**
* Step unsets given checkboxes
*
* @param options - List of options (separated by comma) to unset.
* @param itemName - name of the item
*/
@When("user unsets checkbox(es) {listOfStrings} for {string} checkbox item")
public void user_unsets_checkboxes(List<String> options, String itemName) {
checkboxComponent.unsetCheckboxesByOptionName(itemName, options);
}
}
| 1,848 | Java | .java | dataconsulting-pl/APEX-Low-Test-Framework | 11 | 0 | 13 | 2022-06-28T07:57:50Z | 2023-02-27T10:25:42Z |
CucumberSpringConfiguration.java | /FileExtraction/Java_unseen/dataconsulting-pl_APEX-Low-Test-Framework/src/main/java/pl/dataconsulting/APEX_TAF/stepDefinitions/CucumberSpringConfiguration.java | package pl.dataconsulting.APEX_TAF.stepDefinitions;
import io.cucumber.spring.CucumberContextConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
@CucumberContextConfiguration
public class CucumberSpringConfiguration {
}
| 262 | Java | .java | dataconsulting-pl/APEX-Low-Test-Framework | 11 | 0 | 13 | 2022-06-28T07:57:50Z | 2023-02-27T10:25:42Z |
SelectItemSteps.java | /FileExtraction/Java_unseen/dataconsulting-pl_APEX-Low-Test-Framework/src/main/java/pl/dataconsulting/APEX_TAF/stepDefinitions/SelectItemSteps.java | package pl.dataconsulting.APEX_TAF.stepDefinitions;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import org.springframework.beans.factory.annotation.Autowired;
import pl.dataconsulting.APEX_TAF.APEXComponents.SelectItemComponent;
public class SelectItemSteps {
@Autowired
private SelectItemComponent selectItemComponent;
/**
* Step selects an option on the select item
* @param value - option to be selected
* @param fieldName - name of the filed
* @param frameName - frame/pop-up name
*/
@Given("user selected {string} in {string} field on {string} pop-up")
@When("user selects {string} in {string} field on {string} pop-up")
public void user_set_value_in_select_item(String value, String fieldName, String frameName) {
selectItemComponent.selectItem(frameName, value, fieldName);
}
/**
* Step selects an option on the select item
* @param value - option to be selected
* @param fieldName - name of the filed
*/
@Given("user selected {string} in {string} field")
@When("user selects {string} in {string} field")
public void user_set_value_in_select_item(String value, String fieldName) {
selectItemComponent.selectItem(value, fieldName);
}
/**
* Step verifies a value in the select item
* @param expectedValue - option to be selected
* @param fieldName - name of the filed
*/
@Then("value {string} is selected in {string} field")
public void verify_select_item(String expectedValue, String fieldName) {
selectItemComponent.verifySelectItemValue(expectedValue, fieldName);
}
}
| 1,696 | Java | .java | dataconsulting-pl/APEX-Low-Test-Framework | 11 | 0 | 13 | 2022-06-28T07:57:50Z | 2023-02-27T10:25:42Z |
ShuttleItemSteps.java | /FileExtraction/Java_unseen/dataconsulting-pl_APEX-Low-Test-Framework/src/main/java/pl/dataconsulting/APEX_TAF/stepDefinitions/ShuttleItemSteps.java | package pl.dataconsulting.APEX_TAF.stepDefinitions;
import io.cucumber.java.ParameterType;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import org.springframework.beans.factory.annotation.Autowired;
import pl.dataconsulting.APEX_TAF.APEXComponents.ShuttleComponent;
import java.util.Arrays;
import java.util.List;
public class ShuttleItemSteps {
@Autowired
private ShuttleComponent shuttleComponent;
/**
* Step moves given options in shuttle item
* @param options - options separated by coma, e.g. option 1, option2.
* @param itemName - name of the shuttle item
*/
@When("user moves value(s) {listOfStrings} in {string} shuttle item")
public void user_moves_values(List<String> options, String itemName) {
shuttleComponent.moveShuttleOptionName(itemName, options);
}
/**
* Step removes given options in shuttle item
* @param options - options separated by coma, e.g. option 1, option2.
* @param itemName - name of the shuttle item
*/
@When("user removes value(s) {listOfStrings} in {string} shuttle item")
public void user_removes_values(List<String> options, String itemName) {
shuttleComponent.removeShuttleOptionName(itemName, options);
}
/**
* Step moves all options in shuttle item
* @param itemName - name of the shuttle item
*/
@When("user moves all values in {string} shuttle item")
public void user_moves_all_values(String itemName) {
shuttleComponent.moveAllShuttleOptions(itemName);
}
/**
* Step removes all options in shuttle item
* @param itemName - name of the shuttle item
*/
@When("user removes all values in {string} shuttle item")
public void remove_all_values(String itemName) {
shuttleComponent.removeAllShuttleOptions(itemName);
}
/**
* Step verify, if given option are moved in shuttle item
* @param options - options separated by coma, e.g. option 1, option2.
* @param itemName - name of the shuttle item
*/
@Then("value(s) {listOfStrings} in {string} shuttle item is/are chosen")
public void verify_chosen_values(List<String> options, String itemName) {
shuttleComponent.verifyShuttleByOptionName(itemName,options);
}
/**
* Step, verifies if none of the option is moved in shuttle item
* @param itemName - name of the shuttle item
*/
@Then("no value(s) in {string} shuttle item is/are chosen")
public void verify_chosen_values(String itemName) {
shuttleComponent.verifyNoShuttleOptionChosen(itemName);
}
}
| 2,620 | Java | .java | dataconsulting-pl/APEX-Low-Test-Framework | 11 | 0 | 13 | 2022-06-28T07:57:50Z | 2023-02-27T10:25:42Z |
TextFieldSteps.java | /FileExtraction/Java_unseen/dataconsulting-pl_APEX-Low-Test-Framework/src/main/java/pl/dataconsulting/APEX_TAF/stepDefinitions/TextFieldSteps.java | package pl.dataconsulting.APEX_TAF.stepDefinitions;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import org.springframework.beans.factory.annotation.Autowired;
import pl.dataconsulting.APEX_TAF.APEXComponents.FormComponent;
public class TextFieldSteps {
@Autowired
private FormComponent formComponent;
/**
* Step enters given text into the text field
*
* @param value - text to enter
* @param fieldName - text field name
* @param frameName - frame/pop-up name
*/
@Given("user entered {string} in {string} field on {string} pop-up")
@When("user enters {string} in {string} field on {string} pop-up")
public void user_enters_text_into_field(String value, String fieldName, String frameName) {
formComponent.enterStringIntoTextItem(frameName, fieldName, value);
}
/**
* Step enters given text into the text field
*
* @param value - text to enter
* @param fieldName - text field name
*/
@Given("user entered {string} in {string} field")
@When("user enters {string} in {string} field")
public void user_enters_text_into_field(String value, String fieldName) {
formComponent.enterStringIntoTextItem(fieldName, value);
}
/**
* Step verifies the text in text field item
*
* @param fieldName - text field name
* @param expectedValue - expected text of the text field
*/
@Then("verify, that value of text item {string} is {string}")
@Then("text item {string} value is {string}")
public void user_verifies_value_in_text_field(String fieldName, String expectedValue) {
formComponent.verifyTextItemValue(fieldName, expectedValue);
}
}
| 1,770 | Java | .java | dataconsulting-pl/APEX-Low-Test-Framework | 11 | 0 | 13 | 2022-06-28T07:57:50Z | 2023-02-27T10:25:42Z |
CommonSteps.java | /FileExtraction/Java_unseen/dataconsulting-pl_APEX-Low-Test-Framework/src/main/java/pl/dataconsulting/APEX_TAF/stepDefinitions/CommonSteps.java | package pl.dataconsulting.APEX_TAF.stepDefinitions;
import io.cucumber.java.ParameterType;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import org.springframework.beans.factory.annotation.Autowired;
import pl.dataconsulting.APEX_TAF.APEXComponents.BaseComponent;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
public class CommonSteps {
@Autowired
private BaseComponent baseComponent;
/**
* Step waits given time in seconds
* @param wait - wait time in seconds
* @throws InterruptedException
*/
@Then("waiting for {int} second(s)")
public void wait_for_seconds(int wait) throws InterruptedException {
Thread.sleep(wait * 1000L);
}
}
| 735 | Java | .java | dataconsulting-pl/APEX-Low-Test-Framework | 11 | 0 | 13 | 2022-06-28T07:57:50Z | 2023-02-27T10:25:42Z |
ValidationItemSteps.java | /FileExtraction/Java_unseen/dataconsulting-pl_APEX-Low-Test-Framework/src/main/java/pl/dataconsulting/APEX_TAF/stepDefinitions/ValidationItemSteps.java | package pl.dataconsulting.APEX_TAF.stepDefinitions;
import io.cucumber.java.en.Then;
import org.springframework.beans.factory.annotation.Autowired;
import pl.dataconsulting.APEX_TAF.APEXComponents.FormComponent;
public class ValidationItemSteps {
@Autowired
private FormComponent formComponent;
/**
* Step verifies the validation message of the APEX item
* @param expectedValidationMessage -expected validation message
* @param fieldName - name of the field
* @param frameName - name of the iframe (APEX pop-up)
*/
@Then("validation message {string} for {string} field is displayed in {string} pop-up")
public void verify_validation_message(String expectedValidationMessage, String fieldName, String frameName) {
formComponent.verifyValidationMessage(frameName, fieldName, expectedValidationMessage);
}
/**
* Step verifies the validation message of the APEX item
* @param expectedValidationMessage -expected validation message
* @param fieldName - name of the field
*/
@Then("validation message {string} for {string} field is displayed")
public void verify_validation_message(String expectedValidationMessage, String fieldName) {
formComponent.verifyValidationMessage(fieldName, expectedValidationMessage);
}
}
| 1,319 | Java | .java | dataconsulting-pl/APEX-Low-Test-Framework | 11 | 0 | 13 | 2022-06-28T07:57:50Z | 2023-02-27T10:25:42Z |
InteractiveReportSteps.java | /FileExtraction/Java_unseen/dataconsulting-pl_APEX-Low-Test-Framework/src/main/java/pl/dataconsulting/APEX_TAF/stepDefinitions/InteractiveReportSteps.java | package pl.dataconsulting.APEX_TAF.stepDefinitions;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import org.springframework.beans.factory.annotation.Autowired;
import pl.dataconsulting.APEX_TAF.APEXComponents.BaseComponent;
import pl.dataconsulting.APEX_TAF.APEXComponents.IRComponent;
import java.util.List;
import java.util.Map;
public class InteractiveReportSteps extends BaseComponent {
@Autowired
private IRComponent irComponent;
/**
* Step sets the filter on Interactive Report component
* @param IRName - name of Interactive Report component
* @param dataTable - table that present IR table in format:
* | Header 1 | Header 2 |
* | filter value | filter value |
*/
@Given("{string} IR Filter is set on columns:")
@Then("set {string} IR Filter on columns:")
public void set_IR_Filter(String IRName, io.cucumber.datatable.DataTable dataTable) {
List<Map<String, String>> rows = dataTable.asMaps(String.class, String.class);
irComponent.setMainIRGFilter(IRName, rows);
}
/**
* Step sets the filter on Interactive Report component and verify if at least one record exists
* @param IRName - name of Interactive Report component
* @param dataTable - table that present IR table in format:
* | Header 1 | Header 2 |
* | filter value | filter value |
*/
@Then("at least one record can be found in {string} IR by:")
public void set_filter_and_verify_at_least_one_record_exists_in_IG(String IRName, io.cucumber.datatable.DataTable dataTable) {
List<Map<String, String>> rows = dataTable.asMaps(String.class, String.class);
irComponent.setMainIRGFilter(IRName, rows);
irComponent.verifyAtLeastOneRowExists(IRName);
}
/**
* Step verifies on Interactive Report component if at least one record exists
* @param IRName - name of Interactive Report component
*/
@Then("at least one record can be found in {string} IR")
public void verify_at_least_one_record_exists_in_IG(String IRName) {
irComponent.verifyAtLeastOneRowExists(IRName);
}
/**
* Step compares the data in IR
* @param IRName - name of Interactive Report component
* @param rowIdx - row number to be verified
* @param dataTable - table that present IR table in format:
* | Header 1 | Header 2 |
* | filter value | filter value |
*/
@Then("in {string} IR, data starting from {int} row match table below:")
public void compare_data_ig(String IRName, Integer rowIdx, io.cucumber.datatable.DataTable dataTable) {
List<Map<String, String>> rows = dataTable.asMaps(String.class, String.class);
irComponent.compareMainIRValues(IRName, rows, rowIdx);
}
}
| 2,907 | Java | .java | dataconsulting-pl/APEX-Low-Test-Framework | 11 | 0 | 13 | 2022-06-28T07:57:50Z | 2023-02-27T10:25:42Z |
MenuItemSteps.java | /FileExtraction/Java_unseen/dataconsulting-pl_APEX-Low-Test-Framework/src/main/java/pl/dataconsulting/APEX_TAF/stepDefinitions/MenuItemSteps.java | package pl.dataconsulting.APEX_TAF.stepDefinitions;
import io.cucumber.java.ParameterType;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import org.springframework.beans.factory.annotation.Autowired;
import pl.dataconsulting.APEX_TAF.APEXComponents.MenuComponent;
import java.util.Arrays;
import java.util.List;
public class MenuItemSteps {
@Autowired
private MenuComponent menuComponent;
/**
* Step navigates to the menu option.
*
* @param options - menu option to be selected In case navigation should be done to some sub-menu please use -> as delimiter.
* For exampele Administration->Access Control->Settings
*/
@When("user navigates to {listOfMenuElements} page")
public void user_navigate_to_menu(List<String> options) {
menuComponent.navigateToMenu(options);
}
/**
* Step verifies, if menu option is selected.
*
* @param options - menu option to be verified. In case verification should be performed on some sub-menu please use -> as delimiter.
* For exampele Administration->Access Control->Settings
*/
@Then("verify, that menu option {listOfMenuElements} is selected")
public void verify_menu_element_selected(List<String> options) {
menuComponent.verifyMenuOption(options);
}
}
| 1,354 | Java | .java | dataconsulting-pl/APEX-Low-Test-Framework | 11 | 0 | 13 | 2022-06-28T07:57:50Z | 2023-02-27T10:25:42Z |
LoginPageSteps.java | /FileExtraction/Java_unseen/dataconsulting-pl_APEX-Low-Test-Framework/src/main/java/pl/dataconsulting/APEX_TAF/stepDefinitions/LoginPageSteps.java | package pl.dataconsulting.APEX_TAF.stepDefinitions;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import org.springframework.beans.factory.annotation.Autowired;
import pl.dataconsulting.APEX_TAF.APEXComponents.BaseComponent;
public class LoginPageSteps {
@Autowired
private BaseComponent baseComponent;
/**
* Step accesses the given url
* @param url - url to access
*/
@Given("the user access the {string} url")
public void user_access_url(String url) {
baseComponent.navigateToUrl(url);
}
/**
* Step switches content to iframe for example APEX pop-up
* @param frameName - iframe name
*/
@Given("frame/pop-up {string} is visible")
@Then("frame/pop-up {string} has been opened")
public void switch_to_frame(String frameName){
baseComponent.switchToFrame(frameName);
}
/**
* Step switches content back to main frame
*/
@Given("main frame/page is visible")
@Then("a main frame/page is again active")
public void switch_to_main_frame(){
baseComponent.switchToMainFrame();
}
}
| 1,130 | Java | .java | dataconsulting-pl/APEX-Low-Test-Framework | 11 | 0 | 13 | 2022-06-28T07:57:50Z | 2023-02-27T10:25:42Z |
SwitchItemSteps.java | /FileExtraction/Java_unseen/dataconsulting-pl_APEX-Low-Test-Framework/src/main/java/pl/dataconsulting/APEX_TAF/stepDefinitions/SwitchItemSteps.java | package pl.dataconsulting.APEX_TAF.stepDefinitions;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import org.springframework.beans.factory.annotation.Autowired;
import pl.dataconsulting.APEX_TAF.APEXComponents.SwitchItemComponent;
public class SwitchItemSteps {
@Autowired
private SwitchItemComponent switchItemComponent;
/**
* Step switches on the switch item
* @param switchName - name of the switch item element
* @param frameTitle - frame/pop-up name
*/
@Given("user switched on the {string} switch item on {string} pop-up")
@When("user switch on the {string} switch item on {string} pop-up")
public void user_sets_on_switch(String switchName, String frameTitle) {
switchItemComponent.switchItemOn(switchName,frameTitle);
}
/**
* Step switches on the switch item
* @param switchName - name of the switch item element
*/
@Given("user switched on the {string} switch item")
@When("user switch on the {string} switch item")
public void user_sets_on_switch(String switchName) {
switchItemComponent.switchItemOn(switchName);
}
/**
* Step switches off the switch item
* @param switchName - name of the switch item element
* @param frameTitle - frame/pop-up name
*/
@Given("user switched off the {string} switch item on {string} pop-up")
@When("user switch off the {string} switch item on {string} pop-up")
public void user_sets_off_switch(String switchName, String frameTitle) {
switchItemComponent.switchItemOff(switchName,frameTitle);
}
/**
* Step switches off the switch item
* @param switchName - name of the switch item element
*/
@Given("user switched off the {string} switch item")
@When("user switch off the {string} switch item")
public void user_sets_ff_switch(String switchName) {
switchItemComponent.switchItemOff(switchName);
}
/**
* Step verifies, if given switch item is on
* @param switchName - name of the switch item element
*/
@Then("verify, that switch item {string} is on")
public void verify_switch_item_on(String switchName) {
switchItemComponent.verifySwitchItem(switchName,true);
}
/**
* Step verifies, if given switch item is off
* @param switchName - name of the switch item element
*/
@Then("verify, that switch item {string} is off")
public void verify_switch_item_off(String switchName) {
switchItemComponent.verifySwitchItem(switchName, false);
}
}
| 2,613 | Java | .java | dataconsulting-pl/APEX-Low-Test-Framework | 11 | 0 | 13 | 2022-06-28T07:57:50Z | 2023-02-27T10:25:42Z |
CustomParameters.java | /FileExtraction/Java_unseen/dataconsulting-pl_APEX-Low-Test-Framework/src/main/java/pl/dataconsulting/APEX_TAF/stepDefinitions/common/CustomParameters.java | package pl.dataconsulting.APEX_TAF.stepDefinitions.common;
import com.google.common.base.CharMatcher;
import io.cucumber.java.ParameterType;
import java.util.Arrays;
import java.util.List;
public class CustomParameters {
@ParameterType("(?:[^,]*)(?:,\\s?[^,]*)*")
public List<String> listOfStrings(String arg) {
String argTrimmed = CharMatcher.is('\'').trimFrom(arg);
return Arrays.asList(argTrimmed.split(",\\s?"));
}
@ParameterType("(?:[^,]*)(?:->\\s?[^,]*)*")
public List<String> listOfMenuElements(String arg) {
String argTrimmed = CharMatcher.is('\'').trimFrom(arg);
return Arrays.asList(argTrimmed.split("->\\s?"));
}
}
| 690 | Java | .java | dataconsulting-pl/APEX-Low-Test-Framework | 11 | 0 | 13 | 2022-06-28T07:57:50Z | 2023-02-27T10:25:42Z |
Hooks.java | /FileExtraction/Java_unseen/dataconsulting-pl_APEX-Low-Test-Framework/src/main/java/pl/dataconsulting/APEX_TAF/stepDefinitions/common/Hooks.java | package pl.dataconsulting.APEX_TAF.stepDefinitions.common;
import io.cucumber.java.After;
import io.cucumber.java.AfterStep;
import io.cucumber.java.Scenario;
import org.openqa.selenium.WebDriver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Lazy;
import pl.dataconsulting.APEX_TAF.framework.service.ScreenShotService;
import java.sql.Timestamp;
public class Hooks {
@Lazy
@Autowired
private ScreenShotService screenShotService;
@Lazy
@Autowired
private ApplicationContext applicationContext;
@AfterStep
public void captureExceptionImage(Scenario scenario) {
if (scenario.isFailed()) {
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
String timeMilliseconds = Long.toString(timestamp.getTime());
scenario.attach(this.screenShotService.getScreenshot(), "image/png", timeMilliseconds);
}
}
@After
public void tearDown() {
this.applicationContext.getBean(WebDriver.class).quit();
}
}
| 1,133 | Java | .java | dataconsulting-pl/APEX-Low-Test-Framework | 11 | 0 | 13 | 2022-06-28T07:57:50Z | 2023-02-27T10:25:42Z |
DriverScopeConfig.java | /FileExtraction/Java_unseen/dataconsulting-pl_APEX-Low-Test-Framework/src/main/java/pl/dataconsulting/APEX_TAF/framework/scope/DriverScopeConfig.java | package pl.dataconsulting.APEX_TAF.framework.scope;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class DriverScopeConfig {
@Bean
public static BeanFactoryPostProcessor beanFactoryPostProcessor(){
return new DriverScopePostProcessor();
}
}
| 426 | Java | .java | dataconsulting-pl/APEX-Low-Test-Framework | 11 | 0 | 13 | 2022-06-28T07:57:50Z | 2023-02-27T10:25:42Z |
DriverScope.java | /FileExtraction/Java_unseen/dataconsulting-pl_APEX-Low-Test-Framework/src/main/java/pl/dataconsulting/APEX_TAF/framework/scope/DriverScope.java | package pl.dataconsulting.APEX_TAF.framework.scope;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.remote.SessionId;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.context.support.SimpleThreadScope;
import java.util.Objects;
public class DriverScope extends SimpleThreadScope {
@Override
public Object get(String name, ObjectFactory<?> objectFactory) {
Object o = super.get(name,objectFactory);
SessionId sessionId = ((RemoteWebDriver) o).getSessionId();
if (Objects.isNull(sessionId)){
super.remove(name);
o = super.get(name,objectFactory);
}
return o;
}
@Override
public void registerDestructionCallback(String name, Runnable callback) {
}
}
| 806 | Java | .java | dataconsulting-pl/APEX-Low-Test-Framework | 11 | 0 | 13 | 2022-06-28T07:57:50Z | 2023-02-27T10:25:42Z |
DriverScopePostProcessor.java | /FileExtraction/Java_unseen/dataconsulting-pl_APEX-Low-Test-Framework/src/main/java/pl/dataconsulting/APEX_TAF/framework/scope/DriverScopePostProcessor.java | package pl.dataconsulting.APEX_TAF.framework.scope;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
public class DriverScopePostProcessor implements BeanFactoryPostProcessor
{
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
configurableListableBeanFactory.registerScope("driverscope",new DriverScope());
}
}
| 572 | Java | .java | dataconsulting-pl/APEX-Low-Test-Framework | 11 | 0 | 13 | 2022-06-28T07:57:50Z | 2023-02-27T10:25:42Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.