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
ForgeInstallFragment.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/fragments/ForgeInstallFragment.java
package net.kdt.pojavlaunch.fragments; import android.content.Context; import android.content.Intent; import android.view.LayoutInflater; import android.widget.ExpandableListAdapter; import androidx.annotation.NonNull; import net.kdt.pojavlaunch.JavaGUILauncherActivity; import net.kdt.pojavlaunch.R; import net.kdt.pojavlaunch.Tools; import net.kdt.pojavlaunch.modloaders.ForgeDownloadTask; import net.kdt.pojavlaunch.modloaders.ForgeUtils; import net.kdt.pojavlaunch.modloaders.ForgeVersionListAdapter; import net.kdt.pojavlaunch.modloaders.ModloaderListenerProxy; import java.io.File; import java.io.IOException; import java.util.List; public class ForgeInstallFragment extends ModVersionListFragment<List<String>> { public static final String TAG = "ForgeInstallFragment"; private static ModloaderListenerProxy sTaskProxy; @Override public void onAttach(@NonNull Context context) { super.onAttach(context); } @Override public int getTitleText() { return R.string.forge_dl_select_version; } @Override public int getNoDataMsg() { return R.string.forge_dl_no_installer; } @Override public ModloaderListenerProxy getTaskProxy() { return sTaskProxy; } @Override public void setTaskProxy(ModloaderListenerProxy proxy) { sTaskProxy = proxy; } @Override public List<String> loadVersionList() throws IOException { return ForgeUtils.downloadForgeVersions(); } @Override public ExpandableListAdapter createAdapter(List<String> versionList, LayoutInflater layoutInflater) { return new ForgeVersionListAdapter(versionList, layoutInflater); } @Override public Runnable createDownloadTask(Object selectedVersion, ModloaderListenerProxy listenerProxy) { return new ForgeDownloadTask(listenerProxy, (String) selectedVersion); } @Override public void onDownloadFinished(Context context, File downloadedFile) { Intent modInstallerStartIntent = new Intent(context, JavaGUILauncherActivity.class); ForgeUtils.addAutoInstallArgs(modInstallerStartIntent, downloadedFile, true); context.startActivity(modInstallerStartIntent); } }
2,228
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
CropperView.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/imgcropper/CropperView.java
package net.kdt.pojavlaunch.imgcropper; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.RectF; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import androidx.annotation.CallSuper; import androidx.annotation.Nullable; import net.kdt.pojavlaunch.Tools; import top.defaults.checkerboarddrawable.CheckerboardDrawable; public class CropperView extends View { private final RectF mSelectionHighlight = new RectF(); protected final Rect mSelectionRect = new Rect(); public boolean horizontalLock, verticalLock; private float mLastTouchX, mLastTouchY; private float mHighlightThickness; private float mLastDistance = -1f; private float mSelectionPadding; private int mLastTrackedPointer; private Paint mSelectionPaint; private CropperBehaviour mCropperBehaviour = CropperBehaviour.DUMMY; public CropperView(Context context) { super(context); init(); } public CropperView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); init(); } public CropperView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } protected void init() { setBackground(new CheckerboardDrawable.Builder().build()); mSelectionPadding = Tools.dpToPx(24); mHighlightThickness = Tools.dpToPx(3); mSelectionPaint = new Paint(); mSelectionPaint.setColor(Color.DKGRAY); mSelectionPaint.setStrokeWidth(mHighlightThickness); // Divide the thickness by 2 since we will be needing only half of it for // rect highlight correction. mHighlightThickness /= 2; mSelectionPaint.setStyle(Paint.Style.STROKE); } @Override public boolean dispatchGenericMotionEvent(MotionEvent event) { float x1 = event.getX(0); float y1 = event.getY(0); if(event.getPointerCount() > 1) { // More than 1 pointer = pinching // Compute the distance and zoom the image with it float x2 = event.getX(1); float y2 = event.getY(1); float deltaXSquared = (x2 - x1) * (x2 - x1); float deltaYSquared = (y2 - y1) * (y2 - y1); float distance = (float) Math.sqrt(deltaXSquared + deltaYSquared); if(mLastDistance != -1) { float distanceDelta = distance - mLastDistance; float multiplier = 0.005f; float midpointX = (x1 + x2) / 2; float midpointY = (y1 + y2) / 2; mCropperBehaviour.zoom(1 + distanceDelta * multiplier, midpointX, midpointY); } mLastDistance = distance; return true; } else { // Reset lastDistance as it's fairly reliable to assume that when // there's less than 2 pointers on the screen, the zoom gesture is over mLastDistance = -1f; } // When not pinching, pan around. Simultaneous panning and zooming proved to be confusing in my testing. // Lots of code there to allow seamless finger changing while panning. switch (event.getActionMasked()) { case MotionEvent.ACTION_DOWN: mLastTouchX = x1; mLastTouchY = y1; // Remember the pointer index from the start of the gesture. // We will be tracking it for the rest of the gesture unless it gets released. mLastTrackedPointer = event.getPointerId(0); break; case MotionEvent.ACTION_MOVE: // Fond the pointer we should be tracking int trackedIndex = findPointerIndex(event, mLastTrackedPointer); // By default, we query the X/Y coordinates of pointer index 0. If our tracked // pointer is no longer at index 0 and is still tracked, overwrite the coordinates // with the expected ones if(trackedIndex > 0) { x1 = event.getX(trackedIndex); y1 = event.getY(trackedIndex); } if(trackedIndex != -1) { // If we still track out current pointer, pan the image by the movement delta mCropperBehaviour.pan(x1 - mLastTouchX, y1 - mLastTouchY); } else { // Otherwise, mark the new tracked pointer without panning. mLastTrackedPointer = event.getPointerId(0); } mLastTouchX = x1; mLastTouchY = y1; } return true; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.save(); mCropperBehaviour.drawPreHighlight(canvas); canvas.restore(); canvas.drawRect(mSelectionHighlight, mSelectionPaint); } @SuppressWarnings("ClickableViewAccessibility") // the view is not clickable @Override public boolean onTouchEvent(MotionEvent event) { return dispatchGenericMotionEvent(event); } private int findPointerIndex(MotionEvent event, int id) { for(int i = 0; i < event.getPointerCount(); i++) { if(event.getPointerId(i) == id) return i; } return -1; } @Override protected void onSizeChanged(int w, int h, int oldW, int oldH) { super.onSizeChanged(w, h, oldW, oldH); int lesserDimension = (int)(Math.min(w, h) - mSelectionPadding); // Calculate the corners of the new selection frame. It should always appear at the center of the view. int centerShiftX = (w - lesserDimension) / 2; int centerShiftY = (h - lesserDimension) / 2; mSelectionRect.left = centerShiftX; mSelectionRect.top = centerShiftY; mSelectionRect.right = centerShiftX + lesserDimension; mSelectionRect.bottom = centerShiftY + lesserDimension; mCropperBehaviour.onSelectionRectUpdated(); // Adjust the selection highlight rectangle to be bigger than the selection area // by the highlight thickness, to make sure that the entire inside of the selection highlight // will fit into the image mSelectionHighlight.left = mSelectionRect.left - mHighlightThickness; mSelectionHighlight.top = mSelectionRect.top + mHighlightThickness; mSelectionHighlight.right = mSelectionRect.right + mHighlightThickness; mSelectionHighlight.bottom = mSelectionRect.bottom - mHighlightThickness; } @Override protected void onMeasure(int widthSpec, int heightSpec) { int widthMode = MeasureSpec.getMode(widthSpec), widthSize = MeasureSpec.getSize(widthSpec); int heightMode = MeasureSpec.getMode(heightSpec), heightSize = MeasureSpec.getSize(heightSpec); if (widthMode == MeasureSpec.EXACTLY && heightMode == MeasureSpec.EXACTLY) { // No leeway. Size to spec. setMeasuredDimension(widthSize, heightSize); return; } int biggestAllowedDimension = mCropperBehaviour.getLargestImageSide(); if(widthMode == MeasureSpec.EXACTLY) biggestAllowedDimension = widthSize; if(heightMode == MeasureSpec.EXACTLY) biggestAllowedDimension = heightSize; setMeasuredDimension( pickDesiredDimension(widthMode, widthSize, biggestAllowedDimension), pickDesiredDimension(heightMode, heightSize, biggestAllowedDimension) ); } private int pickDesiredDimension(int mode, int size, int desired) { switch (mode) { case MeasureSpec.EXACTLY: return size; case MeasureSpec.AT_MOST: return Math.min(size, desired); case MeasureSpec.UNSPECIFIED: return desired; } return desired; } public void setCropperBehaviour(CropperBehaviour cropperBehaviour) { this.mCropperBehaviour = cropperBehaviour; cropperBehaviour.onSelectionRectUpdated(); } public void resetTransforms() { mCropperBehaviour.resetTransforms(); } @CallSuper protected void reset() { mLastDistance = -1; } public Bitmap crop(int targetMaxSide) { return mCropperBehaviour.crop(targetMaxSide); } }
8,543
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
CropperBehaviour.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/imgcropper/CropperBehaviour.java
package net.kdt.pojavlaunch.imgcropper; import android.graphics.Bitmap; import android.graphics.Canvas; public interface CropperBehaviour { /** * Get the largest side of the image currently loaded into this CropperBehaviour. * @return the largest side of the loaded image */ int getLargestImageSide(); /** * This method is called by CropperView for the CropperBehaviour to draw its image with all * the transforms applied, It is called before the selection rectangle is drawn. * @param canvas the canvas to draw the image on */ void drawPreHighlight(Canvas canvas); /** * This method is called by CropperView to let the behaviour know that the selection rect * dimensions were updated. */ void onSelectionRectUpdated(); /** * This method is called by CropperView or by the programmer to reset all current transforms * applied to the image loaded within this CropperBehaviour */ void resetTransforms(); /** * Prepares this behaviour for being rendered in CropperView. */ void applyImage(); /** * This method is called by CropperView to pan the image * @param dx pan delta-X * @param dy pan delta-Y */ void pan(float dx, float dy); /** * This method is called by CropperView to zoom the image * @param dz zoom delta-Z * @param originX the X coordinate of a point at which the image should be zoomed * @param originY the Y coordinate of a point at which the image should be zoomed */ void zoom(float dz, float originX, float originY); /** * Crop the image according to current transforms, with the targetMaxSide specifying the * maximum side of the resulting 1:1 bitmap. * @param targetMaxSide the maximum side of the 1:1 bitmap * @return the crop of the behaviour's image */ Bitmap crop(int targetMaxSide); CropperBehaviour DUMMY = new CropperBehaviour() { @Override public int getLargestImageSide() { return 0; } @Override public void drawPreHighlight(Canvas canvas) { } @Override public void onSelectionRectUpdated() { } @Override public void resetTransforms() { } @Override public void applyImage() { } @Override public void pan(float dx, float dy) { } @Override public void zoom(float dz, float originX, float originY) { } @Override public Bitmap crop(int targetMaxSide) { return null; } }; }
2,650
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
BitmapCropBehaviour.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/imgcropper/BitmapCropBehaviour.java
package net.kdt.pojavlaunch.imgcropper; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.Rect; import net.kdt.pojavlaunch.utils.MatrixUtils; public class BitmapCropBehaviour implements CropperBehaviour{ private final Matrix mTranslateInverse = new Matrix(); protected final Matrix mTranslateMatrix = new Matrix(); private final Matrix mPrescaleMatrix = new Matrix(); private final Matrix mImageMatrix = new Matrix(); protected final Matrix mZoomMatrix = new Matrix(); private boolean mTranslateInverseOutdated = true; protected Bitmap mOriginalBitmap; protected CropperView mHostView; public BitmapCropBehaviour(CropperView hostView) { mHostView = hostView; } @Override public void pan(float panX, float panY) { if(mHostView.horizontalLock) panX = 0; if(mHostView.verticalLock) panY = 0; if(panX != 0 || panY != 0) { // Actually translate and refresh only if either of the pan deltas are nonzero mTranslateMatrix.postTranslate(panX, panY); mTranslateInverseOutdated = true; refresh(); } } public void zoom(float zoomLevel, float midpointX, float midpointY) { // Do this to avoid constantly inverting the same matrix on each touch event. if(mTranslateInverseOutdated) { MatrixUtils.inverse(mTranslateMatrix, mTranslateInverse); mTranslateInverseOutdated = false; } float[] zoomCenter = new float[] { midpointX, midpointY }; float[] realZoomCenter = new float[2]; mTranslateInverse.mapPoints(realZoomCenter, 0, zoomCenter, 0, 1); mZoomMatrix.postScale(zoomLevel, zoomLevel, realZoomCenter[0], realZoomCenter[1]); refresh(); } public int getLargestImageSide() { if(mOriginalBitmap == null) return 0; return Math.max(mOriginalBitmap.getWidth(), mOriginalBitmap.getHeight()); } @Override public void drawPreHighlight(Canvas canvas) { canvas.drawBitmap(mOriginalBitmap, mImageMatrix, null); } @Override public void onSelectionRectUpdated() { computeLocalPrescaleMatrix(); } public void applyImage() { mHostView.reset(); computeLocalPrescaleMatrix(); resetTransforms(); refresh(); } public void setBitmap(Bitmap bitmap) { mOriginalBitmap = bitmap; } protected void refresh() { mImageMatrix.set(mPrescaleMatrix); mImageMatrix.postConcat(mZoomMatrix); mImageMatrix.postConcat(mTranslateMatrix); mHostView.invalidate(); } public Bitmap crop(int targetMaxSide) { Matrix imageInverse = new Matrix(); MatrixUtils.inverse(mImageMatrix, imageInverse); // By inverting the matrix we will effectively "divide" our rectangle by it, thus getting // its two points on the surface of the bitmap. Math be cool indeed. Rect targetRect = new Rect(); MatrixUtils.transformRect(mHostView.mSelectionRect, targetRect, imageInverse); // Pick the best dimensions for the crop result, shrinking the target if necessary. int targetWidth, targetHeight; int targetMinDimension = Math.min(targetRect.width(), targetRect.height()); if(targetMaxSide < targetMinDimension) { float ratio = (float) targetMaxSide / targetMinDimension; targetWidth = (int) (targetRect.width() * ratio); targetHeight = (int) (targetRect.height() * ratio); }else { targetWidth = targetRect.width(); targetHeight = targetRect.height(); } Bitmap croppedBitmap = Bitmap.createBitmap( targetWidth, targetHeight, mOriginalBitmap.getConfig() ); // Draw the bitmap on the target. Doing this allows us to not bother with making sure // that targetRect is fully contained within image bounds. Canvas drawCanvas = new Canvas(croppedBitmap); drawCanvas.drawBitmap( mOriginalBitmap, targetRect, new Rect(0, 0, targetWidth, targetHeight), null ); return croppedBitmap; } /** * Computes a prescale matrix. * This matrix basically centers the source image in the selection rect. * Mainly intended for convenience of implementing a "Reset" button. */ protected void computePrescaleMatrix(Matrix inMatrix, int imageWidth, int imageHeight) { if(mOriginalBitmap == null) return; int selectionRectWidth = mHostView.mSelectionRect.width(); int selectionRectHeight = mHostView.mSelectionRect.height(); // A basic "scale to fit while preserving aspect ratio" I have taken from // https://stackoverflow.com/a/23105310 float hRatio = (float)selectionRectWidth / imageWidth ; float vRatio = (float)selectionRectHeight / imageHeight; float ratio = Math.min (hRatio, vRatio); float centerShift_x = (selectionRectWidth - imageWidth*ratio) / 2; float centerShift_y = (selectionRectWidth - imageHeight*ratio) / 2; centerShift_x += mHostView.mSelectionRect.left; centerShift_y += mHostView.mSelectionRect.top; // By doing setScale() we don't have to reset() the matrix beforehand saving us a // JNI transition inMatrix.setScale(ratio, ratio); inMatrix.postTranslate(centerShift_x, centerShift_y); refresh(); } private void computeLocalPrescaleMatrix() { computePrescaleMatrix( mPrescaleMatrix, mOriginalBitmap.getWidth(), mOriginalBitmap.getHeight() ); } public void resetTransforms() { // Don't set the mTranslateInverseOutdated flag to true here as // the inverse of an identity matrix (aka the matrix we're setting ours to on reset()) // is an identity matrix, which technically means that mTranslateInverse gets up-to-date there mTranslateMatrix.reset(); mTranslateInverse.reset(); mZoomMatrix.reset(); refresh(); } }
6,283
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
RegionDecoderCropBehaviour.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/imgcropper/RegionDecoderCropBehaviour.java
package net.kdt.pojavlaunch.imgcropper; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.BitmapRegionDecoder; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.Rect; import android.graphics.RectF; import android.os.Handler; import android.os.Looper; import net.kdt.pojavlaunch.PojavApplication; import net.kdt.pojavlaunch.modloaders.modpacks.SelfReferencingFuture; import net.kdt.pojavlaunch.utils.MatrixUtils; import java.util.concurrent.Future; public class RegionDecoderCropBehaviour extends BitmapCropBehaviour { private BitmapRegionDecoder mBitmapDecoder; private Bitmap mOverlayBitmap; private final RectF mOverlayDst = new RectF(0, 0, 0, 0); private boolean mRequiresOverlayBitmap; private final Matrix mDecoderPrescaleMatrix = new Matrix(); private final Handler mHiresLoadHandler = new Handler(Looper.getMainLooper()); private Future<?> mDecodeFuture; private final Runnable mHiresLoadRunnable = ()->{ RectF subsectionRect = new RectF(0,0, mHostView.getWidth(), mHostView.getHeight()); RectF overlayDst = new RectF(); discardDecodeFuture(); mDecodeFuture = new SelfReferencingFuture(myFuture -> { Bitmap overlayBitmap = decodeRegionBitmap(overlayDst, subsectionRect); mHiresLoadHandler.post(()->{ if(myFuture.isCancelled()) return; mOverlayBitmap = overlayBitmap; mOverlayDst.set(overlayDst); mHostView.invalidate(); }); }).startOnExecutor(PojavApplication.sExecutorService); }; /** * Decode a region from this Bitmap based on a subsection in the View coordinate space. * @param targetDrawRect an output Rect. This Rect is the position at which the region must * be rendered within subsectionRect. * @param subsectionRect the subsection in View coordinate space. Note that this Rect is modified * by this function and shouldn't be re-used. * @return null if the resulting region is bigger than the original image * null if the resulting region is completely out of the original image bounds * null if the resulting region is smaller than 16x16 pixels * null if a region decoding error has occurred * the resulting Bitmap region otherwise. */ private Bitmap decodeRegionBitmap(RectF targetDrawRect, RectF subsectionRect) { RectF decoderRect = new RectF(0, 0, mBitmapDecoder.getWidth(), mBitmapDecoder.getHeight()); Matrix matrix = createDecoderImageMatrix(); Matrix inverse = new Matrix(); MatrixUtils.inverse(matrix, inverse); MatrixUtils.transformRect(subsectionRect, inverse); // If our current sub-section is bigger than the decoder rect, skip. // We do this to avoid unnecessarily loading the image at full resolution. if(subsectionRect.width() > decoderRect.width() || subsectionRect.height() > decoderRect.height()) return null; // If our current sub-section doesn't even intersect the decoder rect, we won't even // be able to create an overlay. So, skip. if(!subsectionRect.setIntersect(decoderRect, subsectionRect)) return null; // In my testing, decoding a region smaller than that breaks the current region decoder instance. // So, if it is smaller, skip. if(subsectionRect.width() < 16 || subsectionRect.height() < 16) return null; // We can't really create a floating-point subsection from a bitmap, so convert the intersected // rectangle that we want to get from the decoder into an integer Rect. Rect bitmapRegionRect = new Rect( (int) subsectionRect.left, (int) subsectionRect.top, (int) subsectionRect.right, (int) subsectionRect.bottom ); MatrixUtils.transformRect(subsectionRect, matrix); targetDrawRect.set(subsectionRect); return mBitmapDecoder.decodeRegion(bitmapRegionRect, null); } private void discardDecodeFuture() { if(mDecodeFuture != null) { // Putting false here as I don't know how BitmapRegionDecoder will behave when interrupted mDecodeFuture.cancel(false); } } public RegionDecoderCropBehaviour(CropperView hostView) { super(hostView); } public void setRegionDecoder(BitmapRegionDecoder bitmapRegionDecoder) { mBitmapDecoder = bitmapRegionDecoder; } @Override public int getLargestImageSide() { if(mBitmapDecoder == null) return 0; return Math.max(mBitmapDecoder.getWidth(), mBitmapDecoder.getHeight()); } @Override public void drawPreHighlight(Canvas canvas) { if (mOverlayBitmap != null) { canvas.drawBitmap(mOverlayBitmap, null, mOverlayDst, null); } else { super.drawPreHighlight(canvas); } } @Override protected void refresh() { if(mOverlayBitmap != null) { mOverlayBitmap.recycle(); mOverlayBitmap = null; } mHiresLoadHandler.removeCallbacks(mHiresLoadRunnable); discardDecodeFuture(); if(mRequiresOverlayBitmap) { mHiresLoadHandler.postDelayed(mHiresLoadRunnable, 200); } super.refresh(); } @Override public void applyImage() { createScaledSourceBitmap(); computeDecoderPrescaleMatrix(); super.applyImage(); } @Override public void onSelectionRectUpdated() { createScaledSourceBitmap(); computeDecoderPrescaleMatrix(); super.onSelectionRectUpdated(); } /** * Load a scaled down version of the Bitmap that will be used for zooming and panning in the view. * BitmapCropBehaviour will base its prescale matrix off of this Bitmap. */ private void createScaledSourceBitmap() { if(mBitmapDecoder == null) return; int width = mHostView.getWidth(); int height = mHostView.getHeight(); int imageWidth = mBitmapDecoder.getWidth(); int imageHeight = mBitmapDecoder.getHeight(); float hRatio = (float)width / imageWidth ; float vRatio = (float)height / imageHeight; float ratio = Math.max(hRatio, vRatio); BitmapFactory.Options options = new BitmapFactory.Options(); if(ratio < 1 && ratio != 0) { ratio = 1 / ratio; options.inSampleSize = (int)Math.floor(ratio); mRequiresOverlayBitmap = true; }else { mRequiresOverlayBitmap = false; } mOriginalBitmap = mBitmapDecoder.decodeRegion( new Rect(0, 0, imageWidth, imageHeight), options ); } /** * Compute the prescale matrix for the image bounds of the BitmapRegionDecoder. Used to * align the transforms done on the scaled source bitmap with the bitmap region decoder. */ private void computeDecoderPrescaleMatrix() { computePrescaleMatrix( mDecoderPrescaleMatrix, mBitmapDecoder.getWidth(), mBitmapDecoder.getHeight() ); } /** * Create a Matrix that can be used to transform points from the bitmap coordinate space into the * View coordinate space. */ private Matrix createDecoderImageMatrix() { Matrix decoderImageMatrix = new Matrix(mDecoderPrescaleMatrix); decoderImageMatrix.postConcat(mZoomMatrix); decoderImageMatrix.postConcat(mTranslateMatrix); return decoderImageMatrix; } @Override public Bitmap crop(int targetMaxSide) { RectF drawRect = new RectF(); Bitmap regionBitmap = decodeRegionBitmap(drawRect, new RectF(mHostView.mSelectionRect)); if(regionBitmap == null) { // If we can't decode a hi-res region, just crop out of the low-res preview. Yes, this will in fact // cause the image to be low res, but we can't really avoid that in this case. return super.crop(targetMaxSide); } int targetDimension = targetMaxSide; // Use Math.max here as the region bitmap may not always be a square, and we need to make it one without // losing detail. int regionBitmapSide = Math.max(regionBitmap.getWidth(), regionBitmap.getHeight()); if(regionBitmapSide < targetDimension) targetDimension = regionBitmapSide; // The drawRect will be a subsection of the selectionRect, so we will need to scale it // down in order to fit it into the targetDimension x targetDimension bitmap // that we will return. float scaleRatio = (float)targetDimension / mHostView.mSelectionRect.width(); Matrix drawRectScaleMatrix = new Matrix(); drawRectScaleMatrix.setScale(scaleRatio, scaleRatio); MatrixUtils.transformRect(drawRect, drawRectScaleMatrix); Bitmap returnBitmap = Bitmap.createBitmap(targetDimension, targetDimension, regionBitmap.getConfig()); Canvas canvas = new Canvas(returnBitmap); canvas.drawBitmap(regionBitmap, null, drawRect, null); return returnBitmap; } }
9,338
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
ProgressService.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/services/ProgressService.java
package net.kdt.pojavlaunch.services; import android.annotation.SuppressLint; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.os.Build; import android.os.IBinder; import android.os.Process; import android.util.Log; import androidx.annotation.Nullable; import androidx.core.app.NotificationCompat; import androidx.core.app.NotificationManagerCompat; import androidx.core.content.ContextCompat; import net.kdt.pojavlaunch.R; import net.kdt.pojavlaunch.Tools; import net.kdt.pojavlaunch.progresskeeper.ProgressKeeper; import net.kdt.pojavlaunch.progresskeeper.TaskCountListener; import net.kdt.pojavlaunch.utils.NotificationUtils; /** * Lazy service which allows the process not to get killed. * Can be created from context, can be killed statically */ public class ProgressService extends Service implements TaskCountListener { private NotificationManagerCompat notificationManagerCompat; /** Simple wrapper to start the service */ public static void startService(Context context){ Intent intent = new Intent(context, ProgressService.class); ContextCompat.startForegroundService(context, intent); } private NotificationCompat.Builder mNotificationBuilder; @Override public void onCreate() { Tools.buildNotificationChannel(getApplicationContext()); notificationManagerCompat = NotificationManagerCompat.from(getApplicationContext()); Intent killIntent = new Intent(getApplicationContext(), ProgressService.class); killIntent.putExtra("kill", true); PendingIntent pendingKillIntent = PendingIntent.getService(this, NotificationUtils.PENDINGINTENT_CODE_KILL_PROGRESS_SERVICE , killIntent, Build.VERSION.SDK_INT >=23 ? PendingIntent.FLAG_IMMUTABLE : 0); mNotificationBuilder = new NotificationCompat.Builder(this, "channel_id") .setContentTitle(getString(R.string.lazy_service_default_title)) .addAction(android.R.drawable.ic_menu_close_clear_cancel, getString(R.string.notification_terminate), pendingKillIntent) .setSmallIcon(R.drawable.notif_icon) .setNotificationSilent(); } @SuppressLint("StringFormatInvalid") @Override public int onStartCommand(Intent intent, int flags, int startId) { if(intent != null) { if(intent.getBooleanExtra("kill", false)) { stopSelf(); // otherwise Android tries to restart the service since it "crashed" Process.killProcess(Process.myPid()); return START_NOT_STICKY; } } Log.d("ProgressService", "Started!"); mNotificationBuilder.setContentText(getString(R.string.progresslayout_tasks_in_progress, ProgressKeeper.getTaskCount())); startForeground(NotificationUtils.NOTIFICATION_ID_PROGRESS_SERVICE, mNotificationBuilder.build()); if(ProgressKeeper.getTaskCount() < 1) stopSelf(); else ProgressKeeper.addTaskCountListener(this, false); return START_NOT_STICKY; } @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public void onDestroy() { ProgressKeeper.removeTaskCountListener(this); } @Override public void onUpdateTaskCount(int taskCount) { Tools.MAIN_HANDLER.post(()->{ if(taskCount > 0) { mNotificationBuilder.setContentText(getString(R.string.progresslayout_tasks_in_progress, taskCount)); notificationManagerCompat.notify(1, mNotificationBuilder.build()); }else{ stopSelf(); } }); } }
3,747
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
ProgressServiceKeeper.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/services/ProgressServiceKeeper.java
package net.kdt.pojavlaunch.services; import android.content.Context; import net.kdt.pojavlaunch.progresskeeper.TaskCountListener; public class ProgressServiceKeeper implements TaskCountListener { private final Context context; public ProgressServiceKeeper(Context ctx) { this.context = ctx; } @Override public void onUpdateTaskCount(int taskCount) { if(taskCount > 0) ProgressService.startService(context); } }
456
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
GameService.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/services/GameService.java
package net.kdt.pojavlaunch.services; import android.app.PendingIntent; import android.app.Service; import android.content.Intent; import android.os.Binder; import android.os.Build; import android.os.IBinder; import android.os.Process; import androidx.annotation.Nullable; import androidx.core.app.NotificationCompat; import net.kdt.pojavlaunch.R; import net.kdt.pojavlaunch.Tools; import net.kdt.pojavlaunch.utils.NotificationUtils; import java.lang.ref.WeakReference; public class GameService extends Service { private static final WeakReference<Service> sGameService = new WeakReference<>(null); private final LocalBinder mLocalBinder = new LocalBinder(); @Override public void onCreate() { Tools.buildNotificationChannel(getApplicationContext()); } @Override public int onStartCommand(Intent intent, int flags, int startId) { if(intent != null && intent.getBooleanExtra("kill", false)) { stopSelf(); Process.killProcess(Process.myPid()); return START_NOT_STICKY; } Intent killIntent = new Intent(getApplicationContext(), GameService.class); killIntent.putExtra("kill", true); PendingIntent pendingKillIntent = PendingIntent.getService(this, NotificationUtils.PENDINGINTENT_CODE_KILL_GAME_SERVICE , killIntent, Build.VERSION.SDK_INT >=23 ? PendingIntent.FLAG_IMMUTABLE : 0); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "channel_id") .setContentTitle(getString(R.string.lazy_service_default_title)) .setContentText(getString(R.string.notification_game_runs)) .addAction(android.R.drawable.ic_menu_close_clear_cancel, getString(R.string.notification_terminate), pendingKillIntent) .setSmallIcon(R.drawable.notif_icon) .setNotificationSilent(); startForeground(NotificationUtils.NOTIFICATION_ID_GAME_SERVICE, notificationBuilder.build()); return START_NOT_STICKY; // non-sticky so android wont try restarting the game after the user uses the "Quit" button } @Override public void onTaskRemoved(Intent rootIntent) { //At this point in time only the game runs and the user poofed the window, time to die stopSelf(); Process.killProcess(Process.myPid()); } @Nullable @Override public IBinder onBind(Intent intent) { return mLocalBinder; } public static class LocalBinder extends Binder { public boolean isActive; } }
2,580
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
DownloaderProgressWrapper.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/progresskeeper/DownloaderProgressWrapper.java
package net.kdt.pojavlaunch.progresskeeper; import static net.kdt.pojavlaunch.Tools.BYTE_TO_MB; import net.kdt.pojavlaunch.Tools; public class DownloaderProgressWrapper implements Tools.DownloaderFeedback { private final int mProgressString; private final String mProgressRecord; public String extraString = null; /** * A simple wrapper to send the downloader progress to ProgressKeeper * @param progressString the string that will be used in the progress reporter * @param progressRecord the record for ProgressKeeper */ public DownloaderProgressWrapper(int progressString, String progressRecord) { this.mProgressString = progressString; this.mProgressRecord = progressRecord; } @Override public void updateProgress(int curr, int max) { Object[] va; if(extraString != null) { va = new Object[3]; va[0] = extraString; va[1] = curr/BYTE_TO_MB; va[2] = max/BYTE_TO_MB; } else { va = new Object[2]; va[0] = curr/BYTE_TO_MB; va[1] = max/BYTE_TO_MB; } // the allocations are fine because thats how java implements variadic arguments in bytecode: an array of whatever ProgressKeeper.submitProgress(mProgressRecord, (int) Math.max((float)curr/max*100,0), mProgressString, va); } }
1,393
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
ProgressListener.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/progresskeeper/ProgressListener.java
package net.kdt.pojavlaunch.progresskeeper; public interface ProgressListener { void onProgressStarted(); void onProgressUpdated(int progress, int resid, Object... va); void onProgressEnded(); }
208
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
ProgressKeeper.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/progresskeeper/ProgressKeeper.java
package net.kdt.pojavlaunch.progresskeeper; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class ProgressKeeper { private static final HashMap<String, List<ProgressListener>> sProgressListeners = new HashMap<>(); private static final HashMap<String, ProgressState> sProgressStates = new HashMap<>(); private static final List<TaskCountListener> sTaskCountListeners = new ArrayList<>(); public static synchronized void submitProgress(String progressRecord, int progress, int resid, Object... va) { ProgressState progressState = sProgressStates.get(progressRecord); boolean shouldCallStarted = progressState == null; boolean shouldCallEnded = resid == -1 && progress == -1; if(shouldCallEnded) { shouldCallStarted = false; sProgressStates.remove(progressRecord); updateTaskCount(); }else if(shouldCallStarted){ sProgressStates.put(progressRecord, (progressState = new ProgressState())); updateTaskCount(); } if(progressState != null) { progressState.progress = progress; progressState.resid = resid; progressState.varArg = va; } List<ProgressListener> progressListeners = sProgressListeners.get(progressRecord); if(progressListeners != null) for(ProgressListener listener : progressListeners) { if(shouldCallStarted) listener.onProgressStarted(); else if(shouldCallEnded) listener.onProgressEnded(); else listener.onProgressUpdated(progress, resid, va); } } private static synchronized void updateTaskCount() { int count = sProgressStates.size(); for(TaskCountListener listener : sTaskCountListeners) { listener.onUpdateTaskCount(count); } } public static synchronized void addListener(String progressRecord, ProgressListener listener) { ProgressState state = sProgressStates.get(progressRecord); if(state != null && (state.resid != -1 || state.progress != -1)) { listener.onProgressStarted(); listener.onProgressUpdated(state.progress, state.resid, state.varArg); }else{ listener.onProgressEnded(); } List<ProgressListener> listenerWeakReferenceList = sProgressListeners.get(progressRecord); if(listenerWeakReferenceList == null) sProgressListeners.put(progressRecord, (listenerWeakReferenceList = new ArrayList<>())); listenerWeakReferenceList.add(listener); } public static synchronized void removeListener(String progressRecord, ProgressListener listener) { List<ProgressListener> listenerWeakReferenceList = sProgressListeners.get(progressRecord); if(listenerWeakReferenceList != null) listenerWeakReferenceList.remove(listener); } public static synchronized void addTaskCountListener(TaskCountListener listener) { listener.onUpdateTaskCount(sProgressStates.size()); if(!sTaskCountListeners.contains(listener)) sTaskCountListeners.add(listener); } public static synchronized void addTaskCountListener(TaskCountListener listener, boolean runUpdate) { if(runUpdate) listener.onUpdateTaskCount(sProgressStates.size()); if(!sTaskCountListeners.contains(listener)) sTaskCountListeners.add(listener); } public static synchronized void removeTaskCountListener(TaskCountListener listener) { sTaskCountListeners.remove(listener); } /** * Waits until all tasks are done and runs the runnable, or if there were no pending process remaining * The runnable runs from the thread that updated the task count last, and it might be the UI thread, * so don't put long running processes in it * @param runnable the runnable to run when no tasks are remaining */ public static void waitUntilDone(final Runnable runnable) { // If we do it the other way the listener would be removed before it was added, which will cause a listener object leak if(getTaskCount() == 0) { runnable.run(); return; } TaskCountListener listener = new TaskCountListener() { @Override public void onUpdateTaskCount(int taskCount) { if(taskCount == 0) { runnable.run(); } removeTaskCountListener(this); } }; addTaskCountListener(listener); } public static synchronized int getTaskCount() { return sProgressStates.size(); } public static boolean hasOngoingTasks() { return getTaskCount() > 0; } }
4,758
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
ProgressState.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/progresskeeper/ProgressState.java
package net.kdt.pojavlaunch.progresskeeper; public class ProgressState { int progress; int resid; Object[] varArg; }
130
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
TaskCountListener.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/progresskeeper/TaskCountListener.java
package net.kdt.pojavlaunch.progresskeeper; public interface TaskCountListener { void onUpdateTaskCount(int taskCount); }
127
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
OpenDocumentWithExtension.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/contracts/OpenDocumentWithExtension.java
package net.kdt.pojavlaunch.contracts; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.webkit.MimeTypeMap; import androidx.activity.result.contract.ActivityResultContract; import androidx.annotation.NonNull; import androidx.annotation.Nullable; // Android's OpenDocument contract is the basicmost crap that doesn't allow // you to specify practically anything. So i made this instead. public class OpenDocumentWithExtension extends ActivityResultContract<Object, Uri> { private final String mimeType; /** * Create a new OpenDocumentWithExtension contract. * If the extension provided to the constructor is not available in the device's MIME * type database, the filter will default to "all types" * @param extension the extension to filter by */ public OpenDocumentWithExtension(String extension) { String extensionMimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); if(extensionMimeType == null) extensionMimeType = "*/*"; mimeType = extensionMimeType; } @NonNull @Override public Intent createIntent(@NonNull Context context, @NonNull Object input) { Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT); intent.addCategory(Intent.CATEGORY_OPENABLE); intent.setType(mimeType); return intent; } @Nullable @Override public final SynchronousResult<Uri> getSynchronousResult(@NonNull Context context, @NonNull Object input) { return null; } @Nullable @Override public final Uri parseResult(int resultCode, @Nullable Intent intent) { if (intent == null || resultCode != Activity.RESULT_OK) return null; return intent.getData(); } }
1,875
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
VersionSelectorListener.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/profiles/VersionSelectorListener.java
package net.kdt.pojavlaunch.profiles; public interface VersionSelectorListener { void onVersionSelected(String versionId, boolean isSnapshot); }
150
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
ProfileIconCache.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/profiles/ProfileIconCache.java
package net.kdt.pojavlaunch.profiles; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.util.Base64; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.content.res.ResourcesCompat; import net.kdt.pojavlaunch.R; import java.util.HashMap; import java.util.Map; import java.util.Objects; public class ProfileIconCache { // Data header format: data:<mime>;<encoding>,<data> private static final String DATA_HEADER = "data:"; private static final String FALLBACK_ICON_NAME = "default"; private static final Map<String, Drawable> sIconCache = new HashMap<>(); private static final Map<String, Drawable> sStaticIconCache = new HashMap<>(); /** * Fetch an icon from the cache, or load it if it's not cached. * @param resources the Resources object, used for creating drawables * @param key the profile key * @param icon the profile icon data (stored in the icon field of MinecraftProfile) * @return an icon drawable */ public static @NonNull Drawable fetchIcon(Resources resources, @NonNull String key, @Nullable String icon) { Drawable cachedIcon = sIconCache.get(key); if(cachedIcon != null) return cachedIcon; if(icon != null && icon.startsWith(DATA_HEADER)) return fetchDataIcon(resources, key, icon); else return fetchStaticIcon(resources, key, icon); } /** * Drop an icon from the icon cache. When dropped, it's Drawable will be re-read from the * data string (or re-fetched from the static cache) * @param key the profile key */ public static void dropIcon(@NonNull String key) { sIconCache.remove(key); } private static Drawable fetchDataIcon(Resources resources, String key, @NonNull String icon) { Drawable dataIcon = readDataIcon(resources, icon); if(dataIcon == null) dataIcon = fetchFallbackIcon(resources); sIconCache.put(key, dataIcon); return dataIcon; } private static Drawable fetchStaticIcon(Resources resources, String key, @Nullable String icon) { Drawable staticIcon = sStaticIconCache.get(icon); if(staticIcon == null) { if(icon != null) staticIcon = getStaticIcon(resources, icon); if(staticIcon == null) staticIcon = fetchFallbackIcon(resources); sStaticIconCache.put(icon, staticIcon); } sIconCache.put(key, staticIcon); return staticIcon; } private static @NonNull Drawable fetchFallbackIcon(Resources resources) { Drawable fallbackIcon = sStaticIconCache.get(FALLBACK_ICON_NAME); if(fallbackIcon == null) { fallbackIcon = Objects.requireNonNull(getStaticIcon(resources, FALLBACK_ICON_NAME)); sStaticIconCache.put(FALLBACK_ICON_NAME, fallbackIcon); } return fallbackIcon; } private static Drawable getStaticIcon(Resources resources, @NonNull String icon) { int staticIconResource = getStaticIconResource(icon); if(staticIconResource == -1) return null; return ResourcesCompat.getDrawable(resources, staticIconResource, null); } private static int getStaticIconResource(String icon) { switch (icon) { case "default": return R.drawable.ic_pojav_full; case "fabric": return R.drawable.ic_fabric; case "quilt": return R.drawable.ic_quilt; default: return -1; } } private static Drawable readDataIcon(Resources resources, String icon) { byte[] iconData = extractIconData(icon); if(iconData == null) return null; Bitmap iconBitmap = BitmapFactory.decodeByteArray(iconData, 0, iconData.length); if(iconBitmap == null) return null; return new BitmapDrawable(resources, iconBitmap); } private static byte[] extractIconData(String inputString) { int firstSemicolon = inputString.indexOf(';'); int commaAfterSemicolon = inputString.indexOf(','); if(firstSemicolon == -1 || commaAfterSemicolon == -1) return null; String dataEncoding = inputString.substring(firstSemicolon+1, commaAfterSemicolon); if(!dataEncoding.equals("base64")) return null; return Base64.decode(inputString.substring(commaAfterSemicolon+1), 0); } }
4,481
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
VersionListAdapter.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/profiles/VersionListAdapter.java
package net.kdt.pojavlaunch.profiles; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseExpandableListAdapter; import android.widget.ExpandableListAdapter; import android.widget.TextView; import net.kdt.pojavlaunch.JMinecraftVersionList; import net.kdt.pojavlaunch.R; import net.kdt.pojavlaunch.Tools; import net.kdt.pojavlaunch.utils.FilteredSubList; import java.io.File; import java.util.Arrays; import java.util.List; public class VersionListAdapter extends BaseExpandableListAdapter implements ExpandableListAdapter { private final LayoutInflater mLayoutInflater; private final String[] mGroups; private final String[] mInstalledVersions; private final List<?>[] mData; private final boolean mHideCustomVersions; private final int mSnapshotListPosition; public VersionListAdapter(JMinecraftVersionList.Version[] versionList, boolean hideCustomVersions, Context ctx){ mHideCustomVersions = hideCustomVersions; mLayoutInflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE); List<JMinecraftVersionList.Version> releaseList = new FilteredSubList<>(versionList, item -> item.type.equals("release")); List<JMinecraftVersionList.Version> snapshotList = new FilteredSubList<>(versionList, item -> item.type.equals("snapshot")); List<JMinecraftVersionList.Version> betaList = new FilteredSubList<>(versionList, item -> item.type.equals("old_beta")); List<JMinecraftVersionList.Version> alphaList = new FilteredSubList<>(versionList, item -> item.type.equals("old_alpha")); // Query installed versions mInstalledVersions = new File(Tools.DIR_GAME_NEW + "/versions").list(); if(mInstalledVersions != null) Arrays.sort(mInstalledVersions); if(!areInstalledVersionsAvailable()){ mGroups = new String[]{ ctx.getString(R.string.mcl_setting_veroption_release), ctx.getString(R.string.mcl_setting_veroption_snapshot), ctx.getString(R.string.mcl_setting_veroption_oldbeta), ctx.getString(R.string.mcl_setting_veroption_oldalpha) }; mData = new List[]{ releaseList, snapshotList, betaList, alphaList}; mSnapshotListPosition = 1; }else{ mGroups = new String[]{ ctx.getString(R.string.mcl_setting_veroption_installed), ctx.getString(R.string.mcl_setting_veroption_release), ctx.getString(R.string.mcl_setting_veroption_snapshot), ctx.getString(R.string.mcl_setting_veroption_oldbeta), ctx.getString(R.string.mcl_setting_veroption_oldalpha) }; mData = new List[]{Arrays.asList(mInstalledVersions), releaseList, snapshotList, betaList, alphaList}; mSnapshotListPosition = 2; } } @Override public int getGroupCount() { return mGroups.length; } @Override public int getChildrenCount(int groupPosition) { return mData[groupPosition].size(); } @Override public Object getGroup(int groupPosition) { return mData[groupPosition]; } @Override public String getChild(int groupPosition, int childPosition) { if(isInstalledVersionSelected(groupPosition)){ return mInstalledVersions[childPosition]; } return ((JMinecraftVersionList.Version)mData[groupPosition].get(childPosition)).id; } @Override public long getGroupId(int groupPosition) { return groupPosition; } @Override public long getChildId(int groupPosition, int childPosition) { return childPosition; } @Override public boolean hasStableIds() { return true; } @Override public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { if(convertView == null) convertView = mLayoutInflater.inflate(android.R.layout.simple_expandable_list_item_1, parent, false); ((TextView) convertView).setText(mGroups[groupPosition]); return convertView; } @Override public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { if(convertView == null) convertView = mLayoutInflater.inflate(android.R.layout.simple_expandable_list_item_1, parent, false); ((TextView) convertView).setText(getChild(groupPosition, childPosition)); return convertView; } @Override public boolean isChildSelectable(int groupPosition, int childPosition) { return true; } public boolean isSnapshotSelected(int groupPosition) { return groupPosition == mSnapshotListPosition; } private boolean areInstalledVersionsAvailable(){ if(mHideCustomVersions) return false; return !(mInstalledVersions == null || mInstalledVersions.length == 0); } private boolean isInstalledVersionSelected(int groupPosition){ return groupPosition == 0 && areInstalledVersionsAvailable(); } }
5,265
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
ProfileAdapter.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/profiles/ProfileAdapter.java
package net.kdt.pojavlaunch.profiles; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import androidx.core.graphics.ColorUtils; import net.kdt.pojavlaunch.R; import net.kdt.pojavlaunch.Tools; import net.kdt.pojavlaunch.prefs.LauncherPreferences; import net.kdt.pojavlaunch.value.launcherprofiles.LauncherProfiles; import net.kdt.pojavlaunch.value.launcherprofiles.MinecraftProfile; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import fr.spse.extended_view.ExtendedTextView; /* * Adapter for listing launcher profiles in a Spinner */ public class ProfileAdapter extends BaseAdapter { private Map<String, MinecraftProfile> mProfiles; private final MinecraftProfile dummy = new MinecraftProfile(); private List<String> mProfileList; private ProfileAdapterExtra[] mExtraEntires; public ProfileAdapter(ProfileAdapterExtra[] extraEntries) { reloadProfiles(extraEntries); } /* * Gets how much profiles are loaded in the adapter right now * @returns loaded profile count */ @Override public int getCount() { return mProfileList.size() + mExtraEntires.length; } /* * Gets the profile at a given index * @param position index to retreive * @returns MinecraftProfile name or null */ @Override public Object getItem(int position) { int profileListSize = mProfileList.size(); int extraPosition = position - profileListSize; if(position < profileListSize){ String profileName = mProfileList.get(position); if(mProfiles.containsKey(profileName)) return profileName; }else if(extraPosition >= 0 && extraPosition < mExtraEntires.length) { return mExtraEntires[extraPosition]; } return null; } public int resolveProfileIndex(String name) { return mProfileList.indexOf(name); } @Override public long getItemId(int position) { return position; } @Override public void notifyDataSetChanged() { mProfiles = new HashMap<>(LauncherProfiles.mainProfileJson.profiles); mProfileList = new ArrayList<>(Arrays.asList(mProfiles.keySet().toArray(new String[0]))); super.notifyDataSetChanged(); } @Override public View getView(int position, View convertView, ViewGroup parent) { View v = convertView; if (v == null) v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_version_profile_layout,parent,false); setView(v, getItem(position), true); return v; } public void setViewProfile(View v, String nm, boolean displaySelection) { ExtendedTextView extendedTextView = (ExtendedTextView) v; MinecraftProfile minecraftProfile = mProfiles.get(nm); if(minecraftProfile == null) minecraftProfile = dummy; Drawable cachedIcon = ProfileIconCache.fetchIcon(v.getResources(), nm, minecraftProfile.icon); extendedTextView.setCompoundDrawablesRelative(cachedIcon, null, extendedTextView.getCompoundsDrawables()[2], null); if(Tools.isValidString(minecraftProfile.name)) extendedTextView.setText(minecraftProfile.name); else extendedTextView.setText(R.string.unnamed); if(minecraftProfile.lastVersionId != null){ if(minecraftProfile.lastVersionId.equalsIgnoreCase("latest-release")){ extendedTextView.setText( String.format("%s - %s", extendedTextView.getText(), v.getContext().getText(R.string.profiles_latest_release))); } else if(minecraftProfile.lastVersionId.equalsIgnoreCase("latest-snapshot")){ extendedTextView.setText( String.format("%s - %s", extendedTextView.getText(), v.getContext().getText(R.string.profiles_latest_snapshot))); } else { extendedTextView.setText( String.format("%s - %s", extendedTextView.getText(), minecraftProfile.lastVersionId)); } } else extendedTextView.setText(extendedTextView.getText()); // Set selected background if needed if(displaySelection){ String selectedProfile = LauncherPreferences.DEFAULT_PREF.getString(LauncherPreferences.PREF_KEY_CURRENT_PROFILE,""); extendedTextView.setBackgroundColor(selectedProfile.equals(nm) ? ColorUtils.setAlphaComponent(Color.WHITE,60) : Color.TRANSPARENT); }else extendedTextView.setBackgroundColor(Color.TRANSPARENT); } public void setViewExtra(View v, ProfileAdapterExtra extra) { ExtendedTextView extendedTextView = (ExtendedTextView) v; extendedTextView.setCompoundDrawablesRelative(extra.icon, null, extendedTextView.getCompoundsDrawables()[2], null); extendedTextView.setText(extra.name); extendedTextView.setBackgroundColor(Color.TRANSPARENT); } public void setView(View v, Object object, boolean displaySelection) { if(object instanceof String) { setViewProfile(v, (String) object, displaySelection); }else if(object instanceof ProfileAdapterExtra) { setViewExtra(v, (ProfileAdapterExtra) object); } } /** Reload profiles from the file */ public void reloadProfiles(){ LauncherProfiles.load(); mProfiles = new HashMap<>(LauncherProfiles.mainProfileJson.profiles); mProfileList = new ArrayList<>(Arrays.asList(mProfiles.keySet().toArray(new String[0]))); notifyDataSetChanged(); } /** Reload profiles from the file, with additional extra entries */ public void reloadProfiles(ProfileAdapterExtra[] extraEntries) { if(extraEntries == null) mExtraEntires = new ProfileAdapterExtra[0]; else mExtraEntires = extraEntries; this.reloadProfiles(); } }
5,987
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
VersionSelectorDialog.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/profiles/VersionSelectorDialog.java
package net.kdt.pojavlaunch.profiles; import static net.kdt.pojavlaunch.extra.ExtraCore.getValue; import android.content.Context; import android.view.LayoutInflater; import android.widget.ExpandableListView; import androidx.appcompat.app.AlertDialog; import net.kdt.pojavlaunch.JMinecraftVersionList; import net.kdt.pojavlaunch.R; import net.kdt.pojavlaunch.extra.ExtraConstants; public class VersionSelectorDialog { public static void open(Context context, boolean hideCustomVersions, VersionSelectorListener listener) { AlertDialog.Builder builder = new AlertDialog.Builder(context); ExpandableListView expandableListView = (ExpandableListView) LayoutInflater.from(context) .inflate(R.layout.dialog_expendable_list_view , null); JMinecraftVersionList jMinecraftVersionList = (JMinecraftVersionList) getValue(ExtraConstants.RELEASE_TABLE); JMinecraftVersionList.Version[] versionArray; if(jMinecraftVersionList == null || jMinecraftVersionList.versions == null) versionArray = new JMinecraftVersionList.Version[0]; else versionArray = jMinecraftVersionList.versions; VersionListAdapter adapter = new VersionListAdapter(versionArray, hideCustomVersions, context); expandableListView.setAdapter(adapter); builder.setView(expandableListView); AlertDialog dialog = builder.show(); expandableListView.setOnChildClickListener((parent, v1, groupPosition, childPosition, id) -> { String version = adapter.getChild(groupPosition, childPosition); listener.onVersionSelected(version, adapter.isSnapshotSelected(groupPosition)); dialog.dismiss(); return true; }); } }
1,732
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
ProfileAdapterExtra.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/profiles/ProfileAdapterExtra.java
package net.kdt.pojavlaunch.profiles; import android.graphics.drawable.Drawable; public class ProfileAdapterExtra { public final int id; public final int name; public final Drawable icon; public ProfileAdapterExtra(int id, int name, Drawable icon) { this.id = id; this.name = name; this.icon = icon; } }
351
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
FFmpegPlugin.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/plugins/FFmpegPlugin.java
package net.kdt.pojavlaunch.plugins; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.util.Log; public class FFmpegPlugin { public static boolean isAvailable = false; public static String libraryPath; public static void discover(Context context) { PackageManager manager = context.getPackageManager(); try { PackageInfo ffmpegPluginInfo = manager.getPackageInfo("net.kdt.pojavlaunch.ffmpeg", PackageManager.GET_SHARED_LIBRARY_FILES); libraryPath = ffmpegPluginInfo.applicationInfo.nativeLibraryDir; isAvailable = true; }catch (Exception e) { Log.i("FFmpegPlugin", "Failed to discover plugin", e); } } }
780
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
FabriclikeDownloadTask.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/modloaders/FabriclikeDownloadTask.java
package net.kdt.pojavlaunch.modloaders; import com.kdt.mcgui.ProgressLayout; import net.kdt.pojavlaunch.R; import net.kdt.pojavlaunch.Tools; import net.kdt.pojavlaunch.progresskeeper.ProgressKeeper; import net.kdt.pojavlaunch.utils.DownloadUtils; import net.kdt.pojavlaunch.utils.FileUtils; import net.kdt.pojavlaunch.value.launcherprofiles.LauncherProfiles; import net.kdt.pojavlaunch.value.launcherprofiles.MinecraftProfile; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.io.IOException; public class FabriclikeDownloadTask implements Runnable, Tools.DownloaderFeedback{ private final ModloaderDownloadListener mModloaderDownloadListener; private final FabriclikeUtils mUtils; private final String mGameVersion; private final String mLoaderVersion; private final boolean mCreateProfile; public FabriclikeDownloadTask(ModloaderDownloadListener modloaderDownloadListener, FabriclikeUtils utils, String mGameVersion, String mLoaderVersion, boolean mCreateProfile) { this.mModloaderDownloadListener = modloaderDownloadListener; this.mUtils = utils; this.mGameVersion = mGameVersion; this.mLoaderVersion = mLoaderVersion; this.mCreateProfile = mCreateProfile; } @Override public void run() { ProgressKeeper.submitProgress(ProgressLayout.INSTALL_MODPACK, 0, R.string.fabric_dl_progress); try { if(runCatching()) mModloaderDownloadListener.onDownloadFinished(null); else mModloaderDownloadListener.onDataNotAvailable(); }catch (IOException e) { mModloaderDownloadListener.onDownloadError(e); } ProgressLayout.clearProgress(ProgressLayout.INSTALL_MODPACK); } private boolean runCatching() throws IOException{ String fabricJson = DownloadUtils.downloadString(mUtils.createJsonDownloadUrl(mGameVersion, mLoaderVersion)); String versionId; try { JSONObject fabricJsonObject = new JSONObject(fabricJson); versionId = fabricJsonObject.getString("id"); }catch (JSONException e) { e.printStackTrace(); return false; } File versionJsonDir = new File(Tools.DIR_HOME_VERSION, versionId); File versionJsonFile = new File(versionJsonDir, versionId+".json"); FileUtils.ensureDirectory(versionJsonDir); Tools.write(versionJsonFile.getAbsolutePath(), fabricJson); if(mCreateProfile) { LauncherProfiles.load(); MinecraftProfile fabricProfile = new MinecraftProfile(); fabricProfile.lastVersionId = versionId; fabricProfile.name = mUtils.getName(); fabricProfile.icon = mUtils.getIconName(); LauncherProfiles.insertMinecraftProfile(fabricProfile); LauncherProfiles.write(); } return true; } @Override public void updateProgress(int curr, int max) { int progress100 = (int)(((float)curr / (float)max)*100f); ProgressKeeper.submitProgress(ProgressLayout.INSTALL_MODPACK, progress100, R.string.fabric_dl_progress, mUtils.getName()); } }
3,184
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
ModloaderDownloadListener.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/modloaders/ModloaderDownloadListener.java
package net.kdt.pojavlaunch.modloaders; import java.io.File; public interface ModloaderDownloadListener { void onDownloadFinished(File downloadedFile); void onDataNotAvailable(); void onDownloadError(Exception e); }
230
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
OFDownloadPageScraper.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/modloaders/OFDownloadPageScraper.java
package net.kdt.pojavlaunch.modloaders; import org.htmlcleaner.HtmlCleaner; import org.htmlcleaner.HtmlNode; import org.htmlcleaner.TagNode; import org.htmlcleaner.TagNodeVisitor; import java.io.IOException; import java.net.URL; public class OFDownloadPageScraper implements TagNodeVisitor { public static String run(String urlInput) throws IOException{ return new OFDownloadPageScraper().runInner(urlInput); } private String mDownloadFullUrl; private String runInner(String url) throws IOException { HtmlCleaner htmlCleaner = new HtmlCleaner(); htmlCleaner.clean(new URL(url)).traverse(this); return mDownloadFullUrl; } @Override public boolean visit(TagNode parentNode, HtmlNode htmlNode) { if(isDownloadUrl(parentNode, htmlNode)) { TagNode tagNode = (TagNode) htmlNode; String href = tagNode.getAttributeByName("href"); if(!href.startsWith("https://")) href = "https://optifine.net/"+href; this.mDownloadFullUrl = href; return false; } return true; } public boolean isDownloadUrl(TagNode parentNode, HtmlNode htmlNode) { if(!(htmlNode instanceof TagNode)) return false; if(parentNode == null) return false; TagNode tagNode = (TagNode) htmlNode; if(!(parentNode.getName().equals("span") && "Download".equals(parentNode.getAttributeByName("id")))) return false; return tagNode.getName().equals("a") && "onDownload()".equals(tagNode.getAttributeByName("onclick")); } }
1,600
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
FabricVersion.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/modloaders/FabricVersion.java
package net.kdt.pojavlaunch.modloaders; import androidx.annotation.NonNull; public class FabricVersion { public String version; public boolean stable; public static class LoaderDescriptor extends FabricVersion { public FabricVersion loader; @NonNull @Override public String toString() { return loader != null ? loader.toString() : "null"; } } @NonNull @Override public String toString() { return version; } }
506
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
ForgeVersionListAdapter.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/modloaders/ForgeVersionListAdapter.java
package net.kdt.pojavlaunch.modloaders; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseExpandableListAdapter; import android.widget.ExpandableListAdapter; import android.widget.TextView; import java.util.ArrayList; import java.util.List; public class ForgeVersionListAdapter extends BaseExpandableListAdapter implements ExpandableListAdapter { private final List<String> mGameVersions; private final List<List<String>> mForgeVersions; private final LayoutInflater mLayoutInflater; public ForgeVersionListAdapter(List<String> forgeVersions, LayoutInflater layoutInflater) { this.mLayoutInflater = layoutInflater; mGameVersions = new ArrayList<>(); mForgeVersions = new ArrayList<>(); for(String version : forgeVersions) { int dashIndex = version.indexOf("-"); String gameVersion = version.substring(0, dashIndex); List<String> versionList; int gameVersionIndex = mGameVersions.indexOf(gameVersion); if(gameVersionIndex != -1) versionList = mForgeVersions.get(gameVersionIndex); else { versionList = new ArrayList<>(); mGameVersions.add(gameVersion); mForgeVersions.add(versionList); } versionList.add(version); } } @Override public int getGroupCount() { return mGameVersions.size(); } @Override public int getChildrenCount(int i) { return mForgeVersions.get(i).size(); } @Override public Object getGroup(int i) { return getGameVersion(i); } @Override public Object getChild(int i, int i1) { return getForgeVersion(i, i1); } @Override public long getGroupId(int i) { return i; } @Override public long getChildId(int i, int i1) { return i1; } @Override public boolean hasStableIds() { return true; } @Override public View getGroupView(int i, boolean b, View convertView, ViewGroup viewGroup) { if(convertView == null) convertView = mLayoutInflater.inflate(android.R.layout.simple_expandable_list_item_1, viewGroup, false); ((TextView) convertView).setText(getGameVersion(i)); return convertView; } @Override public View getChildView(int i, int i1, boolean b, View convertView, ViewGroup viewGroup) { if(convertView == null) convertView = mLayoutInflater.inflate(android.R.layout.simple_expandable_list_item_1, viewGroup, false); ((TextView) convertView).setText(getForgeVersion(i, i1)); return convertView; } private String getGameVersion(int i) { return mGameVersions.get(i); } private String getForgeVersion(int i, int i1){ return mForgeVersions.get(i).get(i1); } @Override public boolean isChildSelectable(int i, int i1) { return true; } }
3,022
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
OptiFineDownloadTask.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/modloaders/OptiFineDownloadTask.java
package net.kdt.pojavlaunch.modloaders; import com.kdt.mcgui.ProgressLayout; import net.kdt.pojavlaunch.JMinecraftVersionList; import net.kdt.pojavlaunch.R; import net.kdt.pojavlaunch.Tools; import net.kdt.pojavlaunch.progresskeeper.ProgressKeeper; import net.kdt.pojavlaunch.tasks.AsyncMinecraftDownloader; import net.kdt.pojavlaunch.tasks.MinecraftDownloader; import net.kdt.pojavlaunch.utils.DownloadUtils; import java.io.File; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; public class OptiFineDownloadTask implements Runnable, Tools.DownloaderFeedback, AsyncMinecraftDownloader.DoneListener { private static final Pattern sMcVersionPattern = Pattern.compile("([0-9]+)\\.([0-9]+)\\.?([0-9]+)?"); private final OptiFineUtils.OptiFineVersion mOptiFineVersion; private final File mDestinationFile; private final ModloaderDownloadListener mListener; private final Object mMinecraftDownloadLock = new Object(); private Throwable mDownloaderThrowable; public OptiFineDownloadTask(OptiFineUtils.OptiFineVersion mOptiFineVersion, ModloaderDownloadListener mListener) { this.mOptiFineVersion = mOptiFineVersion; this.mDestinationFile = new File(Tools.DIR_CACHE, "optifine-installer.jar"); this.mListener = mListener; } @Override public void run() { ProgressKeeper.submitProgress(ProgressLayout.INSTALL_MODPACK, 0, R.string.of_dl_progress, mOptiFineVersion.versionName); try { if(runCatching()) mListener.onDownloadFinished(mDestinationFile); }catch (IOException e) { mListener.onDownloadError(e); } ProgressLayout.clearProgress(ProgressLayout.INSTALL_MODPACK); } public boolean runCatching() throws IOException { String downloadUrl = scrapeDownloadsPage(); if(downloadUrl == null) return false; String minecraftVersion = determineMinecraftVersion(); if(minecraftVersion == null) return false; if(!downloadMinecraft(minecraftVersion)) { if(mDownloaderThrowable instanceof Exception) { mListener.onDownloadError((Exception) mDownloaderThrowable); }else { Exception exception = new Exception(mDownloaderThrowable); mListener.onDownloadError(exception); } return false; } DownloadUtils.downloadFileMonitored(downloadUrl, mDestinationFile, new byte[8192], this); return true; } public String scrapeDownloadsPage() throws IOException{ String scrapeResult = OFDownloadPageScraper.run(mOptiFineVersion.downloadUrl); if(scrapeResult == null) mListener.onDataNotAvailable(); return scrapeResult; } public String determineMinecraftVersion() { Matcher matcher = sMcVersionPattern.matcher(mOptiFineVersion.minecraftVersion); if(matcher.find()) { StringBuilder mcVersionBuilder = new StringBuilder(); mcVersionBuilder.append(matcher.group(1)); mcVersionBuilder.append('.'); mcVersionBuilder.append(matcher.group(2)); String thirdGroup = matcher.group(3); if(thirdGroup != null && !thirdGroup.isEmpty() && !"0".equals(thirdGroup)) { mcVersionBuilder.append('.'); mcVersionBuilder.append(thirdGroup); } return mcVersionBuilder.toString(); }else{ mListener.onDataNotAvailable(); return null; } } public boolean downloadMinecraft(String minecraftVersion) { // the string is always normalized JMinecraftVersionList.Version minecraftJsonVersion = AsyncMinecraftDownloader.getListedVersion(minecraftVersion); if(minecraftJsonVersion == null) return false; try { synchronized (mMinecraftDownloadLock) { new MinecraftDownloader().start(null, minecraftJsonVersion, minecraftVersion, this); mMinecraftDownloadLock.wait(); } }catch (InterruptedException e) { e.printStackTrace(); } return mDownloaderThrowable == null; } @Override public void updateProgress(int curr, int max) { int progress100 = (int)(((float)curr / (float)max)*100f); ProgressKeeper.submitProgress(ProgressLayout.INSTALL_MODPACK, progress100, R.string.of_dl_progress, mOptiFineVersion.versionName); } @Override public void onDownloadDone() { synchronized (mMinecraftDownloadLock) { mDownloaderThrowable = null; mMinecraftDownloadLock.notifyAll(); } } @Override public void onDownloadFailed(Throwable throwable) { synchronized (mMinecraftDownloadLock) { mDownloaderThrowable = throwable; mMinecraftDownloadLock.notifyAll(); } } }
4,914
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
ForgeUtils.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/modloaders/ForgeUtils.java
package net.kdt.pojavlaunch.modloaders; import android.content.Intent; import net.kdt.pojavlaunch.Tools; import net.kdt.pojavlaunch.utils.DownloadUtils; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import java.io.File; import java.io.IOException; import java.io.StringReader; import java.util.List; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; public class ForgeUtils { private static final String FORGE_METADATA_URL = "https://maven.minecraftforge.net/net/minecraftforge/forge/maven-metadata.xml"; private static final String FORGE_INSTALLER_URL = "https://maven.minecraftforge.net/net/minecraftforge/forge/%1$s/forge-%1$s-installer.jar"; public static List<String> downloadForgeVersions() throws IOException { SAXParser saxParser; try { SAXParserFactory parserFactory = SAXParserFactory.newInstance(); saxParser = parserFactory.newSAXParser(); }catch (SAXException | ParserConfigurationException e) { e.printStackTrace(); // if we cant make a parser we might as well not even try to parse anything return null; } try { //of_test(); return DownloadUtils.downloadStringCached(FORGE_METADATA_URL, "forge_versions", input -> { try { ForgeVersionListHandler handler = new ForgeVersionListHandler(); saxParser.parse(new InputSource(new StringReader(input)), handler); return handler.getVersions(); // IOException is present here StringReader throws it only if the parser called close() // sooner than needed, which is a parser issue and not an I/O one }catch (SAXException | IOException e) { throw new DownloadUtils.ParseException(e); } }); }catch (DownloadUtils.ParseException e) { e.printStackTrace(); return null; } } public static String getInstallerUrl(String version) { return String.format(FORGE_INSTALLER_URL, version); } public static void addAutoInstallArgs(Intent intent, File modInstallerJar, boolean createProfile) { intent.putExtra("javaArgs", "-javaagent:"+ Tools.DIR_DATA+"/forge_installer/forge_installer.jar" + (createProfile ? "=NPS" : "") + // No Profile Suppression " -jar "+modInstallerJar.getAbsolutePath()); } public static void addAutoInstallArgs(Intent intent, File modInstallerJar, String modpackFixupId) { intent.putExtra("javaArgs", "-javaagent:"+ Tools.DIR_DATA+"/forge_installer/forge_installer.jar" + "=\"" + modpackFixupId +"\"" + " -jar "+modInstallerJar.getAbsolutePath()); } }
2,898
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
ForgeDownloadTask.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/modloaders/ForgeDownloadTask.java
package net.kdt.pojavlaunch.modloaders; import com.kdt.mcgui.ProgressLayout; import net.kdt.pojavlaunch.R; import net.kdt.pojavlaunch.Tools; import net.kdt.pojavlaunch.progresskeeper.ProgressKeeper; import net.kdt.pojavlaunch.utils.DownloadUtils; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.List; public class ForgeDownloadTask implements Runnable, Tools.DownloaderFeedback { private String mDownloadUrl; private String mFullVersion; private String mLoaderVersion; private String mGameVersion; private final ModloaderDownloadListener mListener; public ForgeDownloadTask(ModloaderDownloadListener listener, String forgeVersion) { this.mListener = listener; this.mDownloadUrl = ForgeUtils.getInstallerUrl(forgeVersion); this.mFullVersion = forgeVersion; } public ForgeDownloadTask(ModloaderDownloadListener listener, String gameVersion, String loaderVersion) { this.mListener = listener; this.mLoaderVersion = loaderVersion; this.mGameVersion = gameVersion; } @Override public void run() { if(determineDownloadUrl()) { downloadForge(); } ProgressLayout.clearProgress(ProgressLayout.INSTALL_MODPACK); } @Override public void updateProgress(int curr, int max) { int progress100 = (int)(((float)curr / (float)max)*100f); ProgressKeeper.submitProgress(ProgressLayout.INSTALL_MODPACK, progress100, R.string.forge_dl_progress, mFullVersion); } private void downloadForge() { ProgressKeeper.submitProgress(ProgressLayout.INSTALL_MODPACK, 0, R.string.forge_dl_progress, mFullVersion); try { File destinationFile = new File(Tools.DIR_CACHE, "forge-installer.jar"); byte[] buffer = new byte[8192]; DownloadUtils.downloadFileMonitored(mDownloadUrl, destinationFile, buffer, this); mListener.onDownloadFinished(destinationFile); }catch (FileNotFoundException e) { mListener.onDataNotAvailable(); } catch (IOException e) { mListener.onDownloadError(e); } } public boolean determineDownloadUrl() { if(mDownloadUrl != null && mFullVersion != null) return true; ProgressKeeper.submitProgress(ProgressLayout.INSTALL_MODPACK, 0, R.string.forge_dl_searching); try { if(!findVersion()) { mListener.onDataNotAvailable(); return false; } }catch (IOException e) { mListener.onDownloadError(e); return false; } return true; } public boolean findVersion() throws IOException { List<String> forgeVersions = ForgeUtils.downloadForgeVersions(); if(forgeVersions == null) return false; String versionStart = mGameVersion+"-"+mLoaderVersion; for(String versionName : forgeVersions) { if(!versionName.startsWith(versionStart)) continue; mFullVersion = versionName; mDownloadUrl = ForgeUtils.getInstallerUrl(mFullVersion); return true; } return false; } }
3,212
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
FabriclikeUtils.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/modloaders/FabriclikeUtils.java
package net.kdt.pojavlaunch.modloaders; import com.google.gson.JsonSyntaxException; import net.kdt.pojavlaunch.Tools; import net.kdt.pojavlaunch.utils.DownloadUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; public class FabriclikeUtils { public static final FabriclikeUtils FABRIC_UTILS = new FabriclikeUtils("https://meta.fabricmc.net/v2", "fabric", "Fabric", "fabric"); public static final FabriclikeUtils QUILT_UTILS = new FabriclikeUtils("https://meta.quiltmc.org/v3", "quilt", "Quilt", "quilt"); private static final String LOADER_METADATA_URL = "%s/versions/loader/%s"; private static final String GAME_METADATA_URL = "%s/versions/game"; private static final String JSON_DOWNLOAD_URL = "%s/versions/loader/%s/%s/profile/json"; private final String mApiUrl; private final String mCachePrefix; private final String mName; private final String mIconName; private FabriclikeUtils(String mApiUrl, String cachePrefix, String mName, String iconName) { this.mApiUrl = mApiUrl; this.mCachePrefix = cachePrefix; this.mIconName = iconName; this.mName = mName; } public FabricVersion[] downloadGameVersions() throws IOException{ try { return DownloadUtils.downloadStringCached(String.format(GAME_METADATA_URL, mApiUrl), mCachePrefix+"_game_versions", FabriclikeUtils::deserializeRawVersions ); }catch (DownloadUtils.ParseException ignored) {} return null; } public FabricVersion[] downloadLoaderVersions(String gameVersion) throws IOException{ try { String urlEncodedGameVersion = URLEncoder.encode(gameVersion, "UTF-8"); return DownloadUtils.downloadStringCached(String.format(LOADER_METADATA_URL, mApiUrl, urlEncodedGameVersion), mCachePrefix+"_loader_versions."+urlEncodedGameVersion, (input)->{ try { return deserializeLoaderVersions(input); }catch (JSONException e) { throw new DownloadUtils.ParseException(e); }}); }catch (DownloadUtils.ParseException e) { e.printStackTrace(); } return null; } public String createJsonDownloadUrl(String gameVersion, String loaderVersion) { try { gameVersion = URLEncoder.encode(gameVersion, "UTF-8"); loaderVersion = URLEncoder.encode(loaderVersion, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } return String.format(JSON_DOWNLOAD_URL, mApiUrl, gameVersion, loaderVersion); } public String getName() { return mName; } public String getIconName() { return mIconName; } private static FabricVersion[] deserializeLoaderVersions(String input) throws JSONException { JSONArray jsonArray = new JSONArray(input); FabricVersion[] fabricVersions = new FabricVersion[jsonArray.length()]; for(int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i).getJSONObject("loader"); FabricVersion fabricVersion = new FabricVersion(); fabricVersion.version = jsonObject.getString("version"); //Quilt has a skill issue and does not say which versions are stable or not if(jsonObject.has("stable")) { fabricVersion.stable = jsonObject.getBoolean("stable"); } else { fabricVersion.stable = !fabricVersion.version.contains("beta"); } fabricVersions[i] = fabricVersion; } return fabricVersions; } private static FabricVersion[] deserializeRawVersions(String jsonArrayIn) throws DownloadUtils.ParseException { try { return Tools.GLOBAL_GSON.fromJson(jsonArrayIn, FabricVersion[].class); }catch (JsonSyntaxException e) { e.printStackTrace(); throw new DownloadUtils.ParseException(null); } } }
4,249
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
ForgeVersionListHandler.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/modloaders/ForgeVersionListHandler.java
package net.kdt.pojavlaunch.modloaders; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import java.util.ArrayList; import java.util.List; public class ForgeVersionListHandler extends DefaultHandler { private List<String> mForgeVersions; private StringBuilder mCurrentVersion = null; @Override public void startDocument() throws SAXException { mForgeVersions = new ArrayList<>(); } @Override public void characters(char[] ch, int start, int length) throws SAXException { if(mCurrentVersion != null) mCurrentVersion.append(ch, start, length); } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if(qName.equals("version")) mCurrentVersion = new StringBuilder(); } @Override public void endElement(String uri, String localName, String qName) throws SAXException { if (qName.equals("version")) { String version = mCurrentVersion.toString(); mForgeVersions.add(version); mCurrentVersion = null; } } public List<String> getVersions() { return mForgeVersions; } }
1,245
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
OptiFineUtils.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/modloaders/OptiFineUtils.java
package net.kdt.pojavlaunch.modloaders; import android.content.Intent; import net.kdt.pojavlaunch.Tools; import net.kdt.pojavlaunch.utils.DownloadUtils; import java.io.File; import java.io.IOException; import java.util.List; public class OptiFineUtils { public static OptiFineVersions downloadOptiFineVersions() throws IOException { try { return DownloadUtils.downloadStringCached("https://optifine.net/downloads", "of_downloads_page", new OptiFineScraper()); }catch (DownloadUtils.ParseException e) { e.printStackTrace(); return null; } } public static void addAutoInstallArgs(Intent intent, File modInstallerJar) { intent.putExtra("javaArgs", "-javaagent:"+ Tools.DIR_DATA+"/forge_installer/forge_installer.jar" + "=OFNPS" +// No Profile Suppression " -jar "+modInstallerJar.getAbsolutePath()); } public static class OptiFineVersions { public List<String> minecraftVersions; public List<List<OptiFineVersion>> optifineVersions; } public static class OptiFineVersion { public String minecraftVersion; public String versionName; public String downloadUrl; } }
1,259
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
ModloaderListenerProxy.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/modloaders/ModloaderListenerProxy.java
package net.kdt.pojavlaunch.modloaders; import java.io.File; public class ModloaderListenerProxy implements ModloaderDownloadListener { public static final int PROXY_RESULT_NONE = -1; public static final int PROXY_RESULT_FINISHED = 0; public static final int PROXY_RESULT_NOT_AVAILABLE = 1; public static final int PROXY_RESULT_ERROR = 2; private ModloaderDownloadListener mDestinationListener; private Object mProxyResultObject; private int mProxyResult = PROXY_RESULT_NONE; @Override public synchronized void onDownloadFinished(File downloadedFile) { if(mDestinationListener != null) { mDestinationListener.onDownloadFinished(downloadedFile); }else{ mProxyResult = PROXY_RESULT_FINISHED; mProxyResultObject = downloadedFile; } } @Override public synchronized void onDataNotAvailable() { if(mDestinationListener != null) { mDestinationListener.onDataNotAvailable(); }else{ mProxyResult = PROXY_RESULT_NOT_AVAILABLE; mProxyResultObject = null; } } @Override public synchronized void onDownloadError(Exception e) { if(mDestinationListener != null) { mDestinationListener.onDownloadError(e); }else { mProxyResult = PROXY_RESULT_ERROR; mProxyResultObject = e; } } public synchronized void attachListener(ModloaderDownloadListener listener) { switch(mProxyResult) { case PROXY_RESULT_FINISHED: listener.onDownloadFinished((File) mProxyResultObject); break; case PROXY_RESULT_NOT_AVAILABLE: listener.onDataNotAvailable(); break; case PROXY_RESULT_ERROR: listener.onDownloadError((Exception) mProxyResultObject); break; } mDestinationListener = listener; } public synchronized void detachListener() { mDestinationListener = null; } }
2,058
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
OptiFineVersionListAdapter.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/modloaders/OptiFineVersionListAdapter.java
package net.kdt.pojavlaunch.modloaders; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseExpandableListAdapter; import android.widget.ExpandableListAdapter; import android.widget.TextView; public class OptiFineVersionListAdapter extends BaseExpandableListAdapter implements ExpandableListAdapter { private final OptiFineUtils.OptiFineVersions mOptiFineVersions; private final LayoutInflater mLayoutInflater; public OptiFineVersionListAdapter(OptiFineUtils.OptiFineVersions optiFineVersions, LayoutInflater mLayoutInflater) { mOptiFineVersions = optiFineVersions; this.mLayoutInflater = mLayoutInflater; } @Override public int getGroupCount() { return mOptiFineVersions.minecraftVersions.size(); } @Override public int getChildrenCount(int i) { return mOptiFineVersions.optifineVersions.get(i).size(); } @Override public Object getGroup(int i) { return mOptiFineVersions.minecraftVersions.get(i); } @Override public Object getChild(int i, int i1) { return mOptiFineVersions.optifineVersions.get(i).get(i1); } @Override public long getGroupId(int i) { return i; } @Override public long getChildId(int i, int i1) { return i1; } @Override public boolean hasStableIds() { return true; } @Override public View getGroupView(int i, boolean b, View convertView, ViewGroup viewGroup) { if(convertView == null) convertView = mLayoutInflater.inflate(android.R.layout.simple_expandable_list_item_1, viewGroup, false); ((TextView) convertView).setText((String)getGroup(i)); return convertView; } @Override public View getChildView(int i, int i1, boolean b, View convertView, ViewGroup viewGroup) { if(convertView == null) convertView = mLayoutInflater.inflate(android.R.layout.simple_expandable_list_item_1, viewGroup, false); ((TextView) convertView).setText(((OptiFineUtils.OptiFineVersion)getChild(i,i1)).versionName); return convertView; } @Override public boolean isChildSelectable(int i, int i1) { return true; } }
2,281
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
OptiFineScraper.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/modloaders/OptiFineScraper.java
package net.kdt.pojavlaunch.modloaders; import net.kdt.pojavlaunch.utils.DownloadUtils; import org.htmlcleaner.HtmlCleaner; import org.htmlcleaner.TagNode; import java.util.ArrayList; import java.util.List; public class OptiFineScraper implements DownloadUtils.ParseCallback<OptiFineUtils.OptiFineVersions> { private final OptiFineUtils.OptiFineVersions mOptiFineVersions; private List<OptiFineUtils.OptiFineVersion> mListInProgress; private String mMinecraftVersion; public OptiFineScraper() { mOptiFineVersions = new OptiFineUtils.OptiFineVersions(); mOptiFineVersions.minecraftVersions = new ArrayList<>(); mOptiFineVersions.optifineVersions = new ArrayList<>(); } @Override public OptiFineUtils.OptiFineVersions process(String input) throws DownloadUtils.ParseException { HtmlCleaner htmlCleaner = new HtmlCleaner(); TagNode tagNode = htmlCleaner.clean(input); traverseTagNode(tagNode); insertVersionContent(null); if(mOptiFineVersions.optifineVersions.size() < 1 || mOptiFineVersions.minecraftVersions.size() < 1) throw new DownloadUtils.ParseException(null); return mOptiFineVersions; } public void traverseTagNode(TagNode tagNode) { if(isDownloadLine(tagNode) && mMinecraftVersion != null) { traverseDownloadLine(tagNode); } else if(isMinecraftVersionTag(tagNode)) { insertVersionContent(tagNode); } else { for(TagNode tagNodes : tagNode.getChildTags()) { traverseTagNode(tagNodes); } } } private boolean isDownloadLine(TagNode tagNode) { return tagNode.getName().equals("tr") && tagNode.hasAttribute("class") && tagNode.getAttributeByName("class").startsWith("downloadLine"); } private boolean isMinecraftVersionTag(TagNode tagNode) { return tagNode.getName().equals("h2") && tagNode.getText().toString().startsWith("Minecraft "); } private void traverseDownloadLine(TagNode tagNode) { OptiFineUtils.OptiFineVersion optiFineVersion = new OptiFineUtils.OptiFineVersion(); optiFineVersion.minecraftVersion = mMinecraftVersion; for(TagNode subNode : tagNode.getChildTags()) { if(!subNode.getName().equals("td")) continue; switch(subNode.getAttributeByName("class")) { case "colFile": optiFineVersion.versionName = subNode.getText().toString(); break; case "colMirror": optiFineVersion.downloadUrl = getLinkHref(subNode); } } mListInProgress.add(optiFineVersion); } private String getLinkHref(TagNode parent) { for(TagNode subNode : parent.getChildTags()) { if(subNode.getName().equals("a") && subNode.hasAttribute("href")) { return subNode.getAttributeByName("href").replace("http://", "https://"); } } return null; } private void insertVersionContent(TagNode tagNode) { if(mListInProgress != null && mMinecraftVersion != null) { mOptiFineVersions.minecraftVersions.add(mMinecraftVersion); mOptiFineVersions.optifineVersions.add(mListInProgress); } if(tagNode != null) { mMinecraftVersion = tagNode.getText().toString(); mListInProgress = new ArrayList<>(); } } }
3,515
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
SelfReferencingFuture.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/modloaders/modpacks/SelfReferencingFuture.java
package net.kdt.pojavlaunch.modloaders.modpacks; import android.util.Log; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; public class SelfReferencingFuture { private final Object mFutureLock = new Object(); private final FutureInterface mFutureInterface; private Future<?> mMyFuture; public SelfReferencingFuture(FutureInterface futureInterface) { this.mFutureInterface = futureInterface; } public Future<?> startOnExecutor(ExecutorService executorService) { Future<?> future = executorService.submit(this::run); synchronized (mFutureLock) { mMyFuture = future; mFutureLock.notify(); } return future; } private void run() { try { synchronized (mFutureLock) { if (mMyFuture == null) mFutureLock.wait(); } mFutureInterface.run(mMyFuture); }catch (InterruptedException e) { Log.i("SelfReferencingFuture", "Interrupted while acquiring own Future"); } } public interface FutureInterface { void run(Future<?> myFuture); } }
1,163
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
ModItemAdapter.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/modloaders/modpacks/ModItemAdapter.java
package net.kdt.pojavlaunch.modloaders.modpacks; import android.annotation.SuppressLint; import android.content.res.Resources; import android.graphics.Bitmap; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewStub; import android.widget.Button; import android.widget.ImageView; import android.widget.Spinner; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.constraintlayout.widget.ConstraintLayout; import androidx.core.graphics.drawable.RoundedBitmapDrawable; import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory; import androidx.recyclerview.widget.RecyclerView; import com.kdt.SimpleArrayAdapter; import net.kdt.pojavlaunch.PojavApplication; import net.kdt.pojavlaunch.R; import net.kdt.pojavlaunch.Tools; import net.kdt.pojavlaunch.modloaders.modpacks.api.ModpackApi; import net.kdt.pojavlaunch.modloaders.modpacks.imagecache.ImageReceiver; import net.kdt.pojavlaunch.modloaders.modpacks.imagecache.ModIconCache; import net.kdt.pojavlaunch.modloaders.modpacks.models.Constants; import net.kdt.pojavlaunch.modloaders.modpacks.models.ModDetail; import net.kdt.pojavlaunch.modloaders.modpacks.models.ModItem; import net.kdt.pojavlaunch.modloaders.modpacks.models.SearchFilters; import net.kdt.pojavlaunch.modloaders.modpacks.models.SearchResult; import net.kdt.pojavlaunch.progresskeeper.TaskCountListener; import java.util.Arrays; import java.util.Collections; import java.util.Set; import java.util.WeakHashMap; import java.util.concurrent.Future; public class ModItemAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements TaskCountListener { private static final ModItem[] MOD_ITEMS_EMPTY = new ModItem[0]; private static final int VIEW_TYPE_MOD_ITEM = 0; private static final int VIEW_TYPE_LOADING = 1; /* Used when versions haven't loaded yet, default text to reduce layout shifting */ private final SimpleArrayAdapter<String> mLoadingAdapter = new SimpleArrayAdapter<>(Collections.singletonList("Loading")); /* This my seem horribly inefficient but it is in fact the most efficient way without effectively writing a weak collection from scratch */ private final Set<ViewHolder> mViewHolderSet = Collections.newSetFromMap(new WeakHashMap<>()); private final ModIconCache mIconCache = new ModIconCache(); private final SearchResultCallback mSearchResultCallback; private ModItem[] mModItems; private final ModpackApi mModpackApi; /* Cache for ever so slightly rounding the image for the corner not to stick out of the layout */ private final float mCornerDimensionCache; private Future<?> mTaskInProgress; private SearchFilters mSearchFilters; private SearchResult mCurrentResult; private boolean mLastPage; private boolean mTasksRunning; public ModItemAdapter(Resources resources, ModpackApi api, SearchResultCallback callback) { mCornerDimensionCache = resources.getDimension(R.dimen._1sdp) / 250; mModpackApi = api; mModItems = new ModItem[]{}; mSearchResultCallback = callback; } public void performSearchQuery(SearchFilters searchFilters) { if(mTaskInProgress != null) { mTaskInProgress.cancel(true); mTaskInProgress = null; } this.mSearchFilters = searchFilters; this.mLastPage = false; mTaskInProgress = new SelfReferencingFuture(new SearchApiTask(mSearchFilters, null)) .startOnExecutor(PojavApplication.sExecutorService); } @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) { LayoutInflater layoutInflater = LayoutInflater.from(viewGroup.getContext()); View view; switch (viewType) { case VIEW_TYPE_MOD_ITEM: // Create a new view, which defines the UI of the list item view = layoutInflater.inflate(R.layout.view_mod, viewGroup, false); return new ViewHolder(view); case VIEW_TYPE_LOADING: // Create a new view, which is actually just the progress bar view = layoutInflater.inflate(R.layout.view_loading, viewGroup, false); return new LoadingViewHolder(view); default: throw new RuntimeException("Unimplemented view type!"); } } @Override public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) { switch (getItemViewType(position)) { case VIEW_TYPE_MOD_ITEM: ((ModItemAdapter.ViewHolder)holder).setStateLimited(mModItems[position]); break; case VIEW_TYPE_LOADING: loadMoreResults(); break; default: throw new RuntimeException("Unimplemented view type!"); } } @Override public int getItemCount() { if(mLastPage || mModItems.length == 0) return mModItems.length; return mModItems.length+1; } private void loadMoreResults() { if(mTaskInProgress != null) return; mTaskInProgress = new SelfReferencingFuture(new SearchApiTask(mSearchFilters, mCurrentResult)) .startOnExecutor(PojavApplication.sExecutorService); } @Override public int getItemViewType(int position) { if(position < mModItems.length) return VIEW_TYPE_MOD_ITEM; return VIEW_TYPE_LOADING; } @Override public void onUpdateTaskCount(int taskCount) { Tools.runOnUiThread(()->{ mTasksRunning = taskCount != 0; for(ViewHolder viewHolder : mViewHolderSet) { viewHolder.updateInstallButtonState(); } }); } /** * Basic viewholder with expension capabilities */ public class ViewHolder extends RecyclerView.ViewHolder { private ModDetail mModDetail = null; private ModItem mModItem = null; private final TextView mTitle, mDescription; private final ImageView mIconView, mSourceView; private View mExtendedLayout; private Spinner mExtendedSpinner; private Button mExtendedButton; private TextView mExtendedErrorTextView; private Future<?> mExtensionFuture; private Bitmap mThumbnailBitmap; private ImageReceiver mImageReceiver; private boolean mInstallEnabled; /* Used to display available versions of the mod(pack) */ private final SimpleArrayAdapter<String> mVersionAdapter = new SimpleArrayAdapter<>(null); public ViewHolder(View view) { super(view); mViewHolderSet.add(this); view.setOnClickListener(v -> { if(!hasExtended()){ // Inflate the ViewStub mExtendedLayout = ((ViewStub)v.findViewById(R.id.mod_limited_state_stub)).inflate(); mExtendedButton = mExtendedLayout.findViewById(R.id.mod_extended_select_version_button); mExtendedSpinner = mExtendedLayout.findViewById(R.id.mod_extended_version_spinner); mExtendedErrorTextView = mExtendedLayout.findViewById(R.id.mod_extended_error_textview); mExtendedButton.setOnClickListener(v1 -> mModpackApi.handleInstallation( mExtendedButton.getContext().getApplicationContext(), mModDetail, mExtendedSpinner.getSelectedItemPosition())); mExtendedSpinner.setAdapter(mLoadingAdapter); } else { if(isExtended()) closeDetailedView(); else openDetailedView(); } if(isExtended() && mModDetail == null && mExtensionFuture == null) { // only reload if no reloads are in progress setDetailedStateDefault(); /* * Why do we do this? * The reason is simple: multithreading is difficult as hell to manage * Let me explain: */ mExtensionFuture = new SelfReferencingFuture(myFuture -> { /* * While we are sitting in the function below doing networking, the view might have already gotten recycled. * If we didn't use a Future, we would have extended a ViewHolder with completely unrelated content * or with an error that has never actually happened */ mModDetail = mModpackApi.getModDetails(mModItem); System.out.println(mModDetail); Tools.runOnUiThread(() -> { /* * Once we enter here, the state we're in is already defined - no view shuffling can happen on the UI * thread while we are on the UI thread ourselves. If we were cancelled, this means that the future * we were supposed to have no longer makes sense, so we return and do not alter the state (since we might * alter the state of an unrelated item otherwise) */ if(myFuture.isCancelled()) return; /* * We do not null the future before returning since this field might already belong to a different item with its * own Future, which we don't want to interfere with. * But if the future is not cancelled, it is the right one for this ViewHolder, and we don't need it anymore, so * let's help GC clean it up once we exit! */ mExtensionFuture = null; setStateDetailed(mModDetail); }); }).startOnExecutor(PojavApplication.sExecutorService); } }); // Define click listener for the ViewHolder's View mTitle = view.findViewById(R.id.mod_title_textview); mDescription = view.findViewById(R.id.mod_body_textview); mIconView = view.findViewById(R.id.mod_thumbnail_imageview); mSourceView = view.findViewById(R.id.mod_source_imageview); } /** Display basic info about the moditem */ public void setStateLimited(ModItem item) { mModDetail = null; if(mThumbnailBitmap != null) { mIconView.setImageBitmap(null); mThumbnailBitmap.recycle(); } if(mImageReceiver != null) { mIconCache.cancelImage(mImageReceiver); } if(mExtensionFuture != null) { /* * Since this method reinitializes the ViewHolder for a new mod, this Future stops being ours, so we cancel it * and null it. The rest is handled above */ mExtensionFuture.cancel(true); mExtensionFuture = null; } mModItem = item; // here the previous reference to the image receiver will disappear mImageReceiver = bm->{ mImageReceiver = null; mThumbnailBitmap = bm; RoundedBitmapDrawable drawable = RoundedBitmapDrawableFactory.create(mIconView.getResources(), bm); drawable.setCornerRadius(mCornerDimensionCache * bm.getHeight()); mIconView.setImageDrawable(drawable); }; mIconCache.getImage(mImageReceiver, mModItem.getIconCacheTag(), mModItem.imageUrl); mSourceView.setImageResource(getSourceDrawable(item.apiSource)); mTitle.setText(item.title); mDescription.setText(item.description); if(hasExtended()){ closeDetailedView(); } } /** Display extended info/interaction about a modpack */ private void setStateDetailed(ModDetail detailedItem) { if(detailedItem != null) { setInstallEnabled(true); mExtendedErrorTextView.setVisibility(View.GONE); mVersionAdapter.setObjects(Arrays.asList(detailedItem.versionNames)); mExtendedSpinner.setAdapter(mVersionAdapter); } else { closeDetailedView(); setInstallEnabled(false); mExtendedErrorTextView.setVisibility(View.VISIBLE); mExtendedSpinner.setAdapter(null); mVersionAdapter.setObjects(null); } } private void openDetailedView() { mExtendedLayout.setVisibility(View.VISIBLE); mDescription.setMaxLines(99); // We need to align to the longer section int futureBottom = mDescription.getBottom() + Tools.mesureTextviewHeight(mDescription) - mDescription.getHeight(); ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) mExtendedLayout.getLayoutParams(); params.topToBottom = futureBottom > mIconView.getBottom() ? R.id.mod_body_textview : R.id.mod_thumbnail_imageview; mExtendedLayout.setLayoutParams(params); } private void closeDetailedView(){ mExtendedLayout.setVisibility(View.GONE); mDescription.setMaxLines(3); } private void setDetailedStateDefault() { setInstallEnabled(false); mExtendedSpinner.setAdapter(mLoadingAdapter); mExtendedErrorTextView.setVisibility(View.GONE); openDetailedView(); } private boolean hasExtended(){ return mExtendedLayout != null; } private boolean isExtended(){ return hasExtended() && mExtendedLayout.getVisibility() == View.VISIBLE; } private int getSourceDrawable(int apiSource) { switch (apiSource) { case Constants.SOURCE_CURSEFORGE: return R.drawable.ic_curseforge; case Constants.SOURCE_MODRINTH: return R.drawable.ic_modrinth; default: throw new RuntimeException("Unknown API source"); } } private void setInstallEnabled(boolean enabled) { mInstallEnabled = enabled; updateInstallButtonState(); } private void updateInstallButtonState() { if(mExtendedButton != null) mExtendedButton.setEnabled(mInstallEnabled && !mTasksRunning); } } /** * The view holder used to hold the progress bar at the end of the list */ private static class LoadingViewHolder extends RecyclerView.ViewHolder { public LoadingViewHolder(View view) { super(view); } } private class SearchApiTask implements SelfReferencingFuture.FutureInterface { private final SearchFilters mSearchFilters; private final SearchResult mPreviousResult; private SearchApiTask(SearchFilters searchFilters, SearchResult previousResult) { this.mSearchFilters = searchFilters; this.mPreviousResult = previousResult; } @SuppressLint("NotifyDataSetChanged") @Override public void run(Future<?> myFuture) { SearchResult result = mModpackApi.searchMod(mSearchFilters, mPreviousResult); ModItem[] resultModItems = result != null ? result.results : null; if(resultModItems != null && resultModItems.length != 0 && mPreviousResult != null) { ModItem[] newModItems = new ModItem[resultModItems.length + mModItems.length]; System.arraycopy(mModItems, 0, newModItems, 0, mModItems.length); System.arraycopy(resultModItems, 0, newModItems, mModItems.length, resultModItems.length); resultModItems = newModItems; } ModItem[] finalModItems = resultModItems; Tools.runOnUiThread(() -> { if(myFuture.isCancelled()) return; mTaskInProgress = null; if(finalModItems == null) { mSearchResultCallback.onSearchError(SearchResultCallback.ERROR_INTERNAL); }else if(finalModItems.length == 0) { if(mPreviousResult != null) { mLastPage = true; notifyItemChanged(mModItems.length); mSearchResultCallback.onSearchFinished(); return; } mSearchResultCallback.onSearchError(SearchResultCallback.ERROR_NO_RESULTS); }else{ mSearchResultCallback.onSearchFinished(); } mCurrentResult = result; if(finalModItems == null) { mModItems = MOD_ITEMS_EMPTY; notifyDataSetChanged(); return; } if(mPreviousResult != null) { int prevLength = mModItems.length; mModItems = finalModItems; notifyItemChanged(prevLength); notifyItemRangeInserted(prevLength+1, mModItems.length); }else { mModItems = finalModItems; notifyDataSetChanged(); } }); } } public interface SearchResultCallback { int ERROR_INTERNAL = 0; int ERROR_NO_RESULTS = 1; void onSearchFinished(); void onSearchError(int error); } }
17,961
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
ModloaderInstallTracker.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/modloaders/modpacks/ModloaderInstallTracker.java
package net.kdt.pojavlaunch.modloaders.modpacks; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import net.kdt.pojavlaunch.modloaders.modpacks.api.ModLoader; import java.io.File; /** * This class is meant to track the availability of a modloader that is ready to be installed (as a result of modpack installation) * It is needed because having all this logic spread over LauncherActivity would be clumsy, and I think that this is the best way to * ensure that the modloader installer will run, even if the user does not receive the notification or something else happens */ public class ModloaderInstallTracker implements SharedPreferences.OnSharedPreferenceChangeListener { private final SharedPreferences mSharedPreferences; private final Activity mActivity; /** * Create a ModInstallTracker object. This must be done in the Activity's onCreate method. * @param activity the host activity */ public ModloaderInstallTracker(Activity activity) { mActivity = activity; mSharedPreferences = getPreferences(activity); } /** * Attach the ModloaderInstallTracker to the current Activity. Must be done in the Activity's * onResume method */ public void attach() { mSharedPreferences.registerOnSharedPreferenceChangeListener(this); runCheck(); } /** * Detach the ModloaderInstallTracker from the current Activity. Must be done in the Activity's * onPause method */ public void detach() { mSharedPreferences.unregisterOnSharedPreferenceChangeListener(this); } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String prefName) { if(!"modLoaderAvailable".equals(prefName)) return; runCheck(); } @SuppressLint("ApplySharedPref") private void runCheck() { if(!mSharedPreferences.getBoolean("modLoaderAvailable", false)) return; SharedPreferences.Editor editor = mSharedPreferences.edit().putBoolean("modLoaderAvailable", false); if(!editor.commit()) editor.apply(); ModLoader modLoader = deserializeModLoader(mSharedPreferences); File modInstallFile = deserializeInstallFile(mSharedPreferences); if(modLoader == null || modInstallFile == null) return; startModInstallation(modLoader, modInstallFile); } private void startModInstallation(ModLoader modLoader, File modInstallFile) { Intent installIntent = modLoader.getInstallationIntent(mActivity, modInstallFile); mActivity.startActivity(installIntent); } private static SharedPreferences getPreferences(Context context) { return context.getSharedPreferences("modloader_info", Context.MODE_PRIVATE); } /** * Store the data necessary to start a ModLoader installation for the tracker to start the installer * sometime. * @param context the Context * @param modLoader the ModLoader to store * @param modInstallFile the installer jar to store */ @SuppressLint("ApplySharedPref") public static void saveModLoader(Context context, ModLoader modLoader, File modInstallFile) { SharedPreferences.Editor editor = getPreferences(context).edit(); editor.putInt("modLoaderType", modLoader.modLoaderType); editor.putString("modLoaderVersion", modLoader.modLoaderVersion); editor.putString("minecraftVersion", modLoader.minecraftVersion); editor.putString("modInstallerJar", modInstallFile.getAbsolutePath()); editor.putBoolean("modLoaderAvailable", true); editor.commit(); } private static ModLoader deserializeModLoader(SharedPreferences sharedPreferences) { if(!sharedPreferences.contains("modLoaderType") || !sharedPreferences.contains("modLoaderVersion") || !sharedPreferences.contains("minecraftVersion")) return null; return new ModLoader(sharedPreferences.getInt("modLoaderType", -1), sharedPreferences.getString("modLoaderVersion", ""), sharedPreferences.getString("minecraftVersion", "")); } private static File deserializeInstallFile(SharedPreferences sharedPreferences) { if(!sharedPreferences.contains("modInstallerJar")) return null; return new File(sharedPreferences.getString("modInstallerJar", "")); } }
4,491
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
ModrinthIndex.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/modloaders/modpacks/models/ModrinthIndex.java
package net.kdt.pojavlaunch.modloaders.modpacks.models; import androidx.annotation.NonNull; import org.jetbrains.annotations.Nullable; import java.util.Arrays; import java.util.Map; /** * POJO to represent the modrinth index inside mrpacks */ public class ModrinthIndex { public int formatVersion; public String game; public String versionId; public String name; public String summary; public ModrinthIndexFile[] files; public Map<String, String> dependencies; public static class ModrinthIndexFile { public String path; public String[] downloads; public int fileSize; public ModrinthIndexFileHashes hashes; @Nullable public ModrinthIndexFileEnv env; @NonNull @Override public String toString() { return "ModrinthIndexFile{" + "path='" + path + '\'' + ", downloads=" + Arrays.toString(downloads) + ", fileSize=" + fileSize + ", hashes=" + hashes + '}'; } public static class ModrinthIndexFileHashes { public String sha1; public String sha512; @NonNull @Override public String toString() { return "ModrinthIndexFileHashes{" + "sha1='" + sha1 + '\'' + ", sha512='" + sha512 + '\'' + '}'; } } public static class ModrinthIndexFileEnv { public String client; public String server; @NonNull @Override public String toString() { return "ModrinthIndexFileEnv{" + "client='" + client + '\'' + ", server='" + server + '\'' + '}'; } } } @NonNull @Override public String toString() { return "ModrinthIndex{" + "formatVersion=" + formatVersion + ", game='" + game + '\'' + ", versionId='" + versionId + '\'' + ", name='" + name + '\'' + ", summary='" + summary + '\'' + ", files=" + Arrays.toString(files) + '}'; } }
2,334
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
SearchResult.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/modloaders/modpacks/models/SearchResult.java
package net.kdt.pojavlaunch.modloaders.modpacks.models; public class SearchResult { public int totalResultCount; public ModItem[] results; }
150
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
SearchFilters.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/modloaders/modpacks/models/SearchFilters.java
package net.kdt.pojavlaunch.modloaders.modpacks.models; import org.jetbrains.annotations.Nullable; /** * Search filters, passed to APIs */ public class SearchFilters { public boolean isModpack; public String name; @Nullable public String mcVersion; }
268
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
ModDetail.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/modloaders/modpacks/models/ModDetail.java
package net.kdt.pojavlaunch.modloaders.modpacks.models; import androidx.annotation.NonNull; import java.util.Arrays; public class ModDetail extends ModItem { /* A cheap way to map from the front facing name to the underlying id */ public String[] versionNames; public String [] mcVersionNames; public String[] versionUrls; /* SHA 1 hashes, null if a hash is unavailable */ public String[] versionHashes; public ModDetail(ModItem item, String[] versionNames, String[] mcVersionNames, String[] versionUrls, String[] hashes) { super(item.apiSource, item.isModpack, item.id, item.title, item.description, item.imageUrl); this.versionNames = versionNames; this.mcVersionNames = mcVersionNames; this.versionUrls = versionUrls; this.versionHashes = hashes; // Add the mc version to the version model for (int i=0; i<versionNames.length; i++){ if (!versionNames[i].contains(mcVersionNames[i])) versionNames[i] += " - " + mcVersionNames[i]; } } @NonNull @Override public String toString() { return "ModDetail{" + "versionNames=" + Arrays.toString(versionNames) + ", mcVersionNames=" + Arrays.toString(mcVersionNames) + ", versionIds=" + Arrays.toString(versionUrls) + ", id='" + id + '\'' + ", title='" + title + '\'' + ", description='" + description + '\'' + ", imageUrl='" + imageUrl + '\'' + ", apiSource=" + apiSource + ", isModpack=" + isModpack + '}'; } }
1,668
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
Constants.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/modloaders/modpacks/models/Constants.java
package net.kdt.pojavlaunch.modloaders.modpacks.models; public class Constants { private Constants(){} /** Types of modpack apis */ public static final int SOURCE_MODRINTH = 0x0; public static final int SOURCE_CURSEFORGE = 0x1; public static final int SOURCE_TECHNIC = 0x2; /** Modrinth api, file environments */ public static final String MODRINTH_FILE_ENV_REQUIRED = "required"; public static final String MODRINTH_FILE_ENV_OPTIONAL = "optional"; public static final String MODRINTH_FILE_ENV_UNSUPPORTED = "unsupported"; }
565
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
ModSource.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/modloaders/modpacks/models/ModSource.java
package net.kdt.pojavlaunch.modloaders.modpacks.models; public abstract class ModSource { public int apiSource; public boolean isModpack; }
149
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
ModItem.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/modloaders/modpacks/models/ModItem.java
package net.kdt.pojavlaunch.modloaders.modpacks.models; import androidx.annotation.NonNull; public class ModItem extends ModSource { public String id; public String title; public String description; public String imageUrl; public ModItem(int apiSource, boolean isModpack, String id, String title, String description, String imageUrl) { this.apiSource = apiSource; this.isModpack = isModpack; this.id = id; this.title = title; this.description = description; this.imageUrl = imageUrl; } @NonNull @Override public String toString() { return "ModItem{" + "id='" + id + '\'' + ", title='" + title + '\'' + ", description='" + description + '\'' + ", imageUrl='" + imageUrl + '\'' + ", apiSource=" + apiSource + ", isModpack=" + isModpack + '}'; } public String getIconCacheTag() { return apiSource+"_"+id; } }
1,036
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
CurseManifest.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/modloaders/modpacks/models/CurseManifest.java
package net.kdt.pojavlaunch.modloaders.modpacks.models; public class CurseManifest { public String name; public String version; public String author; public String manifestType; public int manifestVersion; public CurseFile[] files; public CurseMinecraft minecraft; public String overrides; public static class CurseFile { public long projectID; public long fileID; public boolean required; } public static class CurseMinecraft { public String version; public CurseModLoader[] modLoaders; } public static class CurseModLoader { public String id; public boolean primary; } }
686
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
ReadFromDiskTask.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/modloaders/modpacks/imagecache/ReadFromDiskTask.java
package net.kdt.pojavlaunch.modloaders.modpacks.imagecache; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import net.kdt.pojavlaunch.Tools; import java.io.File; public class ReadFromDiskTask implements Runnable { final ModIconCache iconCache; final ImageReceiver imageReceiver; final File cacheFile; final String imageUrl; ReadFromDiskTask(ModIconCache iconCache, ImageReceiver imageReceiver, String cacheTag, String imageUrl) { this.iconCache = iconCache; this.imageReceiver = imageReceiver; this.cacheFile = new File(iconCache.cachePath, cacheTag+".ca"); this.imageUrl = imageUrl; } public void runDownloadTask() { iconCache.cacheLoaderPool.execute(new DownloadImageTask(this)); } @Override public void run() { if(cacheFile.isDirectory()) { return; } if(cacheFile.canRead()) { IconCacheJanitor.waitForJanitorToFinish(); Bitmap bitmap = BitmapFactory.decodeFile(cacheFile.getAbsolutePath()); if(bitmap != null) { Tools.runOnUiThread(()->{ if(taskCancelled()) { bitmap.recycle(); // do not leak the bitmap if the task got cancelled right at the end return; } imageReceiver.onImageAvailable(bitmap); }); return; } } if(iconCache.cachePath.canWrite() && !taskCancelled()) { // don't run the download task if the task got canceled runDownloadTask(); } } @SuppressWarnings("BooleanMethodAlwaysInverted") public boolean taskCancelled() { return iconCache.checkCancelled(imageReceiver); } }
1,813
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
DownloadImageTask.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/modloaders/modpacks/imagecache/DownloadImageTask.java
package net.kdt.pojavlaunch.modloaders.modpacks.imagecache; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import net.kdt.pojavlaunch.utils.DownloadUtils; import java.io.FileOutputStream; import java.io.IOException; class DownloadImageTask implements Runnable { private static final float BITMAP_FINAL_DIMENSION = 256f; private final ReadFromDiskTask mParentTask; private int mRetryCount; DownloadImageTask(ReadFromDiskTask parentTask) { this.mParentTask = parentTask; this.mRetryCount = 0; } @Override public void run() { boolean wasSuccessful = false; while(mRetryCount < 5 && !(wasSuccessful = runCatching())) { mRetryCount++; } // restart the parent task to read the image and send it to the receiver // if it wasn't cancelled. If it was, then we just die here if(wasSuccessful && !mParentTask.taskCancelled()) mParentTask.iconCache.cacheLoaderPool.execute(mParentTask); } public boolean runCatching() { try { IconCacheJanitor.waitForJanitorToFinish(); DownloadUtils.downloadFile(mParentTask.imageUrl, mParentTask.cacheFile); Bitmap bitmap = BitmapFactory.decodeFile(mParentTask.cacheFile.getAbsolutePath()); if(bitmap == null) return false; int bitmapWidth = bitmap.getWidth(), bitmapHeight = bitmap.getHeight(); if(bitmapWidth <= BITMAP_FINAL_DIMENSION && bitmapHeight <= BITMAP_FINAL_DIMENSION) { bitmap.recycle(); return true; } float imageRescaleRatio = Math.min(BITMAP_FINAL_DIMENSION/bitmapWidth, BITMAP_FINAL_DIMENSION/bitmapHeight); Bitmap resizedBitmap = Bitmap.createScaledBitmap(bitmap, (int)(bitmapWidth * imageRescaleRatio), (int)(bitmapHeight * imageRescaleRatio), true); bitmap.recycle(); if(resizedBitmap == bitmap) return true; try (FileOutputStream fileOutputStream = new FileOutputStream(mParentTask.cacheFile)) { resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 80, fileOutputStream); } finally { resizedBitmap.recycle(); } return true; }catch (IOException e) { e.printStackTrace(); return false; } } }
2,440
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
ImageReceiver.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/modloaders/modpacks/imagecache/ImageReceiver.java
package net.kdt.pojavlaunch.modloaders.modpacks.imagecache; import android.graphics.Bitmap; /** * ModIconCache will call your view back when the image becomes available with this interface */ public interface ImageReceiver { void onImageAvailable(Bitmap image); }
272
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
ModIconCache.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/modloaders/modpacks/imagecache/ModIconCache.java
package net.kdt.pojavlaunch.modloaders.modpacks.imagecache; import android.util.Base64; import android.util.Log; import net.kdt.pojavlaunch.Tools; import org.apache.commons.io.IOUtils; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class ModIconCache { ThreadPoolExecutor cacheLoaderPool = new ThreadPoolExecutor(10, 10, 1000, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>()); File cachePath; private final List<WeakReference<ImageReceiver>> mCancelledReceivers = new ArrayList<>(); public ModIconCache() { cachePath = getImageCachePath(); if(!cachePath.exists() && !cachePath.isFile() && Tools.DIR_CACHE.canWrite()) { if(!cachePath.mkdirs()) throw new RuntimeException("Failed to create icon cache directory"); } } static File getImageCachePath() { return new File(Tools.DIR_CACHE, "mod_icons"); } /** * Get an image for a mod with the associated tag and URL to download it in case if its not cached * @param imageReceiver the receiver interface that would get called when the image loads * @param imageTag the tag of the image to keep track of it * @param imageUrl the URL of the image in case if it's not cached */ public void getImage(ImageReceiver imageReceiver, String imageTag, String imageUrl) { cacheLoaderPool.execute(new ReadFromDiskTask(this, imageReceiver, imageTag, imageUrl)); } /** * Mark the image obtainment task requested with this receiver as "cancelled". This means that * this receiver will not be called back and that some tasks related to this image may be * prevented from happening or interrupted. * @param imageReceiver the receiver to cancel */ public void cancelImage(ImageReceiver imageReceiver) { synchronized (mCancelledReceivers) { mCancelledReceivers.add(new WeakReference<>(imageReceiver)); } } boolean checkCancelled(ImageReceiver imageReceiver) { boolean isCanceled = false; synchronized (mCancelledReceivers) { Iterator<WeakReference<ImageReceiver>> iterator = mCancelledReceivers.iterator(); while (iterator.hasNext()) { WeakReference<ImageReceiver> reference = iterator.next(); if (reference.get() == null) { iterator.remove(); continue; } if(reference.get() == imageReceiver) { isCanceled = true; } } } if(isCanceled) Log.i("IconCache", "checkCancelled("+imageReceiver.hashCode()+") == true"); return isCanceled; } /** * Get the base64-encoded version of a cached icon by its tag. * Note: this functions performs I/O operations, and should not be called on the UI * thread. * @param imageTag the icon tag * @return the base64 encoded image or null if not cached */ public static String getBase64Image(String imageTag) { File imagePath = new File(Tools.DIR_CACHE, "mod_icons/"+imageTag+".ca"); Log.i("IconCache", "Creating base64 version of icon "+imageTag); if(!imagePath.canRead() || !imagePath.isFile()) { Log.i("IconCache", "Icon does not exist"); return null; } try { try(FileInputStream fileInputStream = new FileInputStream(imagePath)) { byte[] imageBytes = IOUtils.toByteArray(fileInputStream); // reencode to png? who cares! our profile icon cache is an omnivore! // if some other launcher parses this and dies it is not our problem :troll: return "data:image/png;base64,"+ Base64.encodeToString(imageBytes, Base64.DEFAULT); } }catch (IOException e) { e.printStackTrace(); return null; } } }
4,249
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
IconCacheJanitor.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/modloaders/modpacks/imagecache/IconCacheJanitor.java
package net.kdt.pojavlaunch.modloaders.modpacks.imagecache; import android.util.Log; import net.kdt.pojavlaunch.PojavApplication; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; /** * This image is intended to keep the mod icon cache tidy (aka under 100 megabytes) */ public class IconCacheJanitor implements Runnable{ public static final long CACHE_SIZE_LIMIT = 104857600; // The cache size limit, 100 megabytes public static final long CACHE_BRINGDOWN = 52428800; // The size to which the cache should be brought // in case of an overflow, 50 mb private static Future<?> sJanitorFuture; private static boolean sJanitorRan = false; private IconCacheJanitor() { // don't allow others to create this } @Override public void run() { File modIconCachePath = ModIconCache.getImageCachePath(); if(!modIconCachePath.isDirectory() || !modIconCachePath.canRead()) return; File[] modIconFiles = modIconCachePath.listFiles(); if(modIconFiles == null) return; ArrayList<File> writableModIconFiles = new ArrayList<>(modIconFiles.length); long directoryFileSize = 0; for(File modIconFile : modIconFiles) { if(!modIconFile.isFile() || !modIconFile.canRead()) continue; directoryFileSize += modIconFile.length(); if(!modIconFile.canWrite()) continue; writableModIconFiles.add(modIconFile); } if(directoryFileSize < CACHE_SIZE_LIMIT) { Log.i("IconCacheJanitor", "Skipping cleanup because there's not enough to clean up"); return; } Arrays.sort(modIconFiles, (x,y)-> Long.compare(y.lastModified(), x.lastModified()) ); int filesCleanedUp = 0; for(File modFile : writableModIconFiles) { if(directoryFileSize < CACHE_BRINGDOWN) break; long modFileSize = modFile.length(); if(modFile.delete()) { directoryFileSize -= modFileSize; filesCleanedUp++; } } Log.i("IconCacheJanitor", "Cleaned up "+filesCleanedUp+ " files"); synchronized (IconCacheJanitor.class) { sJanitorFuture = null; sJanitorRan = true; } } /** * Runs the janitor task, unless there was one running already or one has ran already */ public static void runJanitor() { synchronized (IconCacheJanitor.class) { if (sJanitorFuture != null || sJanitorRan) return; sJanitorFuture = PojavApplication.sExecutorService.submit(new IconCacheJanitor()); } } /** * Waits for the janitor task to finish, if there is one running already * Note that the thread waiting must not be interrupted. */ public static void waitForJanitorToFinish() { synchronized (IconCacheJanitor.class) { if (sJanitorFuture == null) return; try { sJanitorFuture.get(); } catch (ExecutionException | InterruptedException e) { throw new RuntimeException("Should not happen!", e); } } } }
3,280
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
ModpackApi.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/modloaders/modpacks/api/ModpackApi.java
package net.kdt.pojavlaunch.modloaders.modpacks.api; import android.content.Context; import com.kdt.mcgui.ProgressLayout; import net.kdt.pojavlaunch.PojavApplication; import net.kdt.pojavlaunch.R; import net.kdt.pojavlaunch.Tools; import net.kdt.pojavlaunch.modloaders.modpacks.models.ModDetail; import net.kdt.pojavlaunch.modloaders.modpacks.models.ModItem; import net.kdt.pojavlaunch.modloaders.modpacks.models.SearchFilters; import net.kdt.pojavlaunch.modloaders.modpacks.models.SearchResult; import java.io.IOException; /** * */ public interface ModpackApi { /** * @param searchFilters Filters * @param previousPageResult The result from the previous page * @return the list of mod items from specified offset */ SearchResult searchMod(SearchFilters searchFilters, SearchResult previousPageResult); /** * @param searchFilters Filters * @return A list of mod items */ default SearchResult searchMod(SearchFilters searchFilters) { return searchMod(searchFilters, null); } /** * Fetch the mod details * @param item The moditem that was selected * @return Detailed data about a mod(pack) */ ModDetail getModDetails(ModItem item); /** * Download and install the mod(pack) * @param modDetail The mod detail data * @param selectedVersion The selected version */ default void handleInstallation(Context context, ModDetail modDetail, int selectedVersion) { // Doing this here since when starting installation, the progress does not start immediately // which may lead to two concurrent installations (very bad) ProgressLayout.setProgress(ProgressLayout.INSTALL_MODPACK, 0, R.string.global_waiting); PojavApplication.sExecutorService.execute(() -> { try { ModLoader loaderInfo = installMod(modDetail, selectedVersion); if (loaderInfo == null) return; loaderInfo.getDownloadTask(new NotificationDownloadListener(context, loaderInfo)).run(); }catch (IOException e) { Tools.showErrorRemote(context, R.string.modpack_install_download_failed, e); } }); } /** * Install the mod(pack). * May require the download of additional files. * May requires launching the installation of a modloader * @param modDetail The mod detail data * @param selectedVersion The selected version */ ModLoader installMod(ModDetail modDetail, int selectedVersion) throws IOException; }
2,565
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
ModrinthApi.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/modloaders/modpacks/api/ModrinthApi.java
package net.kdt.pojavlaunch.modloaders.modpacks.api; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.kdt.mcgui.ProgressLayout; import net.kdt.pojavlaunch.R; import net.kdt.pojavlaunch.Tools; import net.kdt.pojavlaunch.modloaders.modpacks.models.Constants; import net.kdt.pojavlaunch.modloaders.modpacks.models.ModDetail; import net.kdt.pojavlaunch.modloaders.modpacks.models.ModItem; import net.kdt.pojavlaunch.modloaders.modpacks.models.ModrinthIndex; import net.kdt.pojavlaunch.modloaders.modpacks.models.SearchFilters; import net.kdt.pojavlaunch.modloaders.modpacks.models.SearchResult; import net.kdt.pojavlaunch.progresskeeper.DownloaderProgressWrapper; import net.kdt.pojavlaunch.utils.ZipUtils; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.zip.ZipFile; public class ModrinthApi implements ModpackApi{ private final ApiHandler mApiHandler; public ModrinthApi(){ mApiHandler = new ApiHandler("https://api.modrinth.com/v2"); } @Override public SearchResult searchMod(SearchFilters searchFilters, SearchResult previousPageResult) { ModrinthSearchResult modrinthSearchResult = (ModrinthSearchResult) previousPageResult; HashMap<String, Object> params = new HashMap<>(); // Build the facets filters StringBuilder facetString = new StringBuilder(); facetString.append("["); facetString.append(String.format("[\"project_type:%s\"]", searchFilters.isModpack ? "modpack" : "mod")); if(searchFilters.mcVersion != null && !searchFilters.mcVersion.isEmpty()) facetString.append(String.format(",[\"versions:%s\"]", searchFilters.mcVersion)); facetString.append("]"); params.put("facets", facetString.toString()); params.put("query", searchFilters.name.replace(' ', '+')); params.put("limit", 50); params.put("index", "relevance"); if(modrinthSearchResult != null) params.put("offset", modrinthSearchResult.previousOffset); JsonObject response = mApiHandler.get("search", params, JsonObject.class); if(response == null) return null; JsonArray responseHits = response.getAsJsonArray("hits"); if(responseHits == null) return null; ModItem[] items = new ModItem[responseHits.size()]; for(int i=0; i<responseHits.size(); ++i){ JsonObject hit = responseHits.get(i).getAsJsonObject(); items[i] = new ModItem( Constants.SOURCE_MODRINTH, hit.get("project_type").getAsString().equals("modpack"), hit.get("project_id").getAsString(), hit.get("title").getAsString(), hit.get("description").getAsString(), hit.get("icon_url").getAsString() ); } if(modrinthSearchResult == null) modrinthSearchResult = new ModrinthSearchResult(); modrinthSearchResult.previousOffset += responseHits.size(); modrinthSearchResult.results = items; modrinthSearchResult.totalResultCount = response.get("total_hits").getAsInt(); return modrinthSearchResult; } @Override public ModDetail getModDetails(ModItem item) { JsonArray response = mApiHandler.get(String.format("project/%s/version", item.id), JsonArray.class); if(response == null) return null; System.out.println(response); String[] names = new String[response.size()]; String[] mcNames = new String[response.size()]; String[] urls = new String[response.size()]; String[] hashes = new String[response.size()]; for (int i=0; i<response.size(); ++i) { JsonObject version = response.get(i).getAsJsonObject(); names[i] = version.get("name").getAsString(); mcNames[i] = version.get("game_versions").getAsJsonArray().get(0).getAsString(); urls[i] = version.get("files").getAsJsonArray().get(0).getAsJsonObject().get("url").getAsString(); // Assume there may not be hashes, in case the API changes JsonObject hashesMap = version.getAsJsonArray("files").get(0).getAsJsonObject() .get("hashes").getAsJsonObject(); if(hashesMap == null || hashesMap.get("sha1") == null){ hashes[i] = null; continue; } hashes[i] = hashesMap.get("sha1").getAsString(); } return new ModDetail(item, names, mcNames, urls, hashes); } @Override public ModLoader installMod(ModDetail modDetail, int selectedVersion) throws IOException{ //TODO considering only modpacks for now return ModpackInstaller.installModpack(modDetail, selectedVersion, this::installMrpack); } private static ModLoader createInfo(ModrinthIndex modrinthIndex) { if(modrinthIndex == null) return null; Map<String, String> dependencies = modrinthIndex.dependencies; String mcVersion = dependencies.get("minecraft"); if(mcVersion == null) return null; String modLoaderVersion; if((modLoaderVersion = dependencies.get("forge")) != null) { return new ModLoader(ModLoader.MOD_LOADER_FORGE, modLoaderVersion, mcVersion); } if((modLoaderVersion = dependencies.get("fabric-loader")) != null) { return new ModLoader(ModLoader.MOD_LOADER_FABRIC, modLoaderVersion, mcVersion); } if((modLoaderVersion = dependencies.get("quilt-loader")) != null) { return new ModLoader(ModLoader.MOD_LOADER_QUILT, modLoaderVersion, mcVersion); } return null; } private ModLoader installMrpack(File mrpackFile, File instanceDestination) throws IOException { try (ZipFile modpackZipFile = new ZipFile(mrpackFile)){ ModrinthIndex modrinthIndex = Tools.GLOBAL_GSON.fromJson( Tools.read(ZipUtils.getEntryStream(modpackZipFile, "modrinth.index.json")), ModrinthIndex.class); ModDownloader modDownloader = new ModDownloader(instanceDestination); for(ModrinthIndex.ModrinthIndexFile indexFile : modrinthIndex.files) { modDownloader.submitDownload(indexFile.fileSize, indexFile.path, indexFile.hashes.sha1, indexFile.downloads); } modDownloader.awaitFinish(new DownloaderProgressWrapper(R.string.modpack_download_downloading_mods, ProgressLayout.INSTALL_MODPACK)); ProgressLayout.setProgress(ProgressLayout.INSTALL_MODPACK, 0, R.string.modpack_download_applying_overrides, 1, 2); ZipUtils.zipExtract(modpackZipFile, "overrides/", instanceDestination); ProgressLayout.setProgress(ProgressLayout.INSTALL_MODPACK, 50, R.string.modpack_download_applying_overrides, 2, 2); ZipUtils.zipExtract(modpackZipFile, "client-overrides/", instanceDestination); return createInfo(modrinthIndex); } } class ModrinthSearchResult extends SearchResult { int previousOffset; } }
7,153
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
ModpackInstaller.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/modloaders/modpacks/api/ModpackInstaller.java
package net.kdt.pojavlaunch.modloaders.modpacks.api; import com.kdt.mcgui.ProgressLayout; import net.kdt.pojavlaunch.R; import net.kdt.pojavlaunch.Tools; import net.kdt.pojavlaunch.modloaders.modpacks.imagecache.ModIconCache; import net.kdt.pojavlaunch.modloaders.modpacks.models.ModDetail; import net.kdt.pojavlaunch.progresskeeper.DownloaderProgressWrapper; import net.kdt.pojavlaunch.utils.DownloadUtils; import net.kdt.pojavlaunch.value.launcherprofiles.LauncherProfiles; import net.kdt.pojavlaunch.value.launcherprofiles.MinecraftProfile; import java.io.File; import java.io.IOException; import java.util.Locale; import java.util.concurrent.Callable; public class ModpackInstaller { public static ModLoader installModpack(ModDetail modDetail, int selectedVersion, InstallFunction installFunction) throws IOException { String versionUrl = modDetail.versionUrls[selectedVersion]; String versionHash = modDetail.versionHashes[selectedVersion]; String modpackName = modDetail.title.toLowerCase(Locale.ROOT).trim().replace(" ", "_" ); // Build a new minecraft instance, folder first // Get the modpack file File modpackFile = new File(Tools.DIR_CACHE, modpackName + ".cf"); // Cache File ModLoader modLoaderInfo; try { byte[] downloadBuffer = new byte[8192]; DownloadUtils.ensureSha1(modpackFile, versionHash, (Callable<Void>) () -> { DownloadUtils.downloadFileMonitored(versionUrl, modpackFile, downloadBuffer, new DownloaderProgressWrapper(R.string.modpack_download_downloading_metadata, ProgressLayout.INSTALL_MODPACK)); return null; }); // Install the modpack modLoaderInfo = installFunction.installModpack(modpackFile, new File(Tools.DIR_GAME_HOME, "custom_instances/"+modpackName)); } finally { modpackFile.delete(); ProgressLayout.clearProgress(ProgressLayout.INSTALL_MODPACK); } if(modLoaderInfo == null) { return null; } // Create the instance MinecraftProfile profile = new MinecraftProfile(); profile.gameDir = "./custom_instances/" + modpackName; profile.name = modDetail.title; profile.lastVersionId = modLoaderInfo.getVersionId(); profile.icon = ModIconCache.getBase64Image(modDetail.getIconCacheTag()); LauncherProfiles.mainProfileJson.profiles.put(modpackName, profile); LauncherProfiles.write(); return modLoaderInfo; } interface InstallFunction { ModLoader installModpack(File modpackFile, File instanceDestination) throws IOException; } }
2,748
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
ApiHandler.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/modloaders/modpacks/api/ApiHandler.java
package net.kdt.pojavlaunch.modloaders.modpacks.api; import android.util.ArrayMap; import android.util.Log; import com.google.gson.Gson; import net.kdt.pojavlaunch.Tools; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; import java.util.Objects; @SuppressWarnings("unused") public class ApiHandler { public final String baseUrl; public final Map<String, String> additionalHeaders; public ApiHandler(String url) { baseUrl = url; additionalHeaders = null; } public ApiHandler(String url, String apiKey) { baseUrl = url; additionalHeaders = new ArrayMap<>(); additionalHeaders.put("x-api-key", apiKey); } public <T> T get(String endpoint, Class<T> tClass) { return getFullUrl(additionalHeaders, baseUrl + "/" + endpoint, tClass); } public <T> T get(String endpoint, HashMap<String, Object> query, Class<T> tClass) { return getFullUrl(additionalHeaders, baseUrl + "/" + endpoint, query, tClass); } public <T> T post(String endpoint, T body, Class<T> tClass) { return postFullUrl(additionalHeaders, baseUrl + "/" + endpoint, body, tClass); } public <T> T post(String endpoint, HashMap<String, Object> query, T body, Class<T> tClass) { return postFullUrl(additionalHeaders, baseUrl + "/" + endpoint, query, body, tClass); } //Make a get request and return the response as a raw string; public static String getRaw(String url) { return getRaw(null, url); } public static String getRaw(Map<String, String> headers, String url) { Log.d("ApiHandler", url); try { HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); addHeaders(conn, headers); InputStream inputStream = conn.getInputStream(); String data = Tools.read(inputStream); Log.d(ApiHandler.class.toString(), data); inputStream.close(); conn.disconnect(); return data; } catch (IOException e) { e.printStackTrace(); } return null; } public static String postRaw(String url, String body) { return postRaw(null, url, body); } public static String postRaw(Map<String, String> headers, String url, String body) { try { HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Accept", "application/json"); addHeaders(conn, headers); conn.setDoOutput(true); OutputStream outputStream = conn.getOutputStream(); byte[] input = body.getBytes(StandardCharsets.UTF_8); outputStream.write(input, 0, input.length); outputStream.close(); InputStream inputStream = conn.getInputStream(); String data = Tools.read(inputStream); inputStream.close(); conn.disconnect(); return data; } catch (IOException e) { e.printStackTrace(); } return null; } private static void addHeaders(HttpURLConnection connection, Map<String, String> headers) { if(headers != null) { for(String key : headers.keySet()) connection.addRequestProperty(key, headers.get(key)); } } private static String parseQueries(HashMap<String, Object> query) { StringBuilder params = new StringBuilder("?"); for (String param : query.keySet()) { String value = Objects.toString(query.get(param)); params.append(urlEncodeUTF8(param)) .append("=") .append(urlEncodeUTF8(value)) .append("&"); } return params.substring(0, params.length() - 1); } public static <T> T getFullUrl(String url, Class<T> tClass) { return getFullUrl(null, url, tClass); } public static <T> T getFullUrl(String url, HashMap<String, Object> query, Class<T> tClass) { return getFullUrl(null, url, query, tClass); } public static <T> T postFullUrl(String url, T body, Class<T> tClass) { return postFullUrl(null, url, body, tClass); } public static <T> T postFullUrl(String url, HashMap<String, Object> query, T body, Class<T> tClass) { return postFullUrl(null, url, query, body, tClass); } public static <T> T getFullUrl(Map<String, String> headers, String url, Class<T> tClass) { return new Gson().fromJson(getRaw(headers, url), tClass); } public static <T> T getFullUrl(Map<String, String> headers, String url, HashMap<String, Object> query, Class<T> tClass) { return getFullUrl(headers, url + parseQueries(query), tClass); } public static <T> T postFullUrl(Map<String, String> headers, String url, T body, Class<T> tClass) { return new Gson().fromJson(postRaw(headers, url, body.toString()), tClass); } public static <T> T postFullUrl(Map<String, String> headers, String url, HashMap<String, Object> query, T body, Class<T> tClass) { return new Gson().fromJson(postRaw(headers, url + parseQueries(query), body.toString()), tClass); } private static String urlEncodeUTF8(String input) { try { return URLEncoder.encode(input, "UTF-8"); }catch (UnsupportedEncodingException e) { throw new RuntimeException("UTF-8 is required"); } } }
5,849
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
CommonApi.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/modloaders/modpacks/api/CommonApi.java
package net.kdt.pojavlaunch.modloaders.modpacks.api; import android.util.Log; import androidx.annotation.NonNull; import net.kdt.pojavlaunch.PojavApplication; import net.kdt.pojavlaunch.modloaders.modpacks.models.Constants; import net.kdt.pojavlaunch.modloaders.modpacks.models.ModDetail; import net.kdt.pojavlaunch.modloaders.modpacks.models.ModItem; import net.kdt.pojavlaunch.modloaders.modpacks.models.SearchFilters; import net.kdt.pojavlaunch.modloaders.modpacks.models.SearchResult; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.Future; /** * Group all apis under the same umbrella, as another layer of abstraction */ public class CommonApi implements ModpackApi { private final ModpackApi mCurseforgeApi; private final ModpackApi mModrinthApi; private final ModpackApi[] mModpackApis; public CommonApi(String curseforgeApiKey) { mCurseforgeApi = new CurseforgeApi(curseforgeApiKey); mModrinthApi = new ModrinthApi(); mModpackApis = new ModpackApi[]{mModrinthApi, mCurseforgeApi}; } @Override public SearchResult searchMod(SearchFilters searchFilters, SearchResult previousPageResult) { CommonApiSearchResult commonApiSearchResult = (CommonApiSearchResult) previousPageResult; // If there are no previous page results, create a new array. Otherwise, use the one from the previous page SearchResult[] results = commonApiSearchResult == null ? new SearchResult[mModpackApis.length] : commonApiSearchResult.searchResults; int totalSize = 0; Future<?>[] futures = new Future<?>[mModpackApis.length]; for(int i = 0; i < mModpackApis.length; i++) { // If there is an array and its length is zero, this means that we've exhausted the results for this // search query and we don't need to actually do the search if(results[i] != null && results[i].results.length == 0) continue; // If the previous page result is not null (aka the arrays aren't fresh) // and the previous result is null, it means that na error has occured on the previous // page. We lost contingency anyway, so don't bother requesting. if(previousPageResult != null && results[i] == null) continue; futures[i] = PojavApplication.sExecutorService.submit(new ApiDownloadTask(i, searchFilters, results[i])); } if(Thread.interrupted()) { cancelAllFutures(futures); return null; } boolean hasSuccessful = false; // Count up all the results for(int i = 0; i < mModpackApis.length; i++) { Future<?> future = futures[i]; if(future == null) continue; try { SearchResult searchResult = results[i] = (SearchResult) future.get(); if(searchResult != null) hasSuccessful = true; else continue; totalSize += searchResult.totalResultCount; }catch (Exception e) { cancelAllFutures(futures); e.printStackTrace(); return null; } } if(!hasSuccessful) { return null; } // Then build an array with all the mods ArrayList<ModItem[]> filteredResults = new ArrayList<>(results.length); // Sanitize returned values for(SearchResult result : results) { if(result == null) continue; ModItem[] searchResults = result.results; // If the length is zero, we don't need to perform needless copies if(searchResults.length == 0) continue; filteredResults.add(searchResults); } filteredResults.trimToSize(); if(Thread.interrupted()) return null; ModItem[] concatenatedItems = buildFusedResponse(filteredResults); if(Thread.interrupted()) return null; // Recycle or create new search result if(commonApiSearchResult == null) commonApiSearchResult = new CommonApiSearchResult(); commonApiSearchResult.searchResults = results; commonApiSearchResult.totalResultCount = totalSize; commonApiSearchResult.results = concatenatedItems; return commonApiSearchResult; } @Override public ModDetail getModDetails(ModItem item) { Log.i("CommonApi", "Invoking getModDetails on item.apiSource="+item.apiSource +" item.title="+item.title); return getModpackApi(item.apiSource).getModDetails(item); } @Override public ModLoader installMod(ModDetail modDetail, int selectedVersion) throws IOException { return getModpackApi(modDetail.apiSource).installMod(modDetail, selectedVersion); } private @NonNull ModpackApi getModpackApi(int apiSource) { switch (apiSource) { case Constants.SOURCE_MODRINTH: return mModrinthApi; case Constants.SOURCE_CURSEFORGE: return mCurseforgeApi; default: throw new UnsupportedOperationException("Unknown API source: " + apiSource); } } /** Fuse the arrays in a way that's fair for every endpoint */ private ModItem[] buildFusedResponse(List<ModItem[]> modMatrix){ int totalSize = 0; // Calculate the total size of the merged array for (ModItem[] array : modMatrix) { totalSize += array.length; } ModItem[] fusedItems = new ModItem[totalSize]; int mergedIndex = 0; int maxLength = 0; // Find the maximum length of arrays for (ModItem[] array : modMatrix) { if (array.length > maxLength) { maxLength = array.length; } } // Populate the merged array for (int i = 0; i < maxLength; i++) { for (ModItem[] matrix : modMatrix) { if (i < matrix.length) { fusedItems[mergedIndex] = matrix[i]; mergedIndex++; } } } return fusedItems; } private void cancelAllFutures(Future<?>[] futures) { for(Future<?> future : futures) { if(future == null) continue; future.cancel(true); } } private class ApiDownloadTask implements Callable<SearchResult> { private final int mModApi; private final SearchFilters mSearchFilters; private final SearchResult mPreviousPageResult; private ApiDownloadTask(int modApi, SearchFilters searchFilters, SearchResult previousPageResult) { this.mModApi = modApi; this.mSearchFilters = searchFilters; this.mPreviousPageResult = previousPageResult; } @Override public SearchResult call() { return mModpackApis[mModApi].searchMod(mSearchFilters, mPreviousPageResult); } } class CommonApiSearchResult extends SearchResult { SearchResult[] searchResults = new SearchResult[mModpackApis.length]; } }
7,185
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
NotificationDownloadListener.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/modloaders/modpacks/api/NotificationDownloadListener.java
package net.kdt.pojavlaunch.modloaders.modpacks.api; import android.content.Context; import android.content.Intent; import net.kdt.pojavlaunch.LauncherActivity; import net.kdt.pojavlaunch.R; import net.kdt.pojavlaunch.Tools; import net.kdt.pojavlaunch.modloaders.ModloaderDownloadListener; import net.kdt.pojavlaunch.modloaders.modpacks.ModloaderInstallTracker; import net.kdt.pojavlaunch.utils.NotificationUtils; import java.io.File; public class NotificationDownloadListener implements ModloaderDownloadListener { private final Context mContext; private final ModLoader mModLoader; public NotificationDownloadListener(Context context, ModLoader modLoader) { mModLoader = modLoader; mContext = context.getApplicationContext(); } @Override public void onDownloadFinished(File downloadedFile) { if(mModLoader.requiresGuiInstallation()) { ModloaderInstallTracker.saveModLoader(mContext, mModLoader, downloadedFile); Intent mainActivityIntent = new Intent(mContext, LauncherActivity.class); sendIntentNotification(mainActivityIntent, R.string.modpack_install_notification_success); } } @Override public void onDataNotAvailable() { sendEmptyNotification(R.string.modpack_install_notification_data_not_available); } @Override public void onDownloadError(Exception e) { Tools.showErrorRemote(mContext, R.string.modpack_install_modloader_download_failed, e); } private void sendIntentNotification(Intent intent, int localeString) { Tools.runOnUiThread(() -> NotificationUtils.sendBasicNotification(mContext, R.string.modpack_install_notification_title, localeString, intent, NotificationUtils.PENDINGINTENT_CODE_DOWNLOAD_SERVICE, NotificationUtils.NOTIFICATION_ID_DOWNLOAD_LISTENER )); } private void sendEmptyNotification(int localeString) { Tools.runOnUiThread(()->NotificationUtils.sendBasicNotification(mContext, R.string.modpack_install_notification_title, localeString, null, NotificationUtils.PENDINGINTENT_CODE_DOWNLOAD_SERVICE, NotificationUtils.NOTIFICATION_ID_DOWNLOAD_LISTENER )); } }
2,348
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
ModLoader.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/modloaders/modpacks/api/ModLoader.java
package net.kdt.pojavlaunch.modloaders.modpacks.api; import android.content.Context; import android.content.Intent; import net.kdt.pojavlaunch.JavaGUILauncherActivity; import net.kdt.pojavlaunch.modloaders.FabriclikeDownloadTask; import net.kdt.pojavlaunch.modloaders.FabriclikeUtils; import net.kdt.pojavlaunch.modloaders.ForgeDownloadTask; import net.kdt.pojavlaunch.modloaders.ForgeUtils; import net.kdt.pojavlaunch.modloaders.ModloaderDownloadListener; import java.io.File; public class ModLoader { public static final int MOD_LOADER_FORGE = 0; public static final int MOD_LOADER_FABRIC = 1; public static final int MOD_LOADER_QUILT = 2; public final int modLoaderType; public final String modLoaderVersion; public final String minecraftVersion; public ModLoader(int modLoaderType, String modLoaderVersion, String minecraftVersion) { this.modLoaderType = modLoaderType; this.modLoaderVersion = modLoaderVersion; this.minecraftVersion = minecraftVersion; } /** * Get the Version ID (the name of the mod loader in the versions/ folder) * @return the Version ID as a string */ public String getVersionId() { switch (modLoaderType) { case MOD_LOADER_FORGE: return minecraftVersion+"-forge-"+modLoaderVersion; case MOD_LOADER_FABRIC: return "fabric-loader-"+modLoaderVersion+"-"+minecraftVersion; case MOD_LOADER_QUILT: return "quilt-loader-"+modLoaderVersion+"-"+minecraftVersion; default: return null; } } /** * Get the Runnable that needs to run in order to download the mod loader. * The task will also install the mod loader if it does not require GUI installation * @param listener the listener that gets notified of the installation status * @return the task Runnable that needs to be ran */ public Runnable getDownloadTask(ModloaderDownloadListener listener) { switch (modLoaderType) { case MOD_LOADER_FORGE: return new ForgeDownloadTask(listener, minecraftVersion, modLoaderVersion); case MOD_LOADER_FABRIC: return createFabriclikeTask(listener, FabriclikeUtils.FABRIC_UTILS); case MOD_LOADER_QUILT: return createFabriclikeTask(listener, FabriclikeUtils.QUILT_UTILS); default: return null; } } /** * Get the Intent to start the graphical installation of the mod loader. * This method should only be ran after the download task of the specified mod loader finishes. * This method returns null if the mod loader does not require GUI installation * @param context the package resolving Context (can be the base context) * @param modInstallerJar the JAR file of the mod installer, provided by ModloaderDownloadListener after the installation * finishes. * @return the Intent which the launcher needs to start in order to install the mod loader */ public Intent getInstallationIntent(Context context, File modInstallerJar) { Intent baseIntent = new Intent(context, JavaGUILauncherActivity.class); switch (modLoaderType) { case MOD_LOADER_FORGE: ForgeUtils.addAutoInstallArgs(baseIntent, modInstallerJar, getVersionId()); return baseIntent; case MOD_LOADER_QUILT: case MOD_LOADER_FABRIC: default: return null; } } /** * Check whether the mod loader this object denotes requires GUI installation * @return true if mod loader requires GUI installation, false otherwise */ public boolean requiresGuiInstallation() { switch (modLoaderType) { case MOD_LOADER_FORGE: return true; case MOD_LOADER_FABRIC: case MOD_LOADER_QUILT: default: return false; } } private FabriclikeDownloadTask createFabriclikeTask(ModloaderDownloadListener modloaderDownloadListener, FabriclikeUtils utils) { return new FabriclikeDownloadTask(modloaderDownloadListener, utils, minecraftVersion, modLoaderVersion, false); } }
4,316
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
CurseforgeApi.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/modloaders/modpacks/api/CurseforgeApi.java
package net.kdt.pojavlaunch.modloaders.modpacks.api; import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.kdt.mcgui.ProgressLayout; import net.kdt.pojavlaunch.R; import net.kdt.pojavlaunch.Tools; import net.kdt.pojavlaunch.modloaders.modpacks.models.Constants; import net.kdt.pojavlaunch.modloaders.modpacks.models.CurseManifest; import net.kdt.pojavlaunch.modloaders.modpacks.models.ModDetail; import net.kdt.pojavlaunch.modloaders.modpacks.models.ModItem; import net.kdt.pojavlaunch.modloaders.modpacks.models.SearchFilters; import net.kdt.pojavlaunch.modloaders.modpacks.models.SearchResult; import net.kdt.pojavlaunch.progresskeeper.ProgressKeeper; import net.kdt.pojavlaunch.utils.FileUtils; import net.kdt.pojavlaunch.utils.GsonJsonUtils; import net.kdt.pojavlaunch.utils.ZipUtils; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.regex.Pattern; import java.util.zip.ZipFile; public class CurseforgeApi implements ModpackApi{ private static final Pattern sMcVersionPattern = Pattern.compile("([0-9]+)\\.([0-9]+)\\.?([0-9]+)?"); private static final int ALGO_SHA_1 = 1; // Stolen from // https://github.com/AnzhiZhang/CurseForgeModpackDownloader/blob/6cb3f428459f0cc8f444d16e54aea4cd1186fd7b/utils/requester.py#L93 private static final int CURSEFORGE_MINECRAFT_GAME_ID = 432; private static final int CURSEFORGE_MODPACK_CLASS_ID = 4471; // https://api.curseforge.com/v1/categories?gameId=432 and search for "Mods" (case-sensitive) private static final int CURSEFORGE_MOD_CLASS_ID = 6; private static final int CURSEFORGE_SORT_RELEVANCY = 1; private static final int CURSEFORGE_PAGINATION_SIZE = 50; private static final int CURSEFORGE_PAGINATION_END_REACHED = -1; private static final int CURSEFORGE_PAGINATION_ERROR = -2; private final ApiHandler mApiHandler; public CurseforgeApi(String apiKey) { mApiHandler = new ApiHandler("https://api.curseforge.com/v1", apiKey); } @Override public SearchResult searchMod(SearchFilters searchFilters, SearchResult previousPageResult) { CurseforgeSearchResult curseforgeSearchResult = (CurseforgeSearchResult) previousPageResult; HashMap<String, Object> params = new HashMap<>(); params.put("gameId", CURSEFORGE_MINECRAFT_GAME_ID); params.put("classId", searchFilters.isModpack ? CURSEFORGE_MODPACK_CLASS_ID : CURSEFORGE_MOD_CLASS_ID); params.put("searchFilter", searchFilters.name); params.put("sortField", CURSEFORGE_SORT_RELEVANCY); params.put("sortOrder", "desc"); if(searchFilters.mcVersion != null && !searchFilters.mcVersion.isEmpty()) params.put("gameVersion", searchFilters.mcVersion); if(previousPageResult != null) params.put("index", curseforgeSearchResult.previousOffset); JsonObject response = mApiHandler.get("mods/search", params, JsonObject.class); if(response == null) return null; JsonArray dataArray = response.getAsJsonArray("data"); if(dataArray == null) return null; JsonObject paginationInfo = response.getAsJsonObject("pagination"); ArrayList<ModItem> modItemList = new ArrayList<>(dataArray.size()); for(int i = 0; i < dataArray.size(); i++) { JsonObject dataElement = dataArray.get(i).getAsJsonObject(); JsonElement allowModDistribution = dataElement.get("allowModDistribution"); // Gson automatically casts null to false, which leans to issues // So, only check the distribution flag if it is non-null if(!allowModDistribution.isJsonNull() && !allowModDistribution.getAsBoolean()) { Log.i("CurseforgeApi", "Skipping modpack "+dataElement.get("name").getAsString() + " because curseforge sucks"); continue; } ModItem modItem = new ModItem(Constants.SOURCE_CURSEFORGE, searchFilters.isModpack, dataElement.get("id").getAsString(), dataElement.get("name").getAsString(), dataElement.get("summary").getAsString(), dataElement.getAsJsonObject("logo").get("thumbnailUrl").getAsString()); modItemList.add(modItem); } if(curseforgeSearchResult == null) curseforgeSearchResult = new CurseforgeSearchResult(); curseforgeSearchResult.results = modItemList.toArray(new ModItem[0]); curseforgeSearchResult.totalResultCount = paginationInfo.get("totalCount").getAsInt(); curseforgeSearchResult.previousOffset += dataArray.size(); return curseforgeSearchResult; } @Override public ModDetail getModDetails(ModItem item) { ArrayList<JsonObject> allModDetails = new ArrayList<>(); int index = 0; while(index != CURSEFORGE_PAGINATION_END_REACHED && index != CURSEFORGE_PAGINATION_ERROR) { index = getPaginatedDetails(allModDetails, index, item.id); } if(index == CURSEFORGE_PAGINATION_ERROR) return null; int length = allModDetails.size(); String[] versionNames = new String[length]; String[] mcVersionNames = new String[length]; String[] versionUrls = new String[length]; String[] hashes = new String[length]; for(int i = 0; i < allModDetails.size(); i++) { JsonObject modDetail = allModDetails.get(i); versionNames[i] = modDetail.get("displayName").getAsString(); JsonElement downloadUrl = modDetail.get("downloadUrl"); versionUrls[i] = downloadUrl.getAsString(); JsonArray gameVersions = modDetail.getAsJsonArray("gameVersions"); for(JsonElement jsonElement : gameVersions) { String gameVersion = jsonElement.getAsString(); if(!sMcVersionPattern.matcher(gameVersion).matches()) { continue; } mcVersionNames[i] = gameVersion; break; } hashes[i] = getSha1FromModData(modDetail); } return new ModDetail(item, versionNames, mcVersionNames, versionUrls, hashes); } @Override public ModLoader installMod(ModDetail modDetail, int selectedVersion) throws IOException{ //TODO considering only modpacks for now return ModpackInstaller.installModpack(modDetail, selectedVersion, this::installCurseforgeZip); } private int getPaginatedDetails(ArrayList<JsonObject> objectList, int index, String modId) { HashMap<String, Object> params = new HashMap<>(); params.put("index", index); params.put("pageSize", CURSEFORGE_PAGINATION_SIZE); JsonObject response = mApiHandler.get("mods/"+modId+"/files", params, JsonObject.class); JsonArray data = GsonJsonUtils.getJsonArraySafe(response, "data"); if(data == null) return CURSEFORGE_PAGINATION_ERROR; for(int i = 0; i < data.size(); i++) { JsonObject fileInfo = data.get(i).getAsJsonObject(); if(fileInfo.get("isServerPack").getAsBoolean()) continue; objectList.add(fileInfo); } if(data.size() < CURSEFORGE_PAGINATION_SIZE) { return CURSEFORGE_PAGINATION_END_REACHED; // we read the remainder! yay! } return index + data.size(); } private ModLoader installCurseforgeZip(File zipFile, File instanceDestination) throws IOException { try (ZipFile modpackZipFile = new ZipFile(zipFile)){ CurseManifest curseManifest = Tools.GLOBAL_GSON.fromJson( Tools.read(ZipUtils.getEntryStream(modpackZipFile, "manifest.json")), CurseManifest.class); if(!verifyManifest(curseManifest)) { Log.i("CurseforgeApi","manifest verification failed"); return null; } ModDownloader modDownloader = new ModDownloader(new File(instanceDestination,"mods"), true); int fileCount = curseManifest.files.length; for(int i = 0; i < fileCount; i++) { final CurseManifest.CurseFile curseFile = curseManifest.files[i]; modDownloader.submitDownload(()->{ String url = getDownloadUrl(curseFile.projectID, curseFile.fileID); if(url == null && curseFile.required) throw new IOException("Failed to obtain download URL for "+curseFile.projectID+" "+curseFile.fileID); else if(url == null) return null; return new ModDownloader.FileInfo(url, FileUtils.getFileName(url), getDownloadSha1(curseFile.projectID, curseFile.fileID)); }); } modDownloader.awaitFinish((c,m)-> ProgressKeeper.submitProgress(ProgressLayout.INSTALL_MODPACK, (int) Math.max((float)c/m*100,0), R.string.modpack_download_downloading_mods_fc, c, m) ); String overridesDir = "overrides"; if(curseManifest.overrides != null) overridesDir = curseManifest.overrides; ZipUtils.zipExtract(modpackZipFile, overridesDir, instanceDestination); return createInfo(curseManifest.minecraft); } } private ModLoader createInfo(CurseManifest.CurseMinecraft minecraft) { CurseManifest.CurseModLoader primaryModLoader = null; for(CurseManifest.CurseModLoader modLoader : minecraft.modLoaders) { if(modLoader.primary) { primaryModLoader = modLoader; break; } } if(primaryModLoader == null) primaryModLoader = minecraft.modLoaders[0]; String modLoaderId = primaryModLoader.id; int dashIndex = modLoaderId.indexOf('-'); String modLoaderName = modLoaderId.substring(0, dashIndex); String modLoaderVersion = modLoaderId.substring(dashIndex+1); Log.i("CurseforgeApi", modLoaderId + " " + modLoaderName + " "+modLoaderVersion); int modLoaderTypeInt; switch (modLoaderName) { case "forge": modLoaderTypeInt = ModLoader.MOD_LOADER_FORGE; break; case "fabric": modLoaderTypeInt = ModLoader.MOD_LOADER_FABRIC; break; default: return null; //TODO: Quilt is also Forge? How does that work? } return new ModLoader(modLoaderTypeInt, modLoaderVersion, minecraft.version); } private String getDownloadUrl(long projectID, long fileID) { // First try the official api endpoint JsonObject response = mApiHandler.get("mods/"+projectID+"/files/"+fileID+"/download-url", JsonObject.class); if (response != null && !response.get("data").isJsonNull()) return response.get("data").getAsString(); // Otherwise, fallback to building an edge link JsonObject fallbackResponse = mApiHandler.get(String.format("mods/%s/files/%s", projectID, fileID), JsonObject.class); if (fallbackResponse != null && !fallbackResponse.get("data").isJsonNull()){ JsonObject modData = fallbackResponse.get("data").getAsJsonObject(); int id = modData.get("id").getAsInt(); return String.format("https://edge.forgecdn.net/files/%s/%s/%s", id/1000, id % 1000, modData.get("fileName").getAsString()); } return null; } private @Nullable String getDownloadSha1(long projectID, long fileID) { // Try the api endpoint, die in the other case JsonObject response = mApiHandler.get("mods/"+projectID+"/files/"+fileID, JsonObject.class); JsonObject data = GsonJsonUtils.getJsonObjectSafe(response, "data"); if(data == null) return null; return getSha1FromModData(data); } private String getSha1FromModData(@NonNull JsonObject object) { JsonArray hashes = GsonJsonUtils.getJsonArraySafe(object, "hashes"); if(hashes == null) return null; for (JsonElement jsonElement : hashes) { // The sha1 = 1; md5 = 2; JsonObject jsonObject = GsonJsonUtils.getJsonObjectSafe(jsonElement); if(GsonJsonUtils.getIntSafe( jsonObject, "algo", -1) == ALGO_SHA_1) { return GsonJsonUtils.getStringSafe(jsonObject, "value"); } } return null; } private boolean verifyManifest(CurseManifest manifest) { if(!"minecraftModpack".equals(manifest.manifestType)) return false; if(manifest.manifestVersion != 1) return false; if(manifest.minecraft == null) return false; if(manifest.minecraft.version == null) return false; if(manifest.minecraft.modLoaders == null) return false; return manifest.minecraft.modLoaders.length >= 1; } static class CurseforgeSearchResult extends SearchResult { int previousOffset; } }
13,223
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
ModDownloader.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/modloaders/modpacks/api/ModDownloader.java
package net.kdt.pojavlaunch.modloaders.modpacks.api; import androidx.annotation.Nullable; import net.kdt.pojavlaunch.Tools; import net.kdt.pojavlaunch.utils.DownloadUtils; import java.io.File; import java.io.IOException; import java.io.InterruptedIOException; import java.util.concurrent.Callable; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; public class ModDownloader { private static final ThreadLocal<byte[]> sThreadLocalBuffer = new ThreadLocal<>(); private final ThreadPoolExecutor mDownloadPool = new ThreadPoolExecutor(4,4,100, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>()); private final AtomicBoolean mTerminator = new AtomicBoolean(false); private final AtomicLong mDownloadSize = new AtomicLong(0); private final Object mExceptionSyncPoint = new Object(); private final File mDestinationDirectory; private final boolean mUseFileCount; private IOException mFirstIOException; private long mTotalSize; public ModDownloader(File destinationDirectory) { this(destinationDirectory, false); } public ModDownloader(File destinationDirectory, boolean useFileCount) { this.mDownloadPool.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy()); this.mDestinationDirectory = destinationDirectory; this.mUseFileCount = useFileCount; } public void submitDownload(int fileSize, String relativePath, @Nullable String downloadHash, String... url) { if(mUseFileCount) mTotalSize += 1; else mTotalSize += fileSize; mDownloadPool.execute(new DownloadTask(url, new File(mDestinationDirectory, relativePath), downloadHash)); } public void submitDownload(FileInfoProvider infoProvider) { if(!mUseFileCount) throw new RuntimeException("This method can only be used in a file-counting ModDownloader"); mTotalSize += 1; mDownloadPool.execute(new FileInfoQueryTask(infoProvider)); } public void awaitFinish(Tools.DownloaderFeedback feedback) throws IOException { try { mDownloadPool.shutdown(); while(!mDownloadPool.awaitTermination(20, TimeUnit.MILLISECONDS) && !mTerminator.get()) { feedback.updateProgress((int) mDownloadSize.get(), (int) mTotalSize); } if(mTerminator.get()) { mDownloadPool.shutdownNow(); synchronized (mExceptionSyncPoint) { if(mFirstIOException == null) mExceptionSyncPoint.wait(); throw mFirstIOException; } } }catch (InterruptedException e) { e.printStackTrace(); } } private static byte[] getThreadLocalBuffer() { byte[] buffer = sThreadLocalBuffer.get(); if(buffer != null) return buffer; buffer = new byte[8192]; sThreadLocalBuffer.set(buffer); return buffer; } private void downloadFailed(IOException exception) { mTerminator.set(true); synchronized (mExceptionSyncPoint) { if(mFirstIOException == null) { mFirstIOException = exception; mExceptionSyncPoint.notify(); } } } class FileInfoQueryTask implements Runnable { private final FileInfoProvider mFileInfoProvider; public FileInfoQueryTask(FileInfoProvider fileInfoProvider) { this.mFileInfoProvider = fileInfoProvider; } @Override public void run() { try { FileInfo fileInfo = mFileInfoProvider.getFileInfo(); if(fileInfo == null) return; new DownloadTask(new String[]{fileInfo.url}, new File(mDestinationDirectory, fileInfo.relativePath), fileInfo.sha1).run(); }catch (IOException e) { downloadFailed(e); } } } class DownloadTask implements Runnable, Tools.DownloaderFeedback { private final String[] mDownloadUrls; private final File mDestination; private final String mSha1; private int last = 0; public DownloadTask(String[] downloadurls, File downloadDestination, String downloadHash) { this.mDownloadUrls = downloadurls; this.mDestination = downloadDestination; this.mSha1 = downloadHash; } @Override public void run() { for(String sourceUrl : mDownloadUrls) { try { DownloadUtils.ensureSha1(mDestination, mSha1, (Callable<Void>) () -> { IOException exception = tryDownload(sourceUrl); if(exception != null) { throw exception; } return null; }); }catch (IOException e) { downloadFailed(e); } } } private IOException tryDownload(String sourceUrl) throws InterruptedException { IOException exception = null; for (int i = 0; i < 5; i++) { try { DownloadUtils.downloadFileMonitored(sourceUrl, mDestination, getThreadLocalBuffer(), this); if(mUseFileCount) mDownloadSize.addAndGet(1); return null; } catch (InterruptedIOException e) { throw new InterruptedException(); } catch (IOException e) { e.printStackTrace(); exception = e; } if(!mUseFileCount) { mDownloadSize.addAndGet(-last); last = 0; } } return exception; } @Override public void updateProgress(int curr, int max) { if(mUseFileCount) return; mDownloadSize.addAndGet(curr - last); last = curr; } } public static class FileInfo { public final String url; public final String relativePath; public final String sha1; public FileInfo(String url, String relativePath, @Nullable String sha1) { this.url = url; this.relativePath = relativePath; this.sha1 = sha1; } } public interface FileInfoProvider { FileInfo getFileInfo() throws IOException; } }
6,676
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
CustomControls.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/customcontrols/CustomControls.java
package net.kdt.pojavlaunch.customcontrols; import android.content.*; import androidx.annotation.Keep; import java.io.IOException; import java.util.*; import net.kdt.pojavlaunch.*; @Keep public class CustomControls { public int version = -1; public float scaledAt; public List<ControlData> mControlDataList; public List<ControlDrawerData> mDrawerDataList; public List<ControlJoystickData> mJoystickDataList; public CustomControls() { this(new ArrayList<>(), new ArrayList<>(), new ArrayList<>()); } public CustomControls(List<ControlData> mControlDataList, List<ControlDrawerData> mDrawerDataList, List<ControlJoystickData> mJoystickDataList) { this.mControlDataList = mControlDataList; this.mDrawerDataList = mDrawerDataList; this.mJoystickDataList = mJoystickDataList; this.scaledAt = 100f; } // Generate default control // Here for historical reasons // Just admire it idk @SuppressWarnings("unused") public CustomControls(Context ctx) { this(); this.mControlDataList.add(new ControlData(ControlData.getSpecialButtons()[0])); // Keyboard this.mControlDataList.add(new ControlData(ControlData.getSpecialButtons()[1])); // GUI this.mControlDataList.add(new ControlData(ControlData.getSpecialButtons()[2])); // Primary Mouse mControlDataList this.mControlDataList.add(new ControlData(ControlData.getSpecialButtons()[3])); // Secondary Mouse mControlDataList this.mControlDataList.add(new ControlData(ControlData.getSpecialButtons()[4])); // Virtual mouse toggle this.mControlDataList.add(new ControlData(ctx, R.string.control_debug, new int[]{LwjglGlfwKeycode.GLFW_KEY_F3}, "${margin}", "${margin}", false)); this.mControlDataList.add(new ControlData(ctx, R.string.control_chat, new int[]{LwjglGlfwKeycode.GLFW_KEY_T}, "${margin} * 2 + ${width}", "${margin}", false)); this.mControlDataList.add(new ControlData(ctx, R.string.control_listplayers, new int[]{LwjglGlfwKeycode.GLFW_KEY_TAB}, "${margin} * 4 + ${width} * 3", "${margin}", false)); this.mControlDataList.add(new ControlData(ctx, R.string.control_thirdperson, new int[]{LwjglGlfwKeycode.GLFW_KEY_F5}, "${margin}", "${height} + ${margin}", false)); this.mControlDataList.add(new ControlData(ctx, R.string.control_up, new int[]{LwjglGlfwKeycode.GLFW_KEY_W}, "${margin} * 2 + ${width}", "${bottom} - ${margin} * 3 - ${height} * 2", true)); this.mControlDataList.add(new ControlData(ctx, R.string.control_left, new int[]{LwjglGlfwKeycode.GLFW_KEY_A}, "${margin}", "${bottom} - ${margin} * 2 - ${height}", true)); this.mControlDataList.add(new ControlData(ctx, R.string.control_down, new int[]{LwjglGlfwKeycode.GLFW_KEY_S}, "${margin} * 2 + ${width}", "${bottom} - ${margin}", true)); this.mControlDataList.add(new ControlData(ctx, R.string.control_right, new int[]{LwjglGlfwKeycode.GLFW_KEY_D}, "${margin} * 3 + ${width} * 2", "${bottom} - ${margin} * 2 - ${height}", true)); this.mControlDataList.add(new ControlData(ctx, R.string.control_inventory, new int[]{LwjglGlfwKeycode.GLFW_KEY_E}, "${margin} * 3 + ${width} * 2", "${bottom} - ${margin}", true)); ControlData shiftData = new ControlData(ctx, R.string.control_shift, new int[]{LwjglGlfwKeycode.GLFW_KEY_LEFT_SHIFT}, "${margin} * 2 + ${width}", "${screen_height} - ${margin} * 2 - ${height} * 2", true); shiftData.isToggle = true; this.mControlDataList.add(shiftData); this.mControlDataList.add(new ControlData(ctx, R.string.control_jump, new int[]{LwjglGlfwKeycode.GLFW_KEY_SPACE}, "${right} - ${margin} * 2 - ${width}", "${bottom} - ${margin} * 2 - ${height}", true)); //The default controls are conform to the V3 version = 6; } public void save(String path) throws IOException { //Current version is the V3.0 so the version as to be marked as 6 ! version = 6; Tools.write(path, Tools.GLOBAL_GSON.toJson(this)); } }
3,839
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
ControlData.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/customcontrols/ControlData.java
package net.kdt.pojavlaunch.customcontrols; import static net.kdt.pojavlaunch.LwjglGlfwKeycode.GLFW_KEY_UNKNOWN; import android.util.ArrayMap; import androidx.annotation.Keep; import net.kdt.pojavlaunch.Tools; import net.kdt.pojavlaunch.prefs.LauncherPreferences; import net.kdt.pojavlaunch.utils.JSONUtils; import net.objecthunter.exp4j.ExpressionBuilder; import net.objecthunter.exp4j.function.Function; import org.lwjgl.glfw.CallbackBridge; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; @Keep public class ControlData { public static final int SPECIALBTN_KEYBOARD = -1; public static final int SPECIALBTN_TOGGLECTRL = -2; public static final int SPECIALBTN_MOUSEPRI = -3; public static final int SPECIALBTN_MOUSESEC = -4; public static final int SPECIALBTN_VIRTUALMOUSE = -5; public static final int SPECIALBTN_MOUSEMID = -6; public static final int SPECIALBTN_SCROLLUP = -7; public static final int SPECIALBTN_SCROLLDOWN = -8; public static final int SPECIALBTN_MENU = -9; private static ControlData[] SPECIAL_BUTTONS; private static List<String> SPECIAL_BUTTON_NAME_ARRAY; private static WeakReference<ExpressionBuilder> builder = new WeakReference<>(null); private static WeakReference<ArrayMap<String, String>> conversionMap = new WeakReference<>(null); static { buildExpressionBuilder(); buildConversionMap(); } // Internal usage only public boolean isHideable; /** * Both fields below are dynamic position data, auto updates * X and Y position, unlike the original one which uses fixed * position, so it does not provide auto-location when a control * is made on a small device, then import the control to a * bigger device or vice versa. */ public String dynamicX, dynamicY; public boolean isDynamicBtn, isToggle, passThruEnabled; public String name; public int[] keycodes; //Should store up to 4 keys public float opacity; //Alpha value from 0 to 1; public int bgColor; public int strokeColor; public float strokeWidth; // Dp instead of % now public float cornerRadius; //0-100% public boolean isSwipeable; public boolean displayInGame; public boolean displayInMenu; private float width; //Dp instead of Px now private float height; //Dp instead of Px now public ControlData() { this("button"); } public ControlData(String name) { this(name, new int[]{}); } public ControlData(String name, int[] keycodes) { this(name, keycodes, Tools.currentDisplayMetrics.widthPixels / 2f, Tools.currentDisplayMetrics.heightPixels / 2f); } public ControlData(String name, int[] keycodes, float x, float y) { this(name, keycodes, x, y, 50, 50); } public ControlData(android.content.Context ctx, int resId, int[] keycodes, float x, float y, boolean isSquare) { this(ctx.getResources().getString(resId), keycodes, x, y, isSquare); } public ControlData(String name, int[] keycodes, float x, float y, boolean isSquare) { this(name, keycodes, x, y, isSquare ? 50 : 80, isSquare ? 50 : 30); } public ControlData(String name, int[] keycodes, float x, float y, float width, float height) { this(name, keycodes, Float.toString(x), Float.toString(y), width, height, false); this.isDynamicBtn = false; } public ControlData(String name, int[] keycodes, String dynamicX, String dynamicY) { this(name, keycodes, dynamicX, dynamicY, 50, 50, false); } public ControlData(android.content.Context ctx, int resId, int[] keycodes, String dynamicX, String dynamicY, boolean isSquare) { this(ctx.getResources().getString(resId), keycodes, dynamicX, dynamicY, isSquare); } public ControlData(String name, int[] keycodes, String dynamicX, String dynamicY, boolean isSquare) { this(name, keycodes, dynamicX, dynamicY, isSquare ? 50 : 80, isSquare ? 50 : 30, false); } public ControlData(String name, int[] keycodes, String dynamicX, String dynamicY, float width, float height, boolean isToggle) { this(name, keycodes, dynamicX, dynamicY, width, height, isToggle, 1, 0x4D000000, 0xFFFFFFFF, 0, 0, true, true, false, false); } public ControlData(String name, int[] keycodes, String dynamicX, String dynamicY, float width, float height, boolean isToggle, float opacity, int bgColor, int strokeColor, float strokeWidth, float cornerRadius, boolean displayInGame, boolean displayInMenu, boolean isSwipable, boolean mousePassthrough) { this.name = name; this.keycodes = inflateKeycodeArray(keycodes); this.dynamicX = dynamicX; this.dynamicY = dynamicY; this.width = width; this.height = height; this.isDynamicBtn = false; this.isToggle = isToggle; this.opacity = opacity; this.bgColor = bgColor; this.strokeColor = strokeColor; this.strokeWidth = strokeWidth; this.cornerRadius = cornerRadius; this.displayInGame = displayInGame; this.displayInMenu = displayInMenu; this.isSwipeable = isSwipable; this.passThruEnabled = mousePassthrough; } //Deep copy constructor public ControlData(ControlData controlData) { this( controlData.name, controlData.keycodes, controlData.dynamicX, controlData.dynamicY, controlData.width, controlData.height, controlData.isToggle, controlData.opacity, controlData.bgColor, controlData.strokeColor, controlData.strokeWidth, controlData.cornerRadius, controlData.displayInGame, controlData.displayInMenu, controlData.isSwipeable, controlData.passThruEnabled ); } public static ControlData[] getSpecialButtons() { if (SPECIAL_BUTTONS == null) { SPECIAL_BUTTONS = new ControlData[]{ new ControlData("Keyboard", new int[]{SPECIALBTN_KEYBOARD}, "${margin} * 3 + ${width} * 2", "${margin}", false), new ControlData("GUI", new int[]{SPECIALBTN_TOGGLECTRL}, "${margin}", "${bottom} - ${margin}"), new ControlData("PRI", new int[]{SPECIALBTN_MOUSEPRI}, "${margin}", "${screen_height} - ${margin} * 3 - ${height} * 3"), new ControlData("SEC", new int[]{SPECIALBTN_MOUSESEC}, "${margin} * 3 + ${width} * 2", "${screen_height} - ${margin} * 3 - ${height} * 3"), new ControlData("Mouse", new int[]{SPECIALBTN_VIRTUALMOUSE}, "${right}", "${margin}", false), new ControlData("MID", new int[]{SPECIALBTN_MOUSEMID}, "${margin}", "${margin}"), new ControlData("SCROLLUP", new int[]{SPECIALBTN_SCROLLUP}, "${margin}", "${margin}"), new ControlData("SCROLLDOWN", new int[]{SPECIALBTN_SCROLLDOWN}, "${margin}", "${margin}"), new ControlData("MENU", new int[]{SPECIALBTN_MENU}, "${margin}", "${margin}") }; } return SPECIAL_BUTTONS; } public static List<String> buildSpecialButtonArray() { if (SPECIAL_BUTTON_NAME_ARRAY == null) { List<String> nameList = new ArrayList<>(); for (ControlData btn : getSpecialButtons()) { nameList.add("SPECIAL_" + btn.name); } SPECIAL_BUTTON_NAME_ARRAY = nameList; Collections.reverse(SPECIAL_BUTTON_NAME_ARRAY); } return SPECIAL_BUTTON_NAME_ARRAY; } private static float calculate(String math) { setExpression(math); return (float) builder.get().build().evaluate(); } private static int[] inflateKeycodeArray(int[] keycodes) { int[] inflatedArray = new int[]{GLFW_KEY_UNKNOWN, GLFW_KEY_UNKNOWN, GLFW_KEY_UNKNOWN, GLFW_KEY_UNKNOWN}; System.arraycopy(keycodes, 0, inflatedArray, 0, keycodes.length); return inflatedArray; } /** * Create a builder, keep a weak reference to it to use it with all views on first inflation */ private static void buildExpressionBuilder() { ExpressionBuilder expressionBuilder = new ExpressionBuilder("1 + 1") .function(new Function("dp", 1) { @Override public double apply(double... args) { return Tools.pxToDp((float) args[0]); } }) .function(new Function("px", 1) { @Override public double apply(double... args) { return Tools.dpToPx((float) args[0]); } }); builder = new WeakReference<>(expressionBuilder); } /** * wrapper for the WeakReference to the expressionField. * * @param stringExpression the expression to set. */ private static void setExpression(String stringExpression) { if (builder.get() == null) buildExpressionBuilder(); builder.get().expression(stringExpression); } /** * Build a shared conversion map without the ControlData dependent values * You need to set the view dependent values before using it. */ private static void buildConversionMap() { // Values in the map below may be always changed ArrayMap<String, String> keyValueMap = new ArrayMap<>(10); keyValueMap.put("top", "0"); keyValueMap.put("left", "0"); keyValueMap.put("right", "DUMMY_RIGHT"); keyValueMap.put("bottom", "DUMMY_BOTTOM"); keyValueMap.put("width", "DUMMY_WIDTH"); keyValueMap.put("height", "DUMMY_HEIGHT"); keyValueMap.put("screen_width", "DUMMY_DATA"); keyValueMap.put("screen_height", "DUMMY_DATA"); keyValueMap.put("margin", Integer.toString((int) Tools.dpToPx(2))); keyValueMap.put("preferred_scale", "DUMMY_DATA"); conversionMap = new WeakReference<>(keyValueMap); } public float insertDynamicPos(String dynamicPos) { // Insert value to ${variable} String insertedPos = JSONUtils.insertSingleJSONValue(dynamicPos, fillConversionMap()); // Calculate, because the dynamic position contains some math equations return calculate(insertedPos); } @SuppressWarnings("BooleanMethodIsAlwaysInverted") public boolean containsKeycode(int keycodeToCheck) { for (int keycode : keycodes) if (keycodeToCheck == keycode) return true; return false; } //Getters || setters (with conversion for ease of use) public float getWidth() { return Tools.dpToPx(width); } public void setWidth(float widthInPx) { width = Tools.pxToDp(widthInPx); } public float getHeight() { return Tools.dpToPx(height); } public void setHeight(float heightInPx) { height = Tools.pxToDp(heightInPx); } /** * Fill the conversionMap with controlData dependent values. * The returned valueMap should NOT be kept in memory. * * @return the valueMap to use. */ private Map<String, String> fillConversionMap() { ArrayMap<String, String> valueMap = conversionMap.get(); if (valueMap == null) { buildConversionMap(); valueMap = conversionMap.get(); } valueMap.put("right", Float.toString(CallbackBridge.physicalWidth - getWidth())); valueMap.put("bottom", Float.toString(CallbackBridge.physicalHeight - getHeight())); valueMap.put("width", Float.toString(getWidth())); valueMap.put("height", Float.toString(getHeight())); valueMap.put("screen_width", Integer.toString(CallbackBridge.physicalWidth)); valueMap.put("screen_height", Integer.toString(CallbackBridge.physicalHeight)); valueMap.put("preferred_scale", Float.toString(LauncherPreferences.PREF_BUTTONSIZE)); return valueMap; } }
12,288
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
ControlLayout.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/customcontrols/ControlLayout.java
package net.kdt.pojavlaunch.customcontrols; import static android.content.Context.INPUT_METHOD_SERVICE; import static net.kdt.pojavlaunch.MainActivity.mControlLayout; import static net.kdt.pojavlaunch.Tools.currentDisplayMetrics; import static org.lwjgl.glfw.CallbackBridge.isGrabbing; import android.annotation.SuppressLint; import android.content.Context; import android.os.Build; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.Toast; import androidx.appcompat.app.AlertDialog; import com.google.gson.JsonSyntaxException; import com.kdt.pickafile.FileListView; import com.kdt.pickafile.FileSelectedListener; import net.kdt.pojavlaunch.MinecraftGLSurface; import net.kdt.pojavlaunch.R; import net.kdt.pojavlaunch.Tools; import net.kdt.pojavlaunch.customcontrols.buttons.ControlButton; import net.kdt.pojavlaunch.customcontrols.buttons.ControlDrawer; import net.kdt.pojavlaunch.customcontrols.buttons.ControlInterface; import net.kdt.pojavlaunch.customcontrols.buttons.ControlJoystick; import net.kdt.pojavlaunch.customcontrols.buttons.ControlSubButton; import net.kdt.pojavlaunch.customcontrols.handleview.ActionRow; import net.kdt.pojavlaunch.customcontrols.handleview.ControlHandleView; import net.kdt.pojavlaunch.customcontrols.handleview.EditControlPopup; import net.kdt.pojavlaunch.prefs.LauncherPreferences; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class ControlLayout extends FrameLayout { protected CustomControls mLayout; /* Accessible when inside the game by ControlInterface implementations, cached for perf. */ private MinecraftGLSurface mGameSurface = null; /* Cache to buttons for performance purposes */ private List<ControlInterface> mButtons; private boolean mModifiable = false; private boolean mIsModified; private boolean mControlVisible = false; private EditControlPopup mControlPopup = null; private ControlHandleView mHandleView; private ControlButtonMenuListener mMenuListener; public ActionRow mActionRow = null; public String mLayoutFileName; public ControlLayout(Context ctx) { super(ctx); } public ControlLayout(Context ctx, AttributeSet attrs) { super(ctx, attrs); } public void loadLayout(String jsonPath) throws IOException, JsonSyntaxException { CustomControls layout = LayoutConverter.loadAndConvertIfNecessary(jsonPath); if(layout != null) { loadLayout(layout); updateLoadedFileName(jsonPath); return; } throw new IOException("Unsupported control layout version"); } public void loadLayout(CustomControls controlLayout) { if(mActionRow == null){ mActionRow = new ActionRow(getContext()); addView(mActionRow); } removeAllButtons(); if(mLayout != null) { mLayout.mControlDataList = null; mLayout = null; } System.gc(); mapTable.clear(); // Cleanup buttons only when input layout is null if (controlLayout == null) return; mLayout = controlLayout; // Joystick(s) first, to workaround the touch dispatch for(ControlJoystickData joystick : mLayout.mJoystickDataList){ addJoystickView(joystick); } //CONTROL BUTTON for (ControlData button : controlLayout.mControlDataList) { addControlView(button); } //CONTROL DRAWER for(ControlDrawerData drawerData : controlLayout.mDrawerDataList){ ControlDrawer drawer = addDrawerView(drawerData); if(mModifiable) drawer.areButtonsVisible = true; } mLayout.scaledAt = LauncherPreferences.PREF_BUTTONSIZE; setModified(false); mButtons = null; getButtonChildren(); // Force refresh } // loadLayout //CONTROL BUTTON public void addControlButton(ControlData controlButton) { mLayout.mControlDataList.add(controlButton); addControlView(controlButton); } private void addControlView(ControlData controlButton) { final ControlButton view = new ControlButton(this, controlButton); if (!mModifiable) { view.setAlpha(view.getProperties().opacity); view.setFocusable(false); view.setFocusableInTouchMode(false); } addView(view); setModified(true); } // CONTROL DRAWER public void addDrawer(ControlDrawerData drawerData){ mLayout.mDrawerDataList.add(drawerData); addDrawerView(); } private void addDrawerView(){ addDrawerView(null); } private ControlDrawer addDrawerView(ControlDrawerData drawerData){ final ControlDrawer view = new ControlDrawer(this,drawerData == null ? mLayout.mDrawerDataList.get(mLayout.mDrawerDataList.size()-1) : drawerData); if (!mModifiable) { view.setAlpha(view.getProperties().opacity); view.setFocusable(false); view.setFocusableInTouchMode(false); } addView(view); //CONTROL SUB BUTTON for (ControlData subButton : view.getDrawerData().buttonProperties) { addSubView(view, subButton); } setModified(true); return view; } //CONTROL SUB-BUTTON public void addSubButton(ControlDrawer drawer, ControlData controlButton){ //Yep there isn't much here drawer.getDrawerData().buttonProperties.add(controlButton); addSubView(drawer, drawer.getDrawerData().buttonProperties.get(drawer.getDrawerData().buttonProperties.size()-1 )); } private void addSubView(ControlDrawer drawer, ControlData controlButton){ final ControlSubButton view = new ControlSubButton(this, controlButton, drawer); if (!mModifiable) { view.setAlpha(view.getProperties().opacity); view.setFocusable(false); view.setFocusableInTouchMode(false); }else{ view.setVisible(true); } addView(view); drawer.addButton(view); setModified(true); } // JOYSTICK BUTTON public void addJoystickButton(ControlJoystickData data){ mLayout.mJoystickDataList.add(data); addJoystickView(data); } private void addJoystickView(ControlJoystickData data){ ControlJoystick view = new ControlJoystick(this, data); if (!mModifiable) { view.setAlpha(view.getProperties().opacity); view.setFocusable(false); view.setFocusableInTouchMode(false); } addView(view); } private void removeAllButtons() { for(ControlInterface button : getButtonChildren()){ removeView(button.getControlView()); } System.gc(); //i wanna be sure that all the removed Views will be removed after a reload //because if frames will slowly go down after many control changes it will be warm and bad } public void saveLayout(String path) throws Exception { mLayout.save(path); setModified(false); } public void toggleControlVisible(){ mControlVisible = !mControlVisible; setControlVisible(mControlVisible); } public float getLayoutScale(){ return mLayout.scaledAt; } public CustomControls getLayout(){ return mLayout; } public void setControlVisible(boolean isVisible) { if (mModifiable) return; // Not using on custom controls activity mControlVisible = isVisible; for(ControlInterface button : getButtonChildren()){ button.setVisible(((button.getProperties().displayInGame && isGrabbing()) || (button.getProperties().displayInMenu && !isGrabbing())) && isVisible); } } public void setModifiable(boolean isModifiable) { if(!isModifiable && mModifiable){ removeEditWindow(); } mModifiable = isModifiable; if(isModifiable){ // In edit mode, all controls have to be shown for(ControlInterface button : getButtonChildren()){ button.setVisible(true); } } } public boolean getModifiable(){ return mModifiable; } public void setModified(boolean isModified) { mIsModified = isModified; } public List<ControlInterface> getButtonChildren(){ if(mModifiable || mButtons == null){ mButtons = new ArrayList<>(); for(int i=0; i<getChildCount(); ++i){ View v = getChildAt(i); if(v instanceof ControlInterface) mButtons.add(((ControlInterface) v)); } } return mButtons; } public void refreshControlButtonPositions(){ for(ControlInterface button : getButtonChildren()){ button.setDynamicX(button.getProperties().dynamicX); button.setDynamicY(button.getProperties().dynamicY); } } @Override public void onViewRemoved(View child) { super.onViewRemoved(child); if(child instanceof ControlInterface && mControlPopup != null){ mControlPopup.disappearColor(); mControlPopup.disappear(); } } /** * Load the layout if needed, and pass down the burden of filling values * to the button at hand. */ public void editControlButton(ControlInterface button){ if(mControlPopup == null){ // When the panel is null, it needs to inflate first. // So inflate it, then process it on the next frame mControlPopup = new EditControlPopup(getContext(), this); post(() -> editControlButton(button)); return; } mControlPopup.internalChanges = true; mControlPopup.setCurrentlyEditedButton(button); button.loadEditValues(mControlPopup); mControlPopup.internalChanges = false; mControlPopup.appear(button.getControlView().getX() + button.getControlView().getWidth()/2f < currentDisplayMetrics.widthPixels/2f); mControlPopup.disappearColor(); if(mHandleView == null){ mHandleView = new ControlHandleView(getContext()); addView(mHandleView); } mHandleView.setControlButton(button); //mHandleView.show(); } /** Swap the panel if the button position requires it */ public void adaptPanelPosition(){ if(mControlPopup != null) mControlPopup.adaptPanelPosition(); } final HashMap<View, ControlInterface> mapTable = new HashMap<>(); //While this is called onTouch, this should only be called from a ControlButton. public void onTouch(View v, MotionEvent ev) { ControlInterface lastControlButton = mapTable.get(v); // Map location to screen coordinates ev.offsetLocation(v.getX(), v.getY()); //Check if the action is cancelling, reset the lastControl button associated to the view if (ev.getActionMasked() == MotionEvent.ACTION_UP || ev.getActionMasked() == MotionEvent.ACTION_CANCEL || ev.getActionMasked() == MotionEvent.ACTION_POINTER_UP) { if (lastControlButton != null) lastControlButton.sendKeyPresses(false); mapTable.put(v, null); return; } if (ev.getActionMasked() != MotionEvent.ACTION_MOVE) return; //Optimization pass to avoid looking at all children again if (lastControlButton != null) { System.out.println("last control button check" + ev.getX() + "-" + ev.getY() + "-" + lastControlButton.getControlView().getX() + "-" + lastControlButton.getControlView().getY()); if (ev.getX() > lastControlButton.getControlView().getX() && ev.getX() < lastControlButton.getControlView().getX() + lastControlButton.getControlView().getWidth() && ev.getY() > lastControlButton.getControlView().getY() && ev.getY() < lastControlButton.getControlView().getY() + lastControlButton.getControlView().getHeight()) { return; } } //Release last keys if (lastControlButton != null) lastControlButton.sendKeyPresses(false); mapTable.remove(v); // Update the state of all swipeable buttons for (ControlInterface button : getButtonChildren()) { if (!button.getProperties().isSwipeable) continue; if (ev.getX() > button.getControlView().getX() && ev.getX() < button.getControlView().getX() + button.getControlView().getWidth() && ev.getY() > button.getControlView().getY() && ev.getY() < button.getControlView().getY() + button.getControlView().getHeight()) { //Press the new key if (!button.equals(lastControlButton)) { button.sendKeyPresses(true); mapTable.put(v, button); return; } } } } @SuppressLint("ClickableViewAccessibility") @Override public boolean onTouchEvent(MotionEvent event) { if (mModifiable && event.getActionMasked() != MotionEvent.ACTION_UP || mControlPopup == null) return true; InputMethodManager imm = (InputMethodManager) getContext().getSystemService(INPUT_METHOD_SERVICE); // When the input window cannot be hidden, it returns false if(!imm.hideSoftInputFromWindow(getWindowToken(), 0)){ if(mControlPopup.disappearLayer()){ mActionRow.setFollowedButton(null); mHandleView.hide(); } } return true; } public void removeEditWindow() { InputMethodManager imm = (InputMethodManager) getContext().getSystemService(INPUT_METHOD_SERVICE); // When the input window cannot be hidden, it returns false imm.hideSoftInputFromWindow(getWindowToken(), 0); if(mControlPopup != null) { mControlPopup.disappearColor(); mControlPopup.disappear(); } if(mActionRow != null) mActionRow.setFollowedButton(null); if(mHandleView != null) mHandleView.hide(); } public void save(String path){ try { mLayout.save(path); } catch (IOException e) {Log.e("ControlLayout", "Failed to save the layout at:" + path);} } public boolean hasMenuButton() { for(ControlInterface controlInterface : getButtonChildren()){ for (int keycode : controlInterface.getProperties().keycodes) { if (keycode == ControlData.SPECIALBTN_MENU) return true; } } return false; } public void setMenuListener(ControlButtonMenuListener menuListener) { this.mMenuListener = menuListener; } public void notifyAppMenu() { if(mMenuListener != null) mMenuListener.onClickedMenu(); } /** Cached getter for perf purposes */ public MinecraftGLSurface getGameSurface(){ if(mGameSurface == null){ mGameSurface = findViewById(R.id.main_game_render_view); } return mGameSurface; } public void askToExit(EditorExitable editorExitable) { if(mIsModified) { openSaveDialog(editorExitable); }else{ openExitDialog(editorExitable); } } public void updateLoadedFileName(String path) { path = path.replace(Tools.CTRLMAP_PATH, "."); path = path.substring(0, path.length() - 5); mLayoutFileName = path; } public String saveToDirectory(String name) throws Exception{ String jsonPath = Tools.CTRLMAP_PATH + "/" + name + ".json"; saveLayout(jsonPath); return jsonPath; } class OnClickExitListener implements View.OnClickListener { private final AlertDialog mDialog; private final EditText mEditText; private final EditorExitable mListener; public OnClickExitListener(AlertDialog mDialog, EditText mEditText, EditorExitable mListener) { this.mDialog = mDialog; this.mEditText = mEditText; this.mListener = mListener; } @Override public void onClick(View v) { Context context = v.getContext(); if (mEditText.getText().toString().isEmpty()) { mEditText.setError(context.getString(R.string.global_error_field_empty)); return; } try { String jsonPath = saveToDirectory(mEditText.getText().toString()); Toast.makeText(context, context.getString(R.string.global_save) + ": " + jsonPath, Toast.LENGTH_SHORT).show(); mDialog.dismiss(); if(mListener != null) mListener.exitEditor(); } catch (Throwable th) { Tools.showError(context, th, mListener != null); } } } public void openSaveDialog(EditorExitable editorExitable) { final Context context = getContext(); final EditText edit = new EditText(context); edit.setSingleLine(); edit.setText(mLayoutFileName); AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle(R.string.global_save); builder.setView(edit); builder.setPositiveButton(android.R.string.ok, null); builder.setNegativeButton(android.R.string.cancel, null); if(editorExitable != null) builder.setNeutralButton(R.string.global_save_and_exit, null); final AlertDialog dialog = builder.create(); dialog.setOnShowListener(dialogInterface -> { dialog.getButton(AlertDialog.BUTTON_POSITIVE) .setOnClickListener(new OnClickExitListener(dialog, edit, null)); if(editorExitable != null) dialog.getButton(AlertDialog.BUTTON_NEUTRAL) .setOnClickListener(new OnClickExitListener(dialog, edit, editorExitable)); }); dialog.show(); } public void openLoadDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); builder.setTitle(R.string.global_load); builder.setPositiveButton(android.R.string.cancel, null); final AlertDialog dialog = builder.create(); FileListView flv = new FileListView(dialog, "json"); if(Build.VERSION.SDK_INT < 29)flv.listFileAt(new File(Tools.CTRLMAP_PATH)); else flv.lockPathAt(new File(Tools.CTRLMAP_PATH)); flv.setFileSelectedListener(new FileSelectedListener(){ @Override public void onFileSelected(File file, String path) { try { loadLayout(path); }catch (IOException e) { Tools.showError(getContext(), e); } dialog.dismiss(); } }); dialog.setView(flv); dialog.show(); } public void openSetDefaultDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); builder.setTitle(R.string.customctrl_selectdefault); builder.setPositiveButton(android.R.string.cancel, null); final AlertDialog dialog = builder.create(); FileListView flv = new FileListView(dialog, "json"); flv.lockPathAt(new File(Tools.CTRLMAP_PATH)); flv.setFileSelectedListener(new FileSelectedListener(){ @Override public void onFileSelected(File file, String path) { try { LauncherPreferences.DEFAULT_PREF.edit().putString("defaultCtrl", path).apply(); LauncherPreferences.PREF_DEFAULTCTRL_PATH = path;loadLayout(path); }catch (IOException|JsonSyntaxException e) { Tools.showError(getContext(), e); } dialog.dismiss(); } }); dialog.setView(flv); dialog.show(); } public void openExitDialog(EditorExitable exitListener) { AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); builder.setTitle(R.string.customctrl_editor_exit_title); builder.setMessage(R.string.customctrl_editor_exit_msg); builder.setPositiveButton(R.string.global_yes, (d,w)->exitListener.exitEditor()); builder.setNegativeButton(R.string.global_no, (d,w)->{}); builder.show(); } public boolean areControlVisible(){ return mControlVisible; } }
18,069
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
LayoutConverter.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/customcontrols/LayoutConverter.java
package net.kdt.pojavlaunch.customcontrols; import com.google.gson.JsonSyntaxException; import net.kdt.pojavlaunch.LwjglGlfwKeycode; import net.kdt.pojavlaunch.Tools; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.lwjgl.glfw.CallbackBridge; import java.io.IOException; import java.util.ArrayList; public class LayoutConverter { public static CustomControls loadAndConvertIfNecessary(String jsonPath) throws IOException, JsonSyntaxException { String jsonLayoutData = Tools.read(jsonPath); try { JSONObject layoutJobj = new JSONObject(jsonLayoutData); if (!layoutJobj.has("version")) { //v1 layout CustomControls layout = LayoutConverter.convertV1Layout(layoutJobj); layout.save(jsonPath); return layout; } else if (layoutJobj.getInt("version") == 2) { CustomControls layout = LayoutConverter.convertV2Layout(layoutJobj); layout.save(jsonPath); return layout; }else if (layoutJobj.getInt("version") >= 3 && layoutJobj.getInt("version") <= 5) { return LayoutConverter.convertV3_4Layout(layoutJobj); } else if (layoutJobj.getInt("version") == 6) { return Tools.GLOBAL_GSON.fromJson(jsonLayoutData, CustomControls.class); } else { return null; } } catch (JSONException e) { throw new JsonSyntaxException("Failed to load", e); } } /** * Normalize the layout to v6 from v3/4: The stroke width is no longer dependant on the button size */ public static CustomControls convertV3_4Layout(JSONObject oldLayoutJson) { CustomControls layout = Tools.GLOBAL_GSON.fromJson(oldLayoutJson.toString(), CustomControls.class); convertStrokeWidth(layout); layout.version = 6; return layout; } public static CustomControls convertV2Layout(JSONObject oldLayoutJson) throws JSONException { CustomControls layout = Tools.GLOBAL_GSON.fromJson(oldLayoutJson.toString(), CustomControls.class); JSONArray layoutMainArray = oldLayoutJson.getJSONArray("mControlDataList"); layout.mControlDataList = new ArrayList<>(layoutMainArray.length()); for (int i = 0; i < layoutMainArray.length(); i++) { JSONObject button = layoutMainArray.getJSONObject(i); ControlData n_button = Tools.GLOBAL_GSON.fromJson(button.toString(), ControlData.class); if (!Tools.isValidString(n_button.dynamicX) && button.has("x")) { double buttonC = button.getDouble("x"); double ratio = buttonC / CallbackBridge.physicalWidth; n_button.dynamicX = ratio + " * ${screen_width}"; } if (!Tools.isValidString(n_button.dynamicY) && button.has("y")) { double buttonC = button.getDouble("y"); double ratio = buttonC / CallbackBridge.physicalHeight; n_button.dynamicY = ratio + " * ${screen_height}"; } layout.mControlDataList.add(n_button); } JSONArray layoutDrawerArray = oldLayoutJson.getJSONArray("mDrawerDataList"); layout.mDrawerDataList = new ArrayList<>(); for (int i = 0; i < layoutDrawerArray.length(); i++) { JSONObject button = layoutDrawerArray.getJSONObject(i); JSONObject buttonProperties = button.getJSONObject("properties"); ControlDrawerData n_button = Tools.GLOBAL_GSON.fromJson(button.toString(), ControlDrawerData.class); if (!Tools.isValidString(n_button.properties.dynamicX) && buttonProperties.has("x")) { double buttonC = buttonProperties.getDouble("x"); double ratio = buttonC / CallbackBridge.physicalWidth; n_button.properties.dynamicX = ratio + " * ${screen_width}"; } if (!Tools.isValidString(n_button.properties.dynamicY) && buttonProperties.has("y")) { double buttonC = buttonProperties.getDouble("y"); double ratio = buttonC / CallbackBridge.physicalHeight; n_button.properties.dynamicY = ratio + " * ${screen_height}"; } layout.mDrawerDataList.add(n_button); } convertStrokeWidth(layout); layout.version = 3; return layout; } public static CustomControls convertV1Layout(JSONObject oldLayoutJson) throws JSONException { CustomControls empty = new CustomControls(); JSONArray layoutMainArray = oldLayoutJson.getJSONArray("mControlDataList"); for (int i = 0; i < layoutMainArray.length(); i++) { JSONObject button = layoutMainArray.getJSONObject(i); ControlData n_button = new ControlData(); int[] keycodes = new int[]{LwjglGlfwKeycode.GLFW_KEY_UNKNOWN, LwjglGlfwKeycode.GLFW_KEY_UNKNOWN, LwjglGlfwKeycode.GLFW_KEY_UNKNOWN, LwjglGlfwKeycode.GLFW_KEY_UNKNOWN}; n_button.isDynamicBtn = button.getBoolean("isDynamicBtn"); n_button.dynamicX = button.getString("dynamicX"); n_button.dynamicY = button.getString("dynamicY"); if (!Tools.isValidString(n_button.dynamicX) && button.has("x")) { double buttonC = button.getDouble("x"); double ratio = buttonC / CallbackBridge.physicalWidth; n_button.dynamicX = ratio + " * ${screen_width}"; } if (!Tools.isValidString(n_button.dynamicY) && button.has("y")) { double buttonC = button.getDouble("y"); double ratio = buttonC / CallbackBridge.physicalHeight; n_button.dynamicY = ratio + " * ${screen_height}"; } n_button.name = button.getString("name"); n_button.opacity = ((float) ((button.getInt("transparency") - 100) * -1)) / 100f; n_button.passThruEnabled = button.getBoolean("passThruEnabled"); n_button.isToggle = button.getBoolean("isToggle"); n_button.setHeight(button.getInt("height")); n_button.setWidth(button.getInt("width")); n_button.bgColor = 0x4d000000; n_button.strokeWidth = 0; if (button.getBoolean("isRound")) { n_button.cornerRadius = 35f; } int next_idx = 0; if (button.getBoolean("holdShift")) { keycodes[next_idx] = LwjglGlfwKeycode.GLFW_KEY_LEFT_SHIFT; next_idx++; } if (button.getBoolean("holdCtrl")) { keycodes[next_idx] = LwjglGlfwKeycode.GLFW_KEY_LEFT_CONTROL; next_idx++; } if (button.getBoolean("holdAlt")) { keycodes[next_idx] = LwjglGlfwKeycode.GLFW_KEY_LEFT_ALT; next_idx++; } keycodes[next_idx] = button.getInt("keycode"); n_button.keycodes = keycodes; empty.mControlDataList.add(n_button); } empty.scaledAt = (float) oldLayoutJson.getDouble("scaledAt"); empty.version = 3; return empty; } /** * Convert the layout stroke width to the V5 form */ private static void convertStrokeWidth(CustomControls layout) { for (ControlData data : layout.mControlDataList) { data.strokeWidth = Tools.pxToDp(computeStrokeWidth(data.strokeWidth, data.getWidth(), data.getHeight())); } for (ControlDrawerData data : layout.mDrawerDataList) { data.properties.strokeWidth = Tools.pxToDp(computeStrokeWidth(data.properties.strokeWidth, data.properties.getWidth(), data.properties.getHeight())); for (ControlData subButtonData : data.buttonProperties) { subButtonData.strokeWidth = Tools.pxToDp(computeStrokeWidth(subButtonData.strokeWidth, data.properties.getWidth(), data.properties.getWidth())); } } } /** * Convert a size percentage into a px size, used by older layout versions */ static int computeStrokeWidth(float widthInPercent, float width, float height) { float maxSize = Math.max(width, height); return (int) ((maxSize / 2) * (widthInPercent / 100)); } }
8,405
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
ControlDrawerData.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/customcontrols/ControlDrawerData.java
package net.kdt.pojavlaunch.customcontrols; import net.kdt.pojavlaunch.Tools; import java.util.ArrayList; import static net.kdt.pojavlaunch.customcontrols.ControlDrawerData.Orientation.DOWN; import static net.kdt.pojavlaunch.customcontrols.ControlDrawerData.Orientation.LEFT; import static net.kdt.pojavlaunch.customcontrols.ControlDrawerData.Orientation.RIGHT; import static net.kdt.pojavlaunch.customcontrols.ControlDrawerData.Orientation.UP; import static net.kdt.pojavlaunch.customcontrols.ControlDrawerData.Orientation.FREE; @androidx.annotation.Keep public class ControlDrawerData { public final ArrayList<ControlData> buttonProperties; public final ControlData properties; public Orientation orientation; @androidx.annotation.Keep public enum Orientation { DOWN, LEFT, UP, RIGHT, FREE } public static Orientation[] getOrientations(){ return new Orientation[]{DOWN,LEFT,UP,RIGHT,FREE}; } public static int orientationToInt(Orientation orientation){ switch (orientation){ case DOWN: return 0; case LEFT: return 1; case UP: return 2; case RIGHT: return 3; case FREE: return 4; } return -1; } public static Orientation intToOrientation(int by){ switch (by){ case 0: return DOWN; case 1: return LEFT; case 2: return UP; case 3: return RIGHT; case 4: return FREE; } return null; } public ControlDrawerData(){ this(new ArrayList<>()); } public ControlDrawerData(ArrayList<ControlData> buttonProperties){ this(buttonProperties, new ControlData("Drawer", new int[] {}, Tools.currentDisplayMetrics.widthPixels/2f, Tools.currentDisplayMetrics.heightPixels/2f)); } public ControlDrawerData(ArrayList<ControlData> buttonProperties, ControlData properties){ this(buttonProperties, properties, Orientation.LEFT); } public ControlDrawerData(ArrayList<ControlData> buttonProperties, ControlData properties, Orientation orientation){ this.buttonProperties = buttonProperties; this.properties = properties; this.orientation = orientation; } public ControlDrawerData(ControlDrawerData drawerData){ buttonProperties = new ArrayList<>(drawerData.buttonProperties.size()); for(ControlData controlData : drawerData.buttonProperties){ buttonProperties.add(new ControlData(controlData)); } properties = new ControlData(drawerData.properties); orientation = drawerData.orientation; } }
2,686
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
ControlJoystickData.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/customcontrols/ControlJoystickData.java
package net.kdt.pojavlaunch.customcontrols; public class ControlJoystickData extends ControlData { /* Whether the joystick can stay forward */ public boolean forwardLock = false; /* * Whether the finger tracking is absolute (joystick jumps to where you touched) * or relative (joystick stays in the center) */ public boolean absolute = false; public ControlJoystickData(){ super(); } public ControlJoystickData(ControlJoystickData properties) { super(properties); forwardLock = properties.forwardLock; absolute = properties.absolute; } }
621
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
ActionRow.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/customcontrols/handleview/ActionRow.java
package net.kdt.pojavlaunch.customcontrols.handleview; import static net.kdt.pojavlaunch.Tools.currentDisplayMetrics; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.widget.LinearLayout; import androidx.annotation.Nullable; import androidx.core.math.MathUtils; import net.kdt.pojavlaunch.R; import net.kdt.pojavlaunch.customcontrols.buttons.ControlInterface; /** * Layout floating around a Control Button, displaying contextual actions */ public class ActionRow extends LinearLayout { public static final int SIDE_LEFT = 0x0; public static final int SIDE_TOP = 0x1; public static final int SIDE_RIGHT = 0x2; public static final int SIDE_BOTTOM = 0x3; public static final int SIDE_AUTO = 0x4; public ActionRow(Context context) { super(context); init(); } public ActionRow(Context context, @Nullable AttributeSet attrs) { super(context, attrs); init(); } public final ViewTreeObserver.OnPreDrawListener mFollowedViewListener = new ViewTreeObserver.OnPreDrawListener() { @Override public boolean onPreDraw() { if(mFollowedView == null || !mFollowedView.isShown()){ hide(); return true; } setNewPosition(); return true; } }; private final ActionButtonInterface[] actionButtons = new ActionButtonInterface[3]; private View mFollowedView = null; private final int mSide = SIDE_AUTO; /** Add action buttons and configure them */ private void init(){ setTranslationZ(11); setVisibility(GONE); setOrientation(HORIZONTAL); setLayoutParams(new LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, getResources().getDimensionPixelOffset(R.dimen._40sdp) )); actionButtons[0] = new DeleteButton(getContext()); actionButtons[1] = new CloneButton(getContext()); actionButtons[2] = new AddSubButton(getContext()); // This is not pretty code, don't do this. for(ActionButtonInterface buttonInterface: actionButtons){ View button = ((View)(buttonInterface)); addView(button, new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, 1F)); } setElevation(5F); } public void setFollowedButton(ControlInterface controlInterface){ if(mFollowedView != null) mFollowedView.getViewTreeObserver().removeOnPreDrawListener(mFollowedViewListener); for(ActionButtonInterface buttonInterface: actionButtons){ buttonInterface.setFollowedView(controlInterface); ((View)(buttonInterface)).setVisibility(buttonInterface.shouldBeVisible() ? VISIBLE : GONE); } setVisibility(VISIBLE); mFollowedView = (View) controlInterface; if(mFollowedView != null) mFollowedView.getViewTreeObserver().addOnPreDrawListener(mFollowedViewListener); } private float getXPosition(int side){ if(side == SIDE_LEFT){ return mFollowedView.getX() - getWidth(); }else if(side == SIDE_RIGHT){ return mFollowedView.getX() + mFollowedView.getWidth(); }else{ return mFollowedView.getX() + mFollowedView.getWidth()/2f - getWidth()/2f; } } private float getYPosition(int side){ if(side == SIDE_TOP){ return mFollowedView.getY() - getHeight(); } else if(side == SIDE_BOTTOM){ return mFollowedView.getY() + mFollowedView.getHeight(); }else{ return mFollowedView.getY() + mFollowedView.getHeight()/2f - getHeight()/2f; } } private void setNewPosition(){ if(mFollowedView == null) return; int side = pickSide(); setX(MathUtils.clamp(getXPosition(side), 0, currentDisplayMetrics.widthPixels - getWidth())); setY(getYPosition(side)); } private int pickSide(){ if(mFollowedView == null) return mSide; //Value should not matter if(mSide != SIDE_AUTO) return mSide; //TODO improve the "algo" ViewGroup parent = ((ViewGroup) mFollowedView.getParent()); if(parent == null) return mSide;//Value should not matter int side = SIDE_TOP; float futurePos = getYPosition(side); if(futurePos + getHeight() > (parent.getHeight() + getHeight()/2f)){ side = SIDE_TOP; }else if (futurePos < -getHeight()/2f){ side = SIDE_BOTTOM; } return side; } public void hide(){ if(mFollowedView != null) mFollowedView.getViewTreeObserver().removeOnPreDrawListener(mFollowedViewListener); setVisibility(GONE); } }
4,867
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
DrawerPullButton.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/customcontrols/handleview/DrawerPullButton.java
package net.kdt.pojavlaunch.customcontrols.handleview; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.AttributeSet; import android.view.View; import androidx.annotation.Nullable; import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat; import net.kdt.pojavlaunch.R; public class DrawerPullButton extends View { public DrawerPullButton(Context context) {super(context); init();} public DrawerPullButton(Context context, @Nullable AttributeSet attrs) {super(context, attrs); init();} private final Paint mPaint = new Paint(); private VectorDrawableCompat mDrawable; private void init(){ mDrawable = VectorDrawableCompat.create(getContext().getResources(), R.drawable.ic_sharp_settings_24, null); setAlpha(0.33f); } @Override protected void onDraw(Canvas canvas) { mPaint.setColor(Color.BLACK); canvas.drawArc(0,-getHeight(),getWidth(), getHeight(), 0, 180, true, mPaint); mPaint.setColor(Color.WHITE); mDrawable.setBounds(0, 0, getHeight(), getHeight()); canvas.save(); canvas.translate((getWidth()-getHeight())/2f, 0); mDrawable.draw(canvas); canvas.restore(); } }
1,301
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
EditControlPopup.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/customcontrols/handleview/EditControlPopup.java
package net.kdt.pojavlaunch.customcontrols.handleview; import static android.view.View.GONE; import static android.view.View.VISIBLE; import static net.kdt.pojavlaunch.Tools.currentDisplayMetrics; import android.animation.ObjectAnimator; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Color; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.AccelerateDecelerateInterpolator; import android.view.animation.Interpolator; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.EditText; import android.widget.SeekBar; import android.widget.Spinner; import android.widget.Switch; import android.widget.TextView; import androidx.constraintlayout.widget.ConstraintLayout; import com.kdt.DefocusableScrollView; import net.kdt.pojavlaunch.EfficientAndroidLWJGLKeycode; import net.kdt.pojavlaunch.R; import net.kdt.pojavlaunch.colorselector.ColorSelector; import net.kdt.pojavlaunch.customcontrols.ControlData; import net.kdt.pojavlaunch.customcontrols.ControlDrawerData; import net.kdt.pojavlaunch.customcontrols.ControlJoystickData; import net.kdt.pojavlaunch.customcontrols.buttons.ControlDrawer; import net.kdt.pojavlaunch.customcontrols.buttons.ControlInterface; import java.util.List; /** * Class providing a sort of popup on top of a Layout, allowing to edit a given ControlButton */ public class EditControlPopup { protected final Spinner[] mKeycodeSpinners = new Spinner[4]; private final DefocusableScrollView mScrollView; private final ColorSelector mColorSelector; private final ObjectAnimator mEditPopupAnimator; private final ObjectAnimator mColorEditorAnimator; private final int mMargin; public boolean internalChanges = false; // True when we programmatically change stuff. private final View.OnLayoutChangeListener mLayoutChangedListener = new View.OnLayoutChangeListener() { @Override public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) { if (internalChanges) return; internalChanges = true; int width = (int) (safeParseFloat(mWidthEditText.getText().toString())); if (width >= 0 && Math.abs(right - width) > 1) { mWidthEditText.setText(String.valueOf(right - left)); } int height = (int) (safeParseFloat(mHeightEditText.getText().toString())); if (height >= 0 && Math.abs(bottom - height) > 1) { mHeightEditText.setText(String.valueOf(bottom - top)); } internalChanges = false; } }; protected EditText mNameEditText, mWidthEditText, mHeightEditText; @SuppressLint("UseSwitchCompatOrMaterialCode") protected Switch mToggleSwitch, mPassthroughSwitch, mSwipeableSwitch, mForwardLockSwitch, mAbsoluteTrackingSwitch; protected Spinner mOrientationSpinner; protected TextView[] mKeycodeTextviews = new TextView[4]; protected SeekBar mStrokeWidthSeekbar, mCornerRadiusSeekbar, mAlphaSeekbar; protected TextView mStrokePercentTextView, mCornerRadiusPercentTextView, mAlphaPercentTextView; protected TextView mSelectBackgroundColor, mSelectStrokeColor; protected ArrayAdapter<String> mAdapter; protected List<String> mSpecialArray; protected CheckBox mDisplayInGameCheckbox, mDisplayInMenuCheckbox; private ConstraintLayout mRootView; private boolean mDisplaying = false; private boolean mDisplayingColor = false; private ControlInterface mCurrentlyEditedButton; // Decorative textviews private TextView mOrientationTextView, mMappingTextView, mNameTextView, mCornerRadiusTextView, mVisibilityTextView, mSizeTextview, mSizeXTextView; public EditControlPopup(Context context, ViewGroup parent) { mScrollView = (DefocusableScrollView) LayoutInflater.from(context).inflate(R.layout.dialog_control_button_setting, parent, false); parent.addView(mScrollView); mMargin = context.getResources().getDimensionPixelOffset(R.dimen._20sdp); mColorSelector = new ColorSelector(context, parent, null); mColorSelector.getRootView().setElevation(11); mColorSelector.getRootView().setTranslationZ(11); mColorSelector.getRootView().setX(-context.getResources().getDimensionPixelOffset(R.dimen._280sdp)); mEditPopupAnimator = ObjectAnimator.ofFloat(mScrollView, "x", 0).setDuration(600); mColorEditorAnimator = ObjectAnimator.ofFloat(mColorSelector.getRootView(), "x", 0).setDuration(600); Interpolator decelerate = new AccelerateDecelerateInterpolator(); mEditPopupAnimator.setInterpolator(decelerate); mColorEditorAnimator.setInterpolator(decelerate); mScrollView.setElevation(10); mScrollView.setTranslationZ(10); mScrollView.setX(-context.getResources().getDimensionPixelOffset(R.dimen._280sdp)); bindLayout(); loadAdapter(); setupRealTimeListeners(); } public static void setPercentageText(TextView textView, int progress) { textView.setText(textView.getContext().getString(R.string.percent_format, progress)); } /** * Slide the layout into the visible screen area */ public void appear(boolean fromRight) { disappearColor(); // When someone jumps from a button to another if (fromRight) { if (!mDisplaying || !isAtRight()) { mEditPopupAnimator.setFloatValues(currentDisplayMetrics.widthPixels, currentDisplayMetrics.widthPixels - mScrollView.getWidth() - mMargin); mEditPopupAnimator.start(); } } else { if (!mDisplaying || isAtRight()) { mEditPopupAnimator.setFloatValues(-mScrollView.getWidth(), mMargin); mEditPopupAnimator.start(); } } mDisplaying = true; } /** * Slide out the layout */ public void disappear() { if (!mDisplaying) return; mDisplaying = false; if (isAtRight()) mEditPopupAnimator.setFloatValues(currentDisplayMetrics.widthPixels - mScrollView.getWidth() - mMargin, currentDisplayMetrics.widthPixels); else mEditPopupAnimator.setFloatValues(mMargin, -mScrollView.getWidth()); mEditPopupAnimator.start(); } /** * Slide the layout into the visible screen area */ public void appearColor(boolean fromRight, int color) { if (fromRight) { if (!mDisplayingColor || !isAtRight()) { mColorEditorAnimator.setFloatValues(currentDisplayMetrics.widthPixels, currentDisplayMetrics.widthPixels - mScrollView.getWidth() - mMargin); mColorEditorAnimator.start(); } } else { if (!mDisplayingColor || isAtRight()) { mColorEditorAnimator.setFloatValues(-mScrollView.getWidth(), mMargin); mColorEditorAnimator.start(); } } // Adjust the color selector to have the same size as the control settings ViewGroup.LayoutParams params = mColorSelector.getRootView().getLayoutParams(); params.height = mScrollView.getHeight(); mColorSelector.getRootView().setLayoutParams(params); mDisplayingColor = true; mColorSelector.show(color == -1 ? Color.WHITE : color); } /** * Slide out the layout */ public void disappearColor() { if (!mDisplayingColor) return; mDisplayingColor = false; if (isAtRight()) mColorEditorAnimator.setFloatValues(currentDisplayMetrics.widthPixels - mScrollView.getWidth() - mMargin, currentDisplayMetrics.widthPixels); else mColorEditorAnimator.setFloatValues(mMargin, -mScrollView.getWidth()); mColorEditorAnimator.start(); } /** * Slide out the first visible layer. * * @return True if the last layer is disappearing */ public boolean disappearLayer() { if (mDisplayingColor) { disappearColor(); return false; } else { disappear(); return true; } } /** * Switch the panels position if needed */ public void adaptPanelPosition() { if (mDisplaying) { boolean isAtRight = mCurrentlyEditedButton.getControlView().getX() + mCurrentlyEditedButton.getControlView().getWidth() / 2f < currentDisplayMetrics.widthPixels / 2f; appear(isAtRight); } } public void destroy() { ((ViewGroup) mScrollView.getParent()).removeView(mColorSelector.getRootView()); ((ViewGroup) mScrollView.getParent()).removeView(mScrollView); } private void loadAdapter() { //Initialize adapter for keycodes mAdapter = new ArrayAdapter<>(mRootView.getContext(), R.layout.item_centered_textview); mSpecialArray = ControlData.buildSpecialButtonArray(); mAdapter.addAll(mSpecialArray); mAdapter.addAll(EfficientAndroidLWJGLKeycode.generateKeyName()); mAdapter.setDropDownViewResource(android.R.layout.simple_list_item_single_choice); for (Spinner spinner : mKeycodeSpinners) { spinner.setAdapter(mAdapter); } // Orientation spinner ArrayAdapter<ControlDrawerData.Orientation> adapter = new ArrayAdapter<>(mScrollView.getContext(), android.R.layout.simple_spinner_item); adapter.addAll(ControlDrawerData.getOrientations()); adapter.setDropDownViewResource(android.R.layout.simple_list_item_single_choice); mOrientationSpinner.setAdapter(adapter); } private void setDefaultVisibilitySetting() { for (int i = 0; i < mRootView.getChildCount(); ++i) { mRootView.getChildAt(i).setVisibility(VISIBLE); } for(Spinner s : mKeycodeSpinners) { s.setVisibility(View.INVISIBLE); } } private boolean isAtRight() { return mScrollView.getX() > currentDisplayMetrics.widthPixels / 2f; } /* LOADING VALUES */ /** * Load values for basic control data */ public void loadValues(ControlData data) { setDefaultVisibilitySetting(); mOrientationTextView.setVisibility(GONE); mOrientationSpinner.setVisibility(GONE); mForwardLockSwitch.setVisibility(GONE); mAbsoluteTrackingSwitch.setVisibility(GONE); mNameEditText.setText(data.name); mWidthEditText.setText(String.valueOf(data.getWidth())); mHeightEditText.setText(String.valueOf(data.getHeight())); mAlphaSeekbar.setProgress((int) (data.opacity * 100)); mStrokeWidthSeekbar.setProgress((int) data.strokeWidth * 10); mCornerRadiusSeekbar.setProgress((int) data.cornerRadius); setPercentageText(mAlphaPercentTextView, (int) (data.opacity * 100)); setPercentageText(mStrokePercentTextView, (int) data.strokeWidth * 10); setPercentageText(mCornerRadiusPercentTextView, (int) data.cornerRadius); mToggleSwitch.setChecked(data.isToggle); mPassthroughSwitch.setChecked(data.passThruEnabled); mSwipeableSwitch.setChecked(data.isSwipeable); mDisplayInGameCheckbox.setChecked(data.displayInGame); mDisplayInMenuCheckbox.setChecked(data.displayInMenu); for (int i = 0; i < data.keycodes.length; i++) { if (data.keycodes[i] < 0) { mKeycodeSpinners[i].setSelection(data.keycodes[i] + mSpecialArray.size()); } else { mKeycodeSpinners[i].setSelection(EfficientAndroidLWJGLKeycode.getIndexByValue(data.keycodes[i]) + mSpecialArray.size()); } } } /** * Load values for extended control data */ public void loadValues(ControlDrawerData data) { loadValues(data.properties); mOrientationSpinner.setSelection( ControlDrawerData.orientationToInt(data.orientation)); mMappingTextView.setVisibility(GONE); for (int i = 0; i < mKeycodeSpinners.length; i++) { mKeycodeSpinners[i].setVisibility(GONE); mKeycodeTextviews[i].setVisibility(GONE); } mOrientationTextView.setVisibility(VISIBLE); mOrientationSpinner.setVisibility(VISIBLE); mSwipeableSwitch.setVisibility(View.GONE); mPassthroughSwitch.setVisibility(View.GONE); mToggleSwitch.setVisibility(View.GONE); } /** * Load values for the joystick */ public void loadJoystickValues(ControlJoystickData data) { loadValues(data); mMappingTextView.setVisibility(GONE); for (int i = 0; i < mKeycodeSpinners.length; i++) { mKeycodeSpinners[i].setVisibility(GONE); mKeycodeTextviews[i].setVisibility(GONE); } mNameTextView.setVisibility(GONE); mNameEditText.setVisibility(GONE); mCornerRadiusTextView.setVisibility(GONE); mCornerRadiusSeekbar.setVisibility(GONE); mCornerRadiusPercentTextView.setVisibility(GONE); mSwipeableSwitch.setVisibility(View.GONE); mPassthroughSwitch.setVisibility(View.GONE); mToggleSwitch.setVisibility(View.GONE); mForwardLockSwitch.setVisibility(VISIBLE); mForwardLockSwitch.setChecked(data.forwardLock); mAbsoluteTrackingSwitch.setVisibility(VISIBLE); mAbsoluteTrackingSwitch.setChecked(data.absolute); } /** * Load values for sub buttons */ public void loadSubButtonValues(ControlData data, ControlDrawerData.Orientation drawerOrientation) { loadValues(data); // Size linked to the parent drawer depending on the drawer settings if(drawerOrientation != ControlDrawerData.Orientation.FREE){ mSizeTextview.setVisibility(GONE); mSizeXTextView.setVisibility(GONE); mWidthEditText.setVisibility(GONE); mHeightEditText.setVisibility(GONE); } // No conditional, already depends on the parent drawer visibility mVisibilityTextView.setVisibility(GONE); mDisplayInMenuCheckbox.setVisibility(GONE); mDisplayInGameCheckbox.setVisibility(GONE); } private void bindLayout() { mRootView = mScrollView.findViewById(R.id.edit_layout); mNameEditText = mScrollView.findViewById(R.id.editName_editText); mWidthEditText = mScrollView.findViewById(R.id.editSize_editTextX); mHeightEditText = mScrollView.findViewById(R.id.editSize_editTextY); mToggleSwitch = mScrollView.findViewById(R.id.checkboxToggle); mPassthroughSwitch = mScrollView.findViewById(R.id.checkboxPassThrough); mSwipeableSwitch = mScrollView.findViewById(R.id.checkboxSwipeable); mForwardLockSwitch = mScrollView.findViewById(R.id.checkboxForwardLock); mAbsoluteTrackingSwitch = mScrollView.findViewById(R.id.checkboxAbsoluteFingerTracking); mKeycodeSpinners[0] = mScrollView.findViewById(R.id.editMapping_spinner_1); mKeycodeSpinners[1] = mScrollView.findViewById(R.id.editMapping_spinner_2); mKeycodeSpinners[2] = mScrollView.findViewById(R.id.editMapping_spinner_3); mKeycodeSpinners[3] = mScrollView.findViewById(R.id.editMapping_spinner_4); mKeycodeTextviews[0] = mScrollView.findViewById(R.id.mapping_1_textview); mKeycodeTextviews[1] = mScrollView.findViewById(R.id.mapping_2_textview); mKeycodeTextviews[2] = mScrollView.findViewById(R.id.mapping_3_textview); mKeycodeTextviews[3] = mScrollView.findViewById(R.id.mapping_4_textview); mOrientationSpinner = mScrollView.findViewById(R.id.editOrientation_spinner); mStrokeWidthSeekbar = mScrollView.findViewById(R.id.editStrokeWidth_seekbar); mCornerRadiusSeekbar = mScrollView.findViewById(R.id.editCornerRadius_seekbar); mAlphaSeekbar = mScrollView.findViewById(R.id.editButtonOpacity_seekbar); mSelectBackgroundColor = mScrollView.findViewById(R.id.editBackgroundColor_textView); mSelectStrokeColor = mScrollView.findViewById(R.id.editStrokeColor_textView); mStrokePercentTextView = mScrollView.findViewById(R.id.editStrokeWidth_textView_percent); mAlphaPercentTextView = mScrollView.findViewById(R.id.editButtonOpacity_textView_percent); mCornerRadiusPercentTextView = mScrollView.findViewById(R.id.editCornerRadius_textView_percent); mDisplayInGameCheckbox = mScrollView.findViewById(R.id.visibility_game_checkbox); mDisplayInMenuCheckbox = mScrollView.findViewById(R.id.visibility_menu_checkbox); //Decorative stuff mMappingTextView = mScrollView.findViewById(R.id.editMapping_textView); mOrientationTextView = mScrollView.findViewById(R.id.editOrientation_textView); mNameTextView = mScrollView.findViewById(R.id.editName_textView); mCornerRadiusTextView = mScrollView.findViewById(R.id.editCornerRadius_textView); mVisibilityTextView = mScrollView.findViewById(R.id.visibility_textview); mSizeTextview = mScrollView.findViewById(R.id.editSize_textView); mSizeXTextView = mScrollView.findViewById(R.id.editSize_x_textView); } /** * A long function linking all the displayed data on the popup and, * the currently edited mCurrentlyEditedButton */ public void setupRealTimeListeners() { mNameEditText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { if (internalChanges) return; mCurrentlyEditedButton.getProperties().name = s.toString(); // Cheap and unoptimized, doesn't break the abstraction layer mCurrentlyEditedButton.setProperties(mCurrentlyEditedButton.getProperties(), false); } }); mWidthEditText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { if (internalChanges) return; float width = safeParseFloat(s.toString()); if (width >= 0) { mCurrentlyEditedButton.getProperties().setWidth(width); mCurrentlyEditedButton.updateProperties(); } } }); mHeightEditText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { if (internalChanges) return; float height = safeParseFloat(s.toString()); if (height >= 0) { mCurrentlyEditedButton.getProperties().setHeight(height); mCurrentlyEditedButton.updateProperties(); } } }); mSwipeableSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> { if (internalChanges) return; mCurrentlyEditedButton.getProperties().isSwipeable = isChecked; }); mToggleSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> { if (internalChanges) return; mCurrentlyEditedButton.getProperties().isToggle = isChecked; }); mPassthroughSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> { if (internalChanges) return; mCurrentlyEditedButton.getProperties().passThruEnabled = isChecked; }); mForwardLockSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> { if (internalChanges) return; if(mCurrentlyEditedButton.getProperties() instanceof ControlJoystickData){ ((ControlJoystickData) mCurrentlyEditedButton.getProperties()).forwardLock = isChecked; } }); mAbsoluteTrackingSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> { if (internalChanges) return; if(mCurrentlyEditedButton.getProperties() instanceof ControlJoystickData){ ((ControlJoystickData) mCurrentlyEditedButton.getProperties()).absolute = isChecked; } }); mAlphaSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (internalChanges) return; mCurrentlyEditedButton.getProperties().opacity = mAlphaSeekbar.getProgress() / 100f; mCurrentlyEditedButton.getControlView().setAlpha(mAlphaSeekbar.getProgress() / 100f); setPercentageText(mAlphaPercentTextView, progress); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); mStrokeWidthSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (internalChanges) return; mCurrentlyEditedButton.getProperties().strokeWidth = mStrokeWidthSeekbar.getProgress() / 10F; mCurrentlyEditedButton.setBackground(); setPercentageText(mStrokePercentTextView, progress); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); mCornerRadiusSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (internalChanges) return; mCurrentlyEditedButton.getProperties().cornerRadius = mCornerRadiusSeekbar.getProgress(); mCurrentlyEditedButton.setBackground(); setPercentageText(mCornerRadiusPercentTextView, progress); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); for (int i = 0; i < mKeycodeSpinners.length; ++i) { int finalI = i; mKeycodeTextviews[i].setOnClickListener(v -> mKeycodeSpinners[finalI].performClick()); mKeycodeSpinners[i].setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { // Side note, spinner listeners are fired later than all the other ones. // Meaning the internalChanges bool is useless here. if (position < mSpecialArray.size()) { mCurrentlyEditedButton.getProperties().keycodes[finalI] = mKeycodeSpinners[finalI].getSelectedItemPosition() - mSpecialArray.size(); } else { mCurrentlyEditedButton.getProperties().keycodes[finalI] = EfficientAndroidLWJGLKeycode.getValueByIndex(mKeycodeSpinners[finalI].getSelectedItemPosition() - mSpecialArray.size()); } mKeycodeTextviews[finalI].setText((String) mKeycodeSpinners[finalI].getSelectedItem()); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } mOrientationSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { // Side note, spinner listeners are fired later than all the other ones. // Meaning the internalChanges bool is useless here. if (mCurrentlyEditedButton instanceof ControlDrawer) { ((ControlDrawer) mCurrentlyEditedButton).drawerData.orientation = ControlDrawerData.intToOrientation(mOrientationSpinner.getSelectedItemPosition()); ((ControlDrawer) mCurrentlyEditedButton).syncButtons(); } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); mDisplayInGameCheckbox.setOnCheckedChangeListener((buttonView, isChecked) -> { if (internalChanges) return; mCurrentlyEditedButton.getProperties().displayInGame = isChecked; }); mDisplayInMenuCheckbox.setOnCheckedChangeListener((buttonView, isChecked) -> { if (internalChanges) return; mCurrentlyEditedButton.getProperties().displayInMenu = isChecked; }); mSelectStrokeColor.setOnClickListener(v -> { mColorSelector.setAlphaEnabled(false); mColorSelector.setColorSelectionListener(color -> { mCurrentlyEditedButton.getProperties().strokeColor = color; mCurrentlyEditedButton.setBackground(); }); appearColor(isAtRight(), mCurrentlyEditedButton.getProperties().strokeColor); }); mSelectBackgroundColor.setOnClickListener(v -> { mColorSelector.setAlphaEnabled(true); mColorSelector.setColorSelectionListener(color -> { mCurrentlyEditedButton.getProperties().bgColor = color; mCurrentlyEditedButton.setBackground(); }); appearColor(isAtRight(), mCurrentlyEditedButton.getProperties().bgColor); }); } private float safeParseFloat(String string) { float out = -1; // -1 try { out = Float.parseFloat(string); } catch (NumberFormatException e) { Log.e("EditControlPopup", e.toString()); } return out; } public void setCurrentlyEditedButton(ControlInterface button) { if (mCurrentlyEditedButton != null) mCurrentlyEditedButton.getControlView().removeOnLayoutChangeListener(mLayoutChangedListener); mCurrentlyEditedButton = button; mCurrentlyEditedButton.getControlView().addOnLayoutChangeListener(mLayoutChangedListener); } }
27,456
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
CloneButton.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/customcontrols/handleview/CloneButton.java
package net.kdt.pojavlaunch.customcontrols.handleview; import android.annotation.SuppressLint; import android.content.Context; import android.util.AttributeSet; import android.widget.Button; import androidx.annotation.Nullable; import net.kdt.pojavlaunch.R; import net.kdt.pojavlaunch.customcontrols.buttons.ControlInterface; @SuppressLint("AppCompatCustomView") public class CloneButton extends Button implements ActionButtonInterface { public CloneButton(Context context) {super(context); init();} public CloneButton(Context context, @Nullable AttributeSet attrs) {super(context, attrs); init();} public void init() { setOnClickListener(this); setAllCaps(true); setText(R.string.global_clone); } private ControlInterface mCurrentlySelectedButton = null; @Override public boolean shouldBeVisible() { return mCurrentlySelectedButton != null; } @Override public void setFollowedView(ControlInterface view) { mCurrentlySelectedButton = view; } @Override public void onClick() { if(mCurrentlySelectedButton == null) return; mCurrentlySelectedButton.cloneButton(); mCurrentlySelectedButton.getControlLayoutParent().removeEditWindow(); } }
1,265
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
DeleteButton.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/customcontrols/handleview/DeleteButton.java
package net.kdt.pojavlaunch.customcontrols.handleview; import android.annotation.SuppressLint; import android.content.Context; import android.util.AttributeSet; import android.widget.Button; import androidx.annotation.Nullable; import net.kdt.pojavlaunch.R; import net.kdt.pojavlaunch.customcontrols.buttons.ControlInterface; @SuppressLint("AppCompatCustomView") public class DeleteButton extends Button implements ActionButtonInterface { public DeleteButton(Context context) {super(context); init();} public DeleteButton(Context context, @Nullable AttributeSet attrs) {super(context, attrs); init();} public void init() { setOnClickListener(this); setAllCaps(true); setText(R.string.global_delete); } private ControlInterface mCurrentlySelectedButton = null; @Override public boolean shouldBeVisible() { return mCurrentlySelectedButton != null; } @Override public void setFollowedView(ControlInterface view) { mCurrentlySelectedButton = view; } @Override public void onClick() { if(mCurrentlySelectedButton == null) return; mCurrentlySelectedButton.removeButton(); } }
1,193
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
AddSubButton.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/customcontrols/handleview/AddSubButton.java
package net.kdt.pojavlaunch.customcontrols.handleview; import android.annotation.SuppressLint; import android.content.Context; import android.util.AttributeSet; import android.widget.Button; import androidx.annotation.Nullable; import net.kdt.pojavlaunch.R; import net.kdt.pojavlaunch.customcontrols.ControlData; import net.kdt.pojavlaunch.customcontrols.buttons.ControlDrawer; import net.kdt.pojavlaunch.customcontrols.buttons.ControlInterface; @SuppressLint("AppCompatCustomView") public class AddSubButton extends Button implements ActionButtonInterface { public AddSubButton(Context context) {super(context); init();} public AddSubButton(Context context, @Nullable AttributeSet attrs) {super(context, attrs); init();} public void init() { setText(R.string.customctrl_addsubbutton); setOnClickListener(this); } private ControlInterface mCurrentlySelectedButton = null; @Override public boolean shouldBeVisible() { return mCurrentlySelectedButton != null && mCurrentlySelectedButton instanceof ControlDrawer; } @Override public void setFollowedView(ControlInterface view) { mCurrentlySelectedButton = view; } @Override public void onClick() { if(mCurrentlySelectedButton instanceof ControlDrawer){ ((ControlDrawer)mCurrentlySelectedButton).getControlLayoutParent().addSubButton( (ControlDrawer)mCurrentlySelectedButton, new ControlData() ); } } }
1,528
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
ActionButtonInterface.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/customcontrols/handleview/ActionButtonInterface.java
package net.kdt.pojavlaunch.customcontrols.handleview; import android.view.View; import net.kdt.pojavlaunch.customcontrols.buttons.ControlInterface; /** Interface defining the behavior of action buttons */ public interface ActionButtonInterface extends View.OnClickListener { /** HAS TO BE CALLED BY THE CONSTRUCTOR */ void init(); /** Called when the button should be made aware of the current target */ void setFollowedView(ControlInterface view); /** Called when the button action should be executed on the target */ void onClick(); /** Whether the button should be shown, given the current contextual information that it has */ boolean shouldBeVisible(); @Override // Wrapper to remove the arg default void onClick(View v){onClick();} }
790
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
ControlHandleView.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/customcontrols/handleview/ControlHandleView.java
package net.kdt.pojavlaunch.customcontrols.handleview; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import androidx.annotation.Nullable; import androidx.core.content.res.ResourcesCompat; import net.kdt.pojavlaunch.R; import net.kdt.pojavlaunch.customcontrols.buttons.ControlInterface; public class ControlHandleView extends View { public ControlHandleView(Context context) { super(context); init(); } public ControlHandleView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); init(); } private final Drawable mDrawable = ResourcesCompat.getDrawable(getResources(), R.drawable.ic_view_handle, getContext().getTheme()); private ControlInterface mView; private float mXOffset, mYOffset; private final ViewTreeObserver.OnPreDrawListener mPositionListener = new ViewTreeObserver.OnPreDrawListener() { @Override public boolean onPreDraw() { if(mView == null || !mView.getControlView().isShown()){ hide(); return true; } setX(mView.getControlView().getX() + mView.getControlView().getWidth()); setY(mView.getControlView().getY() + mView.getControlView().getHeight()); return true; } }; private void init(){ int size = getResources().getDimensionPixelOffset(R.dimen._22sdp); mDrawable.setBounds(0,0,size,size); ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(size, size); setLayoutParams(params); setBackground(mDrawable); setTranslationZ(10.5F); } public void setControlButton(ControlInterface controlInterface){ if(mView != null) mView.getControlView().getViewTreeObserver().removeOnPreDrawListener(mPositionListener); setVisibility(VISIBLE); mView = controlInterface; mView.getControlView().getViewTreeObserver().addOnPreDrawListener(mPositionListener); setX(controlInterface.getControlView().getX() + controlInterface.getControlView().getWidth()); setY(controlInterface.getControlView().getY() + controlInterface.getControlView().getHeight()); } @SuppressLint("ClickableViewAccessibility") @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getActionMasked()){ case MotionEvent.ACTION_DOWN: mXOffset = event.getX(); mYOffset = event.getY(); break; case MotionEvent.ACTION_MOVE: setX(getX() + event.getX() - mXOffset); setY(getY() + event.getY() - mYOffset); System.out.println(getX() - mView.getControlView().getX()); System.out.println(getY() - mView.getControlView().getY()); mView.getProperties().setWidth(getX() - mView.getControlView().getX()); mView.getProperties().setHeight(getY() - mView.getControlView().getY()); mView.regenerateDynamicCoordinates(); break; } return true; } public void hide(){ if(mView != null) mView.getControlView().getViewTreeObserver().removeOnPreDrawListener(mPositionListener); setVisibility(GONE); } }
3,509
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
RightClickGesture.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/customcontrols/mouse/RightClickGesture.java
package net.kdt.pojavlaunch.customcontrols.mouse; import android.os.Handler; import net.kdt.pojavlaunch.LwjglGlfwKeycode; import org.lwjgl.glfw.CallbackBridge; public class RightClickGesture extends ValidatorGesture{ private boolean mGestureEnabled = true; private boolean mGestureValid = true; private float mGestureStartX, mGestureStartY; public RightClickGesture(Handler mHandler) { super(mHandler, 150); } public final void inputEvent() { if(!mGestureEnabled) return; if(submit()) { mGestureStartX = CallbackBridge.mouseX; mGestureStartY = CallbackBridge.mouseY; mGestureEnabled = false; mGestureValid = true; } } @Override public boolean checkAndTrigger() { // If the validate() method was called, it means that the user held on for too long. The cancellation should be ignored. mGestureValid = false; // Never call onGestureCancelled. This way we will be able to reserve that only for when // the gesture is stopped in the code (when the user lets go of the screen or the tap was // cancelled by turning on the grab) return true; } @Override public void onGestureCancelled(boolean isSwitching) { mGestureEnabled = true; if(!mGestureValid || isSwitching) return; boolean fingerStill = LeftClickGesture.isFingerStill(mGestureStartX, mGestureStartY); if(!fingerStill) return; CallbackBridge.sendMouseButton(LwjglGlfwKeycode.GLFW_MOUSE_BUTTON_RIGHT, true); CallbackBridge.sendMouseButton(LwjglGlfwKeycode.GLFW_MOUSE_BUTTON_RIGHT, false); } }
1,679
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
InGUIEventProcessor.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/customcontrols/mouse/InGUIEventProcessor.java
package net.kdt.pojavlaunch.customcontrols.mouse; import android.view.GestureDetector; import android.view.MotionEvent; import net.kdt.pojavlaunch.LwjglGlfwKeycode; import net.kdt.pojavlaunch.SingleTapConfirm; import net.kdt.pojavlaunch.Tools; import net.kdt.pojavlaunch.prefs.LauncherPreferences; import org.lwjgl.glfw.CallbackBridge; public class InGUIEventProcessor implements TouchEventProcessor { public static final float FINGER_SCROLL_THRESHOLD = Tools.dpToPx(6); private final PointerTracker mTracker = new PointerTracker(); private final GestureDetector mSingleTapDetector; private AbstractTouchpad mTouchpad; private boolean mIsMouseDown = false; private final float mScaleFactor; private final Scroller mScroller = new Scroller(FINGER_SCROLL_THRESHOLD); public InGUIEventProcessor(float scaleFactor) { mSingleTapDetector = new GestureDetector(null, new SingleTapConfirm()); mScaleFactor = scaleFactor; } @Override public boolean processTouchEvent(MotionEvent motionEvent) { switch (motionEvent.getActionMasked()) { case MotionEvent.ACTION_DOWN: mTracker.startTracking(motionEvent); if(!touchpadDisplayed()) { sendTouchCoordinates(motionEvent.getX(), motionEvent.getY()); enableMouse(); } break; case MotionEvent.ACTION_MOVE: int pointerCount = motionEvent.getPointerCount(); int pointerIndex = mTracker.trackEvent(motionEvent); if(pointerCount == 1 || LauncherPreferences.PREF_DISABLE_GESTURES) { if(touchpadDisplayed()) { mTouchpad.applyMotionVector(mTracker.getMotionVector()); }else { float mainPointerX = motionEvent.getX(pointerIndex); float mainPointerY = motionEvent.getY(pointerIndex); sendTouchCoordinates(mainPointerX, mainPointerY); if(!mIsMouseDown) enableMouse(); } } else mScroller.performScroll(mTracker.getMotionVector()); break; case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: mScroller.resetScrollOvershoot(); mTracker.cancelTracking(); if(mIsMouseDown) disableMouse(); } if(touchpadDisplayed() && mSingleTapDetector.onTouchEvent(motionEvent)) clickMouse(); return true; } private boolean touchpadDisplayed() { return mTouchpad != null && mTouchpad.getDisplayState(); } public void setAbstractTouchpad(AbstractTouchpad touchpad) { mTouchpad = touchpad; } private void sendTouchCoordinates(float x, float y) { CallbackBridge.sendCursorPos( x * mScaleFactor, y * mScaleFactor); } private void enableMouse() { CallbackBridge.sendMouseButton(LwjglGlfwKeycode.GLFW_MOUSE_BUTTON_LEFT, true); mIsMouseDown = true; } private void disableMouse() { CallbackBridge.sendMouseButton(LwjglGlfwKeycode.GLFW_MOUSE_BUTTON_LEFT, false); mIsMouseDown = false; } private void clickMouse() { CallbackBridge.sendMouseButton(LwjglGlfwKeycode.GLFW_MOUSE_BUTTON_LEFT, true); CallbackBridge.sendMouseButton(LwjglGlfwKeycode.GLFW_MOUSE_BUTTON_LEFT, false); } @Override public void cancelPendingActions() { mScroller.resetScrollOvershoot(); disableMouse(); } }
3,589
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
DropGesture.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/customcontrols/mouse/DropGesture.java
package net.kdt.pojavlaunch.customcontrols.mouse; import static org.lwjgl.glfw.CallbackBridge.sendKeyPress; import android.os.Handler; import net.kdt.pojavlaunch.LwjglGlfwKeycode; import net.kdt.pojavlaunch.prefs.LauncherPreferences; public class DropGesture implements Runnable{ private final Handler mHandler; private boolean mActive; public DropGesture(Handler mHandler) { this.mHandler = mHandler; } public void submit() { if(!mActive) { mActive = true; mHandler.postDelayed(this, LauncherPreferences.PREF_LONGPRESS_TRIGGER); } } public void cancel() { mActive = false; mHandler.removeCallbacks(this); } @Override public void run() { if(!mActive) return; sendKeyPress(LwjglGlfwKeycode.GLFW_KEY_Q); mHandler.postDelayed(this, 250); } }
879
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
AbstractTouchpad.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/customcontrols/mouse/AbstractTouchpad.java
package net.kdt.pojavlaunch.customcontrols.mouse; public interface AbstractTouchpad { /** * Get the supposed display state of the mouse (whether it should be shown when the user is in a GUI) * Note that this does *not* reflect the actual visibility state of the mouse * @return current supposed enabled state */ boolean getDisplayState(); /** * Apply a motion vector to the mouse in form of a two-entry float array. This will move the mouse * on the screen and send the new cursor position to the game. * @param vector the array that contains the vector */ default void applyMotionVector(float[] vector) { applyMotionVector(vector[0], vector[1]); } /** * Apply a motion vector to the mouse in form of the separate X/Y coordinates. This will move the mouse * on the screen and send the new cursor position to the game. * @param x the relative X coordinate of the vector * @param y the relative Y coordinate for the vector */ void applyMotionVector(float x, float y); /** * Sets the state of the touchpad to "enabled" * @param supposed if set to true, this will set the supposed display state to enabled but may not * affect the touchpad until internal conditions are met * if set to false it will turn the touchpad on regardless of internal conditions */ void enable(boolean supposed); /** * Sets the state of the touchpad to "disabled". */ void disable(); }
1,546
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
TouchEventProcessor.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/customcontrols/mouse/TouchEventProcessor.java
package net.kdt.pojavlaunch.customcontrols.mouse; import android.view.MotionEvent; public interface TouchEventProcessor { boolean processTouchEvent(MotionEvent motionEvent); void cancelPendingActions(); }
215
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
Scroller.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/customcontrols/mouse/Scroller.java
package net.kdt.pojavlaunch.customcontrols.mouse; import org.lwjgl.glfw.CallbackBridge; public class Scroller { private float mScrollOvershootH, mScrollOvershootV; private final float mScrollThreshold; public Scroller(float mScrollThreshold) { this.mScrollThreshold = mScrollThreshold; } /** * Perform a scrolling gesture. * @param dx the X coordinate of the primary pointer's vector * @param dy the Y coordinate of the primary pointer's vector */ public void performScroll(float dx, float dy) { float hScroll = (dx / mScrollThreshold) + mScrollOvershootH; float vScroll = (dy / mScrollThreshold) + mScrollOvershootV; int hScrollRound = (int) hScroll, vScrollRound = (int) vScroll; if(hScrollRound != 0 || vScrollRound != 0) CallbackBridge.sendScroll(hScroll, vScroll); mScrollOvershootH = hScroll - hScrollRound; mScrollOvershootV = vScroll - vScrollRound; } /** * Perform a scrolling gesture. * @param vector a 2-component vector that stores the relative position of the primary pointer. */ public void performScroll(float[] vector) { performScroll(vector[0], vector[1]); } /** * Reset scroll overshoot values. Scroll overshoot makes the scrolling feel less * choppy, but will cause anomailes if not reset on the end of a scrolling gesture. */ public void resetScrollOvershoot() { mScrollOvershootH = mScrollOvershootV = 0f; } }
1,512
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
HotbarView.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/customcontrols/mouse/HotbarView.java
package net.kdt.pojavlaunch.customcontrols.mouse; import android.content.Context; import android.os.Handler; import android.os.Looper; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import androidx.annotation.Nullable; import net.kdt.pojavlaunch.LwjglGlfwKeycode; import net.kdt.pojavlaunch.TapDetector; import net.kdt.pojavlaunch.prefs.LauncherPreferences; import net.kdt.pojavlaunch.utils.MCOptionUtils; import net.kdt.pojavlaunch.utils.MathUtils; import org.lwjgl.glfw.CallbackBridge; public class HotbarView extends View implements MCOptionUtils.MCOptionListener, View.OnLayoutChangeListener, Runnable { private final TapDetector mDoubleTapDetector = new TapDetector(2, TapDetector.DETECTION_METHOD_DOWN); private View mParentView; private static final int[] HOTBAR_KEYS = { LwjglGlfwKeycode.GLFW_KEY_1, LwjglGlfwKeycode.GLFW_KEY_2, LwjglGlfwKeycode.GLFW_KEY_3, LwjglGlfwKeycode.GLFW_KEY_4, LwjglGlfwKeycode.GLFW_KEY_5, LwjglGlfwKeycode.GLFW_KEY_6, LwjglGlfwKeycode.GLFW_KEY_7, LwjglGlfwKeycode.GLFW_KEY_8, LwjglGlfwKeycode.GLFW_KEY_9}; private final DropGesture mDropGesture = new DropGesture(new Handler(Looper.getMainLooper())); private final float mScaleFactor = LauncherPreferences.PREF_SCALE_FACTOR/100f; private int mWidth; private int mLastIndex; private int mGuiScale; public HotbarView(Context context) { super(context); initialize(); } public HotbarView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); initialize(); } public HotbarView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initialize(); } @SuppressWarnings("unused") // You suggested me this constructor, Android public HotbarView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); initialize(); } private void initialize() { MCOptionUtils.addMCOptionListener(this); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); ViewParent parent = getParent(); if(parent == null) return; if(parent instanceof View) { mParentView = (View) parent; mParentView.addOnLayoutChangeListener(this); } mGuiScale = MCOptionUtils.getMcScale(); repositionView(); } private void repositionView() { ViewGroup.LayoutParams layoutParams = getLayoutParams(); if(!(layoutParams instanceof ViewGroup.MarginLayoutParams)) throw new RuntimeException("Incorrect LayoutParams type, expected ViewGroup.MarginLayoutParams"); ViewGroup.MarginLayoutParams marginLayoutParams = (ViewGroup.MarginLayoutParams) layoutParams; int height; marginLayoutParams.width = mWidth = mcScale(180); marginLayoutParams.height = height = mcScale(20); marginLayoutParams.leftMargin = (CallbackBridge.physicalWidth / 2) - (mWidth / 2); marginLayoutParams.topMargin = CallbackBridge.physicalHeight - height; setLayoutParams(marginLayoutParams); } @SuppressWarnings("ClickableViewAccessibility") // performClick does not report coordinates. @Override public boolean onTouchEvent(MotionEvent event) { if(!CallbackBridge.isGrabbing()) return false; boolean hasDoubleTapped = mDoubleTapDetector.onTouchEvent(event); // Check if we need to cancel the drop event int actionMasked = event.getActionMasked(); if(isLastEventInGesture(actionMasked)) mDropGesture.cancel(); else mDropGesture.submit(); // Determine the hotbar slot float x = event.getX(); if(x < 0 || x > mWidth) { // If out of bounds, cancel the hotbar gesture to avoid dropping items on last hotbar slots mDropGesture.cancel(); return true; } int hotbarIndex = (int)MathUtils.map(x, 0, mWidth, 0, HOTBAR_KEYS.length); // Check if the slot changed and we need to make a key press if(hotbarIndex == mLastIndex) { // Only check for doubletapping if the slot has not changed if(hasDoubleTapped && !LauncherPreferences.PREF_DISABLE_SWAP_HAND) CallbackBridge.sendKeyPress(LwjglGlfwKeycode.GLFW_KEY_F); return true; } mLastIndex = hotbarIndex; int hotbarKey = HOTBAR_KEYS[hotbarIndex]; CallbackBridge.sendKeyPress(hotbarKey); // Cancel the event since we changed hotbar slots. mDropGesture.cancel(); // Only resubmit the gesture only if it isn't the last event we will receive. if(!isLastEventInGesture(actionMasked)) mDropGesture.submit(); return true; } private boolean isLastEventInGesture(int actionMasked) { return actionMasked == MotionEvent.ACTION_UP || actionMasked == MotionEvent.ACTION_CANCEL; } private int mcScale(int input) { return (int)((mGuiScale * input)/ mScaleFactor); } @Override public void onOptionChanged() { post(this); } @Override public void run() { if(getParent() == null) return; int scale = MCOptionUtils.getMcScale(); if(scale == mGuiScale) return; mGuiScale = scale; repositionView(); } @Override public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) { // We need to check whether dimensions match or not because here we are looking specifically for changes of dimensions // and Android keeps calling this without dimensions actually changing for some reason. if(v.equals(mParentView) && (left != oldLeft || right != oldRight || top != oldTop || bottom != oldBottom)) { // Need to post this, because it is not correct to resize the view // during a layout pass. post(this::repositionView); } } }
6,211
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
AndroidPointerCapture.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/customcontrols/mouse/AndroidPointerCapture.java
package net.kdt.pojavlaunch.customcontrols.mouse; import android.os.Build; import android.view.MotionEvent; import android.view.View; import android.view.ViewTreeObserver; import androidx.annotation.RequiresApi; import net.kdt.pojavlaunch.MainActivity; import net.kdt.pojavlaunch.MinecraftGLSurface; import net.kdt.pojavlaunch.Tools; import org.lwjgl.glfw.CallbackBridge; @RequiresApi(api = Build.VERSION_CODES.O) public class AndroidPointerCapture implements ViewTreeObserver.OnWindowFocusChangeListener, View.OnCapturedPointerListener { private static final float TOUCHPAD_SCROLL_THRESHOLD = 1; private final AbstractTouchpad mTouchpad; private final View mHostView; private final float mScaleFactor; private final float mMousePrescale = Tools.dpToPx(1); private final Scroller mScroller = new Scroller(TOUCHPAD_SCROLL_THRESHOLD); public AndroidPointerCapture(AbstractTouchpad touchpad, View hostView, float scaleFactor) { this.mScaleFactor = scaleFactor; this.mTouchpad = touchpad; this.mHostView = hostView; hostView.setOnCapturedPointerListener(this); hostView.getViewTreeObserver().addOnWindowFocusChangeListener(this); } private void enableTouchpadIfNecessary() { if(!mTouchpad.getDisplayState()) mTouchpad.enable(true); } public void handleAutomaticCapture() { if(!CallbackBridge.isGrabbing()) return; if(mHostView.hasPointerCapture()) { enableTouchpadIfNecessary(); return; } if(!mHostView.hasWindowFocus()) { mHostView.requestFocus(); } else { mHostView.requestPointerCapture(); } } @Override public boolean onCapturedPointer(View view, MotionEvent event) { // Yes, we actually not only receive relative mouse events here, but also absolute touchpad ones! // Read from relative axis directly to work around. float relX = event.getAxisValue(MotionEvent.AXIS_RELATIVE_X); float relY = event.getAxisValue(MotionEvent.AXIS_RELATIVE_Y); if(!CallbackBridge.isGrabbing()) { enableTouchpadIfNecessary(); // Yes, if the user's touchpad is multi-touch we will also receive events for that. // So, handle the scrolling gesture ourselves. relX *= mMousePrescale; relY *= mMousePrescale; if(event.getPointerCount() < 2) { mTouchpad.applyMotionVector(relX, relY); mScroller.resetScrollOvershoot(); } else { mScroller.performScroll(relX, relY); } } else { // Position is updated by many events, hence it is send regardless of the event value CallbackBridge.mouseX += (relX * mScaleFactor); CallbackBridge.mouseY += (relY * mScaleFactor); CallbackBridge.sendCursorPos(CallbackBridge.mouseX, CallbackBridge.mouseY); } switch (event.getActionMasked()) { case MotionEvent.ACTION_MOVE: return true; case MotionEvent.ACTION_BUTTON_PRESS: return MinecraftGLSurface.sendMouseButtonUnconverted(event.getActionButton(), true); case MotionEvent.ACTION_BUTTON_RELEASE: return MinecraftGLSurface.sendMouseButtonUnconverted(event.getActionButton(), false); case MotionEvent.ACTION_SCROLL: CallbackBridge.sendScroll( event.getAxisValue(MotionEvent.AXIS_HSCROLL), event.getAxisValue(MotionEvent.AXIS_VSCROLL) ); return true; default: return false; } } @Override public void onWindowFocusChanged(boolean hasFocus) { if(hasFocus && MainActivity.isAndroid8OrHigher()) mHostView.requestPointerCapture(); } public void detach() { mHostView.setOnCapturedPointerListener(null); mHostView.getViewTreeObserver().removeOnWindowFocusChangeListener(this); } }
4,071
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
InGameEventProcessor.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/customcontrols/mouse/InGameEventProcessor.java
package net.kdt.pojavlaunch.customcontrols.mouse; import android.os.Handler; import android.os.Looper; import android.view.MotionEvent; import net.kdt.pojavlaunch.prefs.LauncherPreferences; import org.lwjgl.glfw.CallbackBridge; public class InGameEventProcessor implements TouchEventProcessor { private final Handler mGestureHandler = new Handler(Looper.getMainLooper()); private final double mSensitivity; private boolean mEventTransitioned = true; private final PointerTracker mTracker = new PointerTracker(); private final LeftClickGesture mLeftClickGesture = new LeftClickGesture(mGestureHandler); private final RightClickGesture mRightClickGesture = new RightClickGesture(mGestureHandler); public InGameEventProcessor(double sensitivity) { mSensitivity = sensitivity; } @Override public boolean processTouchEvent(MotionEvent motionEvent) { switch (motionEvent.getActionMasked()) { case MotionEvent.ACTION_DOWN: mTracker.startTracking(motionEvent); if(LauncherPreferences.PREF_DISABLE_GESTURES) break; mEventTransitioned = false; checkGestures(); break; case MotionEvent.ACTION_MOVE: mTracker.trackEvent(motionEvent); float[] motionVector = mTracker.getMotionVector(); CallbackBridge.mouseX += motionVector[0] * mSensitivity; CallbackBridge.mouseY += motionVector[1] * mSensitivity; CallbackBridge.sendCursorPos(CallbackBridge.mouseX, CallbackBridge.mouseY); if(LauncherPreferences.PREF_DISABLE_GESTURES) break; checkGestures(); break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: mTracker.cancelTracking(); cancelGestures(false); } return true; } @Override public void cancelPendingActions() { cancelGestures(true); } private void checkGestures() { mLeftClickGesture.inputEvent(); // Only register right click events if it's a fresh event stream, not one after a transition. // This is done to avoid problems when people hold the button for just a bit too long after // exiting a menu for example. if(!mEventTransitioned) mRightClickGesture.inputEvent(); } private void cancelGestures(boolean isSwitching) { mEventTransitioned = true; mLeftClickGesture.cancel(isSwitching); mRightClickGesture.cancel(isSwitching); } }
2,611
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
ValidatorGesture.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/customcontrols/mouse/ValidatorGesture.java
package net.kdt.pojavlaunch.customcontrols.mouse; import android.os.Handler; /** * This class implements an abstract "validator gesture", meant as a base for implementation of * more complex gestures with finger position tracking and such. */ public abstract class ValidatorGesture implements Runnable{ private final Handler mHandler; private boolean mGestureActive; private final int mRequiredDuration; /** * @param mHandler the Handler that will be used for calling back the checkAndTrigger() method. * This Handler should run on the same thread as the callee of submit()/cancel() * @param mRequiredDuration the duration after which the class will call checkAndTrigger(). */ public ValidatorGesture(Handler mHandler, int mRequiredDuration) { this.mHandler = mHandler; this.mRequiredDuration = mRequiredDuration; } /** * Submit the gesture, starting the timer and marking this gesture as "active". * If the gesture was already active, this call will be ignored * @return true if the gesture was submitted, false if the call was ignored */ public final boolean submit() { if(mGestureActive) return false; mHandler.postDelayed(this, mRequiredDuration); mGestureActive = true; return true; } /** * Cancel the gesture, stopping the timer and marking this gesture as "inactive". * If the gesture was already inactive, this call will be ignored. * @param isSwitching true if this gesture was cancelled due to user interaction (the user let go of the finger) * false if this gesture is cancelled due a request from the programmer or the OS. * Note that returning false from checkAndTrigger() counts as user interaction. */ public final void cancel(boolean isSwitching) { if(!mGestureActive) return; mHandler.removeCallbacks(this); onGestureCancelled(isSwitching); mGestureActive = false; } @Override public final void run() { if(checkAndTrigger()) return; mGestureActive = false; onGestureCancelled(false); } /** * This method will be called after mRequiredDuration milliseconds, if the gesture was not cancelled. * @return false if you want to mark this gesture as "inactive" * true otherwise */ public abstract boolean checkAndTrigger(); /** * This method will be called if the gesture was cancelled using the cancel() method or by returning false * from checkAndTrigger(). * @param isSwitching true if this gesture was cancelled due to user interaction (the user let go of the finger) * false if this gesture is cancelled due a request from the programmer or the OS. */ public abstract void onGestureCancelled(boolean isSwitching); }
2,918
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
Touchpad.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/customcontrols/mouse/Touchpad.java
package net.kdt.pojavlaunch.customcontrols.mouse; import static net.kdt.pojavlaunch.Tools.currentDisplayMetrics; import static net.kdt.pojavlaunch.prefs.LauncherPreferences.DEFAULT_PREF; import android.content.Context; import android.graphics.Canvas; import android.graphics.drawable.Drawable; import android.os.Build; import android.util.AttributeSet; import android.view.View; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.content.res.ResourcesCompat; import net.kdt.pojavlaunch.GrabListener; import net.kdt.pojavlaunch.R; import net.kdt.pojavlaunch.prefs.LauncherPreferences; import org.lwjgl.glfw.CallbackBridge; /** * Class dealing with the virtual mouse */ public class Touchpad extends View implements GrabListener, AbstractTouchpad { /* Whether the Touchpad should be displayed */ private boolean mDisplayState; /* Mouse pointer icon used by the touchpad */ private Drawable mMousePointerDrawable; private float mMouseX, mMouseY; /* Resolution scaler option, allow downsizing a window */ private final float mScaleFactor = DEFAULT_PREF.getInt("resolutionRatio",100)/100f; public Touchpad(@NonNull Context context) { this(context, null); } public Touchpad(@NonNull Context context, @Nullable AttributeSet attrs) { super(context, attrs); init(); } /** Enable the touchpad */ private void _enable(){ setVisibility(VISIBLE); placeMouseAt(currentDisplayMetrics.widthPixels / 2f, currentDisplayMetrics.heightPixels / 2f); } /** Disable the touchpad and hides the mouse */ private void _disable(){ setVisibility(GONE); } /** @return The new state, enabled or disabled */ public boolean switchState(){ mDisplayState = !mDisplayState; if(!CallbackBridge.isGrabbing()) { if(mDisplayState) _enable(); else _disable(); } return mDisplayState; } public void placeMouseAt(float x, float y) { mMouseX = x; mMouseY = y; updateMousePosition(); } private void sendMousePosition() { CallbackBridge.sendCursorPos((mMouseX * mScaleFactor), (mMouseY * mScaleFactor)); } private void updateMousePosition() { sendMousePosition(); // I wanted to implement a dirty rect for this, but it is ignored since API level 21 // (which is our min API) // Let's hope the "internally calculated area" is good enough. invalidate(); } @Override protected void onDraw(Canvas canvas) { canvas.translate(mMouseX, mMouseY); mMousePointerDrawable.draw(canvas); } private void init(){ // Setup mouse pointer mMousePointerDrawable = ResourcesCompat.getDrawable(getResources(), R.drawable.ic_mouse_pointer, getContext().getTheme()); // For some reason it's annotated as Nullable even though it doesn't seem to actually // ever return null assert mMousePointerDrawable != null; mMousePointerDrawable.setBounds( 0, 0, (int) (36 / 100f * LauncherPreferences.PREF_MOUSESCALE), (int) (54 / 100f * LauncherPreferences.PREF_MOUSESCALE) ); setFocusable(false); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { setDefaultFocusHighlightEnabled(false); } // When the game is grabbing, we should not display the mouse disable(); mDisplayState = false; } @Override public void onGrabState(boolean isGrabbing) { post(()->updateGrabState(isGrabbing)); } private void updateGrabState(boolean isGrabbing) { if(!isGrabbing) { if(mDisplayState && getVisibility() != VISIBLE) _enable(); if(!mDisplayState && getVisibility() == VISIBLE) _disable(); }else{ if(getVisibility() != View.GONE) _disable(); } } @Override public boolean getDisplayState() { return mDisplayState; } @Override public void applyMotionVector(float x, float y) { mMouseX = Math.max(0, Math.min(currentDisplayMetrics.widthPixels, mMouseX + x * LauncherPreferences.PREF_MOUSESPEED)); mMouseY = Math.max(0, Math.min(currentDisplayMetrics.heightPixels, mMouseY + y * LauncherPreferences.PREF_MOUSESPEED)); updateMousePosition(); } @Override public void enable(boolean supposed) { if(mDisplayState) return; mDisplayState = true; if(supposed && CallbackBridge.isGrabbing()) return; _enable(); } @Override public void disable() { if(!mDisplayState) return; mDisplayState = false; _disable(); } }
4,780
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
PointerTracker.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/customcontrols/mouse/PointerTracker.java
package net.kdt.pojavlaunch.customcontrols.mouse; import android.view.MotionEvent; public class PointerTracker { private boolean mColdStart = true; private int mTrackedPointerId; private int mPointerCount; private float mLastX, mLastY; private final float[] mMotionVector = new float[2]; public void startTracking(MotionEvent motionEvent) { mColdStart = false; mTrackedPointerId = motionEvent.getPointerId(0); mPointerCount = motionEvent.getPointerCount(); mLastX = motionEvent.getX(); mLastY = motionEvent.getY(); } public void cancelTracking() { mColdStart = true; } public int trackEvent(MotionEvent motionEvent) { int trackedPointerIndex = motionEvent.findPointerIndex(mTrackedPointerId); int pointerCount = motionEvent.getPointerCount(); if(trackedPointerIndex == -1 || mPointerCount != pointerCount || mColdStart) { startTracking(motionEvent); trackedPointerIndex = 0; } float trackedX = motionEvent.getX(trackedPointerIndex); float trackedY = motionEvent.getY(trackedPointerIndex); mMotionVector[0] = trackedX - mLastX; mMotionVector[1] = trackedY - mLastY; mLastX = trackedX; mLastY = trackedY; return trackedPointerIndex; } public float[] getMotionVector() { return mMotionVector; } }
1,420
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
LeftClickGesture.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/customcontrols/mouse/LeftClickGesture.java
package net.kdt.pojavlaunch.customcontrols.mouse; import static org.lwjgl.glfw.CallbackBridge.sendMouseButton; import android.os.Handler; import net.kdt.pojavlaunch.LwjglGlfwKeycode; import net.kdt.pojavlaunch.Tools; import net.kdt.pojavlaunch.prefs.LauncherPreferences; import net.kdt.pojavlaunch.utils.MathUtils; import org.lwjgl.glfw.CallbackBridge; public class LeftClickGesture extends ValidatorGesture { public static final int FINGER_STILL_THRESHOLD = (int) Tools.dpToPx(9); private float mGestureStartX, mGestureStartY; private boolean mMouseActivated; public LeftClickGesture(Handler handler) { super(handler, LauncherPreferences.PREF_LONGPRESS_TRIGGER); } public final void inputEvent() { if(submit()) { mGestureStartX = CallbackBridge.mouseX; mGestureStartY = CallbackBridge.mouseY; } } @Override public boolean checkAndTrigger() { boolean fingerStill = LeftClickGesture.isFingerStill(mGestureStartX, mGestureStartY); // If the finger is still, fire the gesture. if(fingerStill) { sendMouseButton(LwjglGlfwKeycode.GLFW_MOUSE_BUTTON_LEFT, true); mMouseActivated = true; } // Otherwise, don't click but still keep it active return true; } @Override public void onGestureCancelled(boolean isSwitching) { if(mMouseActivated) { sendMouseButton(LwjglGlfwKeycode.GLFW_MOUSE_BUTTON_LEFT, false); mMouseActivated = false; } } /** * Check if the finger is still when compared to mouseX/mouseY in CallbackBridge. * @param startX the starting X of the gesture * @param startY the starting Y of the gesture * @return whether the finger's position counts as "still" or not */ public static boolean isFingerStill(float startX, float startY) { return MathUtils.dist( CallbackBridge.mouseX, CallbackBridge.mouseY, startX, startY ) <= FINGER_STILL_THRESHOLD; } }
2,095
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
ControlSubButton.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/customcontrols/buttons/ControlSubButton.java
package net.kdt.pojavlaunch.customcontrols.buttons; import android.annotation.SuppressLint; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import net.kdt.pojavlaunch.customcontrols.ControlData; import net.kdt.pojavlaunch.customcontrols.ControlDrawerData; import net.kdt.pojavlaunch.customcontrols.ControlLayout; import net.kdt.pojavlaunch.customcontrols.handleview.EditControlPopup; @SuppressLint("ViewConstructor") public class ControlSubButton extends ControlButton { public final ControlDrawer parentDrawer; public ControlSubButton(ControlLayout layout, ControlData properties, ControlDrawer parentDrawer) { super(layout, properties); this.parentDrawer = parentDrawer; filterProperties(); } private void filterProperties(){ if (parentDrawer != null && parentDrawer.drawerData.orientation != ControlDrawerData.Orientation.FREE) { mProperties.setHeight(parentDrawer.getProperties().getHeight()); mProperties.setWidth(parentDrawer.getProperties().getWidth()); } mProperties.isDynamicBtn = false; setProperties(mProperties, false); } @Override public void setVisible(boolean isVisible) { // STUB, visibility handled by the ControlDrawer //setVisibility(isVisible ? VISIBLE : (!mProperties.isHideable && parentDrawer.getVisibility() == GONE) ? VISIBLE : View.GONE); } @Override public void onGrabState(boolean isGrabbing) { // STUB, visibility lifecycle handled by the ControlDrawer } @Override public void setLayoutParams(ViewGroup.LayoutParams params) { if(parentDrawer != null && parentDrawer.drawerData.orientation != ControlDrawerData.Orientation.FREE){ params.width = (int)parentDrawer.mProperties.getWidth(); params.height = (int)parentDrawer.mProperties.getHeight(); } super.setLayoutParams(params); } @SuppressLint("ClickableViewAccessibility") @Override public boolean onTouchEvent(MotionEvent event) { if(!getControlLayoutParent().getModifiable() || parentDrawer.drawerData.orientation == ControlDrawerData.Orientation.FREE){ return super.onTouchEvent(event); } if (event.getActionMasked() == MotionEvent.ACTION_UP) { //mCanTriggerLongClick = true; onLongClick(this); } return true; } @Override public void cloneButton() { ControlData cloneData = new ControlData(getProperties()); cloneData.dynamicX = "0.5 * ${screen_width}"; cloneData.dynamicY = "0.5 * ${screen_height}"; ((ControlLayout) getParent()).addSubButton(parentDrawer, cloneData); } @Override public void removeButton() { parentDrawer.drawerData.buttonProperties.remove(getProperties()); parentDrawer.drawerData.buttonProperties.remove(getProperties()); parentDrawer.buttons.remove(this); parentDrawer.syncButtons(); super.removeButton(); } @Override public void snapAndAlign(float x, float y) { if(parentDrawer.drawerData.orientation == ControlDrawerData.Orientation.FREE) super.snapAndAlign(x, y); // Else the button is forced into place } @Override public void loadEditValues(EditControlPopup editControlPopup) { editControlPopup.loadSubButtonValues(getProperties(), parentDrawer.drawerData.orientation); } }
3,500
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
ControlJoystick.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/customcontrols/buttons/ControlJoystick.java
package net.kdt.pojavlaunch.customcontrols.buttons; import static net.kdt.pojavlaunch.customcontrols.gamepad.GamepadJoystick.DIRECTION_EAST; import static net.kdt.pojavlaunch.customcontrols.gamepad.GamepadJoystick.DIRECTION_NONE; import static net.kdt.pojavlaunch.customcontrols.gamepad.GamepadJoystick.DIRECTION_NORTH; import static net.kdt.pojavlaunch.customcontrols.gamepad.GamepadJoystick.DIRECTION_NORTH_EAST; import static net.kdt.pojavlaunch.customcontrols.gamepad.GamepadJoystick.DIRECTION_NORTH_WEST; import static net.kdt.pojavlaunch.customcontrols.gamepad.GamepadJoystick.DIRECTION_SOUTH; import static net.kdt.pojavlaunch.customcontrols.gamepad.GamepadJoystick.DIRECTION_SOUTH_EAST; import static net.kdt.pojavlaunch.customcontrols.gamepad.GamepadJoystick.DIRECTION_SOUTH_WEST; import static net.kdt.pojavlaunch.customcontrols.gamepad.GamepadJoystick.DIRECTION_WEST; import android.annotation.SuppressLint; import android.view.View; import net.kdt.pojavlaunch.LwjglGlfwKeycode; import net.kdt.pojavlaunch.Tools; import net.kdt.pojavlaunch.customcontrols.ControlData; import net.kdt.pojavlaunch.customcontrols.ControlJoystickData; import net.kdt.pojavlaunch.customcontrols.ControlLayout; import net.kdt.pojavlaunch.customcontrols.gamepad.GamepadJoystick; import net.kdt.pojavlaunch.customcontrols.handleview.EditControlPopup; import org.lwjgl.glfw.CallbackBridge; import io.github.controlwear.virtual.joystick.android.JoystickView; @SuppressLint("ViewConstructor") public class ControlJoystick extends JoystickView implements ControlInterface { public final static int DIRECTION_FORWARD_LOCK = 8; // Directions keycode private final int[] mDirectionForwardLock = new int[]{LwjglGlfwKeycode.GLFW_KEY_LEFT_CONTROL}; private final int[] mDirectionForward = new int[]{LwjglGlfwKeycode.GLFW_KEY_W}; private final int[] mDirectionRight = new int[]{LwjglGlfwKeycode.GLFW_KEY_D}; private final int[] mDirectionBackward = new int[]{LwjglGlfwKeycode.GLFW_KEY_S}; private final int[] mDirectionLeft = new int[]{LwjglGlfwKeycode.GLFW_KEY_A}; private ControlJoystickData mControlData; private int mLastDirectionInt = GamepadJoystick.DIRECTION_NONE; private int mCurrentDirectionInt = GamepadJoystick.DIRECTION_NONE; public ControlJoystick(ControlLayout parent, ControlJoystickData data) { super(parent.getContext()); init(data, parent); } private static void sendInput(int[] keys, boolean isDown) { for (int key : keys) { CallbackBridge.sendKeyPress(key, CallbackBridge.getCurrentMods(), isDown); } } private void init(ControlJoystickData data, ControlLayout layout) { mControlData = data; setProperties(preProcessProperties(data, layout)); setDeadzone(35); setFixedCenter(data.absolute); setAutoReCenterButton(true); injectBehaviors(); setOnMoveListener(new OnMoveListener() { @Override public void onMove(int angle, int strength) { mLastDirectionInt = mCurrentDirectionInt; mCurrentDirectionInt = getDirectionInt(angle, strength); if (mLastDirectionInt != mCurrentDirectionInt) { sendDirectionalKeycode(mLastDirectionInt, false); sendDirectionalKeycode(mCurrentDirectionInt, true); } } @Override public void onForwardLock(boolean isLocked) { sendInput(mDirectionForwardLock, isLocked); } }); } @Override public View getControlView() { return this; } @Override public ControlData getProperties() { return mControlData; } @Override public void setProperties(ControlData properties, boolean changePos) { mControlData = (ControlJoystickData) properties; mControlData.isHideable = true; ControlInterface.super.setProperties(properties, changePos); postDelayed(() -> { setForwardLockDistance(mControlData.forwardLock ? (int) Tools.dpToPx(60) : 0); setFixedCenter(mControlData.absolute); }, 10); } @Override public void removeButton() { getControlLayoutParent().getLayout().mJoystickDataList.remove(getProperties()); getControlLayoutParent().removeView(this); } @Override public void cloneButton() { ControlJoystickData data = new ControlJoystickData(mControlData); getControlLayoutParent().addJoystickButton(data); } @Override public void setBackground() { setBorderWidth((int) Tools.dpToPx(getProperties().strokeWidth * (getControlLayoutParent().getLayoutScale()/100f))); setBorderColor(getProperties().strokeColor); setBackgroundColor(getProperties().bgColor); } @Override public void sendKeyPresses(boolean isDown) {/*STUB since non swipeable*/ } @Override public void loadEditValues(EditControlPopup editControlPopup) { editControlPopup.loadJoystickValues(mControlData); } private int getDirectionInt(int angle, int intensity) { if (intensity == 0) return DIRECTION_NONE; return (int) (((angle + 22.5) / 45) % 8); } private void sendDirectionalKeycode(int direction, boolean isDown) { switch (direction) { case DIRECTION_NORTH: sendInput(mDirectionForward, isDown); break; case DIRECTION_NORTH_EAST: sendInput(mDirectionForward, isDown); sendInput(mDirectionRight, isDown); break; case DIRECTION_EAST: sendInput(mDirectionRight, isDown); break; case DIRECTION_SOUTH_EAST: sendInput(mDirectionRight, isDown); sendInput(mDirectionBackward, isDown); break; case DIRECTION_SOUTH: sendInput(mDirectionBackward, isDown); break; case DIRECTION_SOUTH_WEST: sendInput(mDirectionBackward, isDown); sendInput(mDirectionLeft, isDown); break; case DIRECTION_WEST: sendInput(mDirectionLeft, isDown); break; case DIRECTION_NORTH_WEST: sendInput(mDirectionForward, isDown); sendInput(mDirectionLeft, isDown); break; case DIRECTION_FORWARD_LOCK: sendInput(mDirectionForwardLock, isDown); break; } } }
6,614
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
ControlInterface.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/customcontrols/buttons/ControlInterface.java
package net.kdt.pojavlaunch.customcontrols.buttons; import static android.view.View.GONE; import static android.view.View.VISIBLE; import static net.kdt.pojavlaunch.prefs.LauncherPreferences.PREF_BUTTONSIZE; import android.annotation.SuppressLint; import android.graphics.drawable.GradientDrawable; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import androidx.annotation.CallSuper; import androidx.annotation.NonNull; import androidx.core.math.MathUtils; import net.kdt.pojavlaunch.GrabListener; import net.kdt.pojavlaunch.Tools; import net.kdt.pojavlaunch.customcontrols.ControlData; import net.kdt.pojavlaunch.customcontrols.ControlLayout; import net.kdt.pojavlaunch.customcontrols.handleview.EditControlPopup; import org.lwjgl.glfw.CallbackBridge; /** * Interface injecting custom behavior to a View. * Most of the injected behavior is editing behavior, * sending keys has to be implemented by sub classes. */ public interface ControlInterface extends View.OnLongClickListener, GrabListener { View getControlView(); ControlData getProperties(); default void setProperties(ControlData properties) { setProperties(properties, true); } /** * Remove the button presence from the CustomControl object * You need to use {getControlParent()} for this. */ void removeButton(); /** * Duplicate the data of the button and add a view with the duplicated data * Relies on the ControlLayout for the implementation. */ void cloneButton(); default void setVisible(boolean isVisible) { if(getProperties().isHideable) getControlView().setVisibility(isVisible ? VISIBLE : GONE); } void sendKeyPresses(boolean isDown); /** * Load the values and hide non useful forms */ void loadEditValues(EditControlPopup editControlPopup); @Override default void onGrabState(boolean isGrabbing) { if (getControlLayoutParent() != null && getControlLayoutParent().getModifiable()) return; // Disable when edited setVisible(((getProperties().displayInGame && isGrabbing) || (getProperties().displayInMenu && !isGrabbing)) && getControlLayoutParent().areControlVisible()); } default ControlLayout getControlLayoutParent() { return (ControlLayout) getControlView().getParent(); } /** * Apply conversion steps for when the view is created */ default ControlData preProcessProperties(ControlData properties, ControlLayout layout) { //Size properties.setWidth(properties.getWidth() / layout.getLayoutScale() * PREF_BUTTONSIZE); properties.setHeight(properties.getHeight() / layout.getLayoutScale() * PREF_BUTTONSIZE); //Visibility properties.isHideable = !properties.containsKeycode(ControlData.SPECIALBTN_TOGGLECTRL) && !properties.containsKeycode(ControlData.SPECIALBTN_VIRTUALMOUSE); return properties; } default void updateProperties() { setProperties(getProperties()); } /* This function should be overridden to store the properties */ @CallSuper default void setProperties(ControlData properties, boolean changePos) { if (changePos) { getControlView().setX(properties.insertDynamicPos(getProperties().dynamicX)); getControlView().setY(properties.insertDynamicPos(getProperties().dynamicY)); } // Recycle layout params ViewGroup.LayoutParams params = getControlView().getLayoutParams(); if (params == null) params = new FrameLayout.LayoutParams((int) properties.getWidth(), (int) properties.getHeight()); params.width = (int) properties.getWidth(); params.height = (int) properties.getHeight(); getControlView().setLayoutParams(params); } /** * Apply the background according to properties */ default void setBackground() { GradientDrawable gd = getControlView().getBackground() instanceof GradientDrawable ? (GradientDrawable) getControlView().getBackground() : new GradientDrawable(); gd.setColor(getProperties().bgColor); gd.setStroke((int) Tools.dpToPx(getProperties().strokeWidth * (getControlLayoutParent().getLayoutScale()/100f)), getProperties().strokeColor); gd.setCornerRadius(computeCornerRadius(getProperties().cornerRadius)); getControlView().setBackground(gd); } /** * Apply the dynamic equation on the x axis. * * @param dynamicX The equation to compute the position from */ default void setDynamicX(String dynamicX) { getProperties().dynamicX = dynamicX; getControlView().setX(getProperties().insertDynamicPos(dynamicX)); } /** * Apply the dynamic equation on the y axis. * * @param dynamicY The equation to compute the position from */ default void setDynamicY(String dynamicY) { getProperties().dynamicY = dynamicY; getControlView().setY(getProperties().insertDynamicPos(dynamicY)); } /** * Generate a dynamic equation from an absolute position, used to scale properly across devices * * @param x The absolute position on the horizontal axis * @return The equation as a String */ default String generateDynamicX(float x) { if (x + (getProperties().getWidth() / 2f) > CallbackBridge.physicalWidth / 2f) { return (x + getProperties().getWidth()) / CallbackBridge.physicalWidth + " * ${screen_width} - ${width}"; } else { return x / CallbackBridge.physicalWidth + " * ${screen_width}"; } } /** * Generate a dynamic equation from an absolute position, used to scale properly across devices * * @param y The absolute position on the vertical axis * @return The equation as a String */ default String generateDynamicY(float y) { if (y + (getProperties().getHeight() / 2f) > CallbackBridge.physicalHeight / 2f) { return (y + getProperties().getHeight()) / CallbackBridge.physicalHeight + " * ${screen_height} - ${height}"; } else { return y / CallbackBridge.physicalHeight + " * ${screen_height}"; } } /** * Regenerate and apply coordinates with supposedly modified properties */ default void regenerateDynamicCoordinates() { getProperties().dynamicX = generateDynamicX(getControlView().getX()); getProperties().dynamicY = generateDynamicY(getControlView().getY()); updateProperties(); } /** * Do a pre-conversion of an equation using values from a button, * so the variables can be used for another button * <p> * Internal use only. * * @param equation The dynamic position as a String * @param button The button to get the values from. * @return The pre-processed equation as a String. */ default String applySize(String equation, ControlInterface button) { return equation .replace("${right}", "(${screen_width} - ${width})") .replace("${bottom}", "(${screen_height} - ${height})") .replace("${height}", "(px(" + Tools.pxToDp(button.getProperties().getHeight()) + ") /" + PREF_BUTTONSIZE + " * ${preferred_scale})") .replace("${width}", "(px(" + Tools.pxToDp(button.getProperties().getWidth()) + ") / " + PREF_BUTTONSIZE + " * ${preferred_scale})"); } /** * Convert a corner radius percentage into a px corner radius */ default float computeCornerRadius(float radiusInPercent) { float minSize = Math.min(getProperties().getWidth(), getProperties().getHeight()); return (minSize / 2) * (radiusInPercent / 100); } /** * Passe a series of checks to determine if the ControlButton isn't available to be snapped on. * * @param button The button to check * @return whether or not the button */ @SuppressWarnings("BooleanMethodIsAlwaysInverted") default boolean canSnap(ControlInterface button) { float MIN_DISTANCE = Tools.dpToPx(8); if (button == this) return false; return !(net.kdt.pojavlaunch.utils.MathUtils.dist( button.getControlView().getX() + button.getControlView().getWidth() / 2f, button.getControlView().getY() + button.getControlView().getHeight() / 2f, getControlView().getX() + getControlView().getWidth() / 2f, getControlView().getY() + getControlView().getHeight() / 2f) > Math.max(button.getControlView().getWidth() / 2f + getControlView().getWidth() / 2f, button.getControlView().getHeight() / 2f + getControlView().getHeight() / 2f) + MIN_DISTANCE); } /** * Try to snap, then align to neighboring buttons, given the provided coordinates. * The new position is automatically applied to the View, * regardless of if the View snapped or not. * <p> * The new position is always dynamic, thus replacing previous dynamic positions * * @param x Coordinate on the x axis * @param y Coordinate on the y axis */ default void snapAndAlign(float x, float y) { float MIN_DISTANCE = Tools.dpToPx(8); String dynamicX = generateDynamicX(x); String dynamicY = generateDynamicY(y); getControlView().setX(x); getControlView().setY(y); for (ControlInterface button : ((ControlLayout) getControlView().getParent()).getButtonChildren()) { //Step 1: Filter unwanted buttons if (!canSnap(button)) continue; //Step 2: Get Coordinates float button_top = button.getControlView().getY(); float button_bottom = button_top + button.getControlView().getHeight(); float button_left = button.getControlView().getX(); float button_right = button_left + button.getControlView().getWidth(); float top = getControlView().getY(); float bottom = getControlView().getY() + getControlView().getHeight(); float left = getControlView().getX(); float right = getControlView().getX() + getControlView().getWidth(); //Step 3: For each axis, we try to snap to the nearest if (Math.abs(top - button_bottom) < MIN_DISTANCE) { // Bottom snap dynamicY = applySize(button.getProperties().dynamicY, button) + applySize(" + ${height}", button) + " + ${margin}"; } else if (Math.abs(button_top - bottom) < MIN_DISTANCE) { //Top snap dynamicY = applySize(button.getProperties().dynamicY, button) + " - ${height} - ${margin}"; } if (!dynamicY.equals(generateDynamicY(getControlView().getY()))) { //If we snapped if (Math.abs(button_left - left) < MIN_DISTANCE) { //Left align snap dynamicX = applySize(button.getProperties().dynamicX, button); } else if (Math.abs(button_right - right) < MIN_DISTANCE) { //Right align snap dynamicX = applySize(button.getProperties().dynamicX, button) + applySize(" + ${width}", button) + " - ${width}"; } } if (Math.abs(button_left - right) < MIN_DISTANCE) { //Left snap dynamicX = applySize(button.getProperties().dynamicX, button) + " - ${width} - ${margin}"; } else if (Math.abs(left - button_right) < MIN_DISTANCE) { //Right snap dynamicX = applySize(button.getProperties().dynamicX, button) + applySize(" + ${width}", button) + " + ${margin}"; } if (!dynamicX.equals(generateDynamicX(getControlView().getX()))) { //If we snapped if (Math.abs(button_top - top) < MIN_DISTANCE) { //Top align snap dynamicY = applySize(button.getProperties().dynamicY, button); } else if (Math.abs(button_bottom - bottom) < MIN_DISTANCE) { //Bottom align snap dynamicY = applySize(button.getProperties().dynamicY, button) + applySize(" + ${height}", button) + " - ${height}"; } } } setDynamicX(dynamicX); setDynamicY(dynamicY); } /** * Wrapper for multiple injections at once */ default void injectBehaviors() { injectProperties(); injectTouchEventBehavior(); injectLayoutParamBehavior(); injectGrabListenerBehavior(); } /** * Inject the grab listener, remove it when the view is gone */ default void injectGrabListenerBehavior() { if (getControlView() == null) { Log.e(ControlInterface.class.toString(), "Failed to inject grab listener behavior !"); return; } getControlView().addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() { @Override public void onViewAttachedToWindow(@NonNull View v) { CallbackBridge.addGrabListener(ControlInterface.this); } @Override public void onViewDetachedFromWindow(@NonNull View v) { getControlView().removeOnAttachStateChangeListener(this); CallbackBridge.removeGrabListener(ControlInterface.this); } }); } default void injectProperties() { getControlView().post(() -> getControlView().setTranslationZ(10)); } /** * Inject a touch listener on the view to make editing controls straight forward */ default void injectTouchEventBehavior() { getControlView().setOnTouchListener(new View.OnTouchListener() { private boolean mCanTriggerLongClick = true; private float downX, downY; private float downRawX, downRawY; @SuppressLint("ClickableViewAccessibility") @Override public boolean onTouch(View view, MotionEvent event) { if (!getControlLayoutParent().getModifiable()) { // Basically, editing behavior is forced while in game behavior is specific view.onTouchEvent(event); return true; } /* If the button can be modified/moved */ //Instantiate the gesture detector only when needed if (event.getActionMasked() == MotionEvent.ACTION_UP && mCanTriggerLongClick) { //TODO change this. onLongClick(view); } switch (event.getActionMasked()) { case MotionEvent.ACTION_DOWN: mCanTriggerLongClick = true; downRawX = event.getRawX(); downRawY = event.getRawY(); downX = downRawX - view.getX(); downY = downRawY - view.getY(); break; case MotionEvent.ACTION_MOVE: if (Math.abs(event.getRawX() - downRawX) > 8 || Math.abs(event.getRawY() - downRawY) > 8) mCanTriggerLongClick = false; getControlLayoutParent().adaptPanelPosition(); if (!getProperties().isDynamicBtn) { snapAndAlign( MathUtils.clamp(event.getRawX() - downX, 0, CallbackBridge.physicalWidth - view.getWidth()), MathUtils.clamp(event.getRawY() - downY, 0, CallbackBridge.physicalHeight - view.getHeight()) ); } break; } return true; } }); } default void injectLayoutParamBehavior() { getControlView().addOnLayoutChangeListener((v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom) -> { getProperties().setWidth(right - left); getProperties().setHeight(bottom - top); setBackground(); // Re-calculate position if (!getProperties().isDynamicBtn) { getControlView().setX(getControlView().getX()); getControlView().setY(getControlView().getY()); } else { getControlView().setX(getProperties().insertDynamicPos(getProperties().dynamicX)); getControlView().setY(getProperties().insertDynamicPos(getProperties().dynamicY)); } }); } @Override default boolean onLongClick(View v) { if (getControlLayoutParent().getModifiable()) { getControlLayoutParent().editControlButton(this); getControlLayoutParent().mActionRow.setFollowedButton(this); } return true; } }
16,961
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
ControlDrawer.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/customcontrols/buttons/ControlDrawer.java
package net.kdt.pojavlaunch.customcontrols.buttons; import android.annotation.SuppressLint; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import net.kdt.pojavlaunch.Tools; import net.kdt.pojavlaunch.customcontrols.ControlData; import net.kdt.pojavlaunch.customcontrols.ControlDrawerData; import net.kdt.pojavlaunch.customcontrols.ControlLayout; import net.kdt.pojavlaunch.customcontrols.handleview.EditControlPopup; import java.util.ArrayList; @SuppressLint("ViewConstructor") public class ControlDrawer extends ControlButton { public final ArrayList<ControlSubButton> buttons; public final ControlDrawerData drawerData; public final ControlLayout parentLayout; public boolean areButtonsVisible; public ControlDrawer(ControlLayout layout, ControlDrawerData drawerData) { super(layout, drawerData.properties); buttons = new ArrayList<>(drawerData.buttonProperties.size()); this.parentLayout = layout; this.drawerData = drawerData; areButtonsVisible = layout.getModifiable(); } public void addButton(ControlData properties){ addButton(new ControlSubButton(parentLayout, properties, this)); } public void addButton(ControlSubButton button){ buttons.add(button); syncButtons(); setControlButtonVisibility(button, areButtonsVisible); } private void setControlButtonVisibility(ControlButton button, boolean isVisible){ button.getControlView().setVisibility(isVisible ? VISIBLE : GONE); } private void switchButtonVisibility(){ areButtonsVisible = !areButtonsVisible; int visibility = areButtonsVisible ? VISIBLE : GONE; for(ControlButton button : buttons){ button.getControlView().setVisibility(visibility); } } //Syncing stuff private void alignButtons(){ if(buttons == null) return; if(drawerData.orientation == ControlDrawerData.Orientation.FREE) return; for(int i = 0; i < buttons.size(); ++i){ switch (drawerData.orientation){ case RIGHT: buttons.get(i).setDynamicX(generateDynamicX(getX() + (drawerData.properties.getWidth() + Tools.dpToPx(2))*(i+1) )); buttons.get(i).setDynamicY(generateDynamicY(getY())); break; case LEFT: buttons.get(i).setDynamicX(generateDynamicX(getX() - (drawerData.properties.getWidth() + Tools.dpToPx(2))*(i+1))); buttons.get(i).setDynamicY(generateDynamicY(getY())); break; case UP: buttons.get(i).setDynamicY(generateDynamicY(getY() - (drawerData.properties.getHeight() + Tools.dpToPx(2))*(i+1))); buttons.get(i).setDynamicX(generateDynamicX(getX())); break; case DOWN: buttons.get(i).setDynamicY(generateDynamicY(getY() + (drawerData.properties.getHeight() + Tools.dpToPx(2))*(i+1))); buttons.get(i).setDynamicX(generateDynamicX(getX())); break; } buttons.get(i).updateProperties(); } } private void resizeButtons(){ if (buttons == null || drawerData.orientation == ControlDrawerData.Orientation.FREE) return; for(ControlSubButton subButton : buttons){ subButton.mProperties.setWidth(mProperties.getWidth()); subButton.mProperties.setHeight(mProperties.getHeight()); subButton.updateProperties(); } } public void syncButtons(){ alignButtons(); resizeButtons(); } /** * Check whether or not the button passed as a parameter belongs to this drawer. * * @param button The button to look for * @return Whether the button is in the buttons list of the drawer. */ public boolean containsChild(ControlInterface button){ for(ControlButton childButton : buttons){ if (childButton == button) return true; } return false; } @Override public ControlData preProcessProperties(ControlData properties, ControlLayout layout) { ControlData data = super.preProcessProperties(properties, layout); data.isHideable = true; return data; } @Override public void setVisible(boolean isVisible) { int visibility = isVisible ? VISIBLE : GONE; setVisibility(visibility); if(visibility == GONE || areButtonsVisible) { for(ControlSubButton button : buttons){ button.getControlView().setVisibility(isVisible ? VISIBLE : (!mProperties.isHideable && getVisibility() == GONE) ? VISIBLE : View.GONE); } } } @SuppressLint("ClickableViewAccessibility") @Override public boolean onTouchEvent(MotionEvent event) { if(!getControlLayoutParent().getModifiable()){ switch (event.getActionMasked()){ case MotionEvent.ACTION_UP: // 1 case MotionEvent.ACTION_POINTER_UP: // 6 switchButtonVisibility(); break; } return true; } return super.onTouchEvent(event); } @Override public void setX(float x) { super.setX(x); alignButtons(); } @Override public void setY(float y) { super.setY(y); alignButtons(); } @Override public void setLayoutParams(ViewGroup.LayoutParams params) { super.setLayoutParams(params); syncButtons(); } @Override public boolean canSnap(ControlInterface button) { boolean result = super.canSnap(button); return result && !containsChild(button); } //Getters public ControlDrawerData getDrawerData() { return drawerData; } @Override public void loadEditValues(EditControlPopup editControlPopup) { editControlPopup.loadValues(drawerData); } @Override public void cloneButton() { ControlDrawerData cloneData = new ControlDrawerData(getDrawerData()); cloneData.properties.dynamicX = "0.5 * ${screen_width}"; cloneData.properties.dynamicY = "0.5 * ${screen_height}"; ((ControlLayout) getParent()).addDrawer(cloneData); } @Override public void removeButton() { ControlLayout layout = getControlLayoutParent(); for(ControlSubButton subButton : buttons){ layout.removeView(subButton); } layout.getLayout().mDrawerDataList.remove(getDrawerData()); layout.removeView(this); } }
6,741
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
ControlButton.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/customcontrols/buttons/ControlButton.java
package net.kdt.pojavlaunch.customcontrols.buttons; import static net.kdt.pojavlaunch.LwjglGlfwKeycode.GLFW_KEY_UNKNOWN; import static org.lwjgl.glfw.CallbackBridge.sendKeyPress; import static org.lwjgl.glfw.CallbackBridge.sendMouseButton; import android.annotation.SuppressLint; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.Log; import android.util.TypedValue; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.widget.TextView; import net.kdt.pojavlaunch.LwjglGlfwKeycode; import net.kdt.pojavlaunch.MainActivity; import net.kdt.pojavlaunch.R; import net.kdt.pojavlaunch.customcontrols.ControlData; import net.kdt.pojavlaunch.customcontrols.ControlLayout; import net.kdt.pojavlaunch.customcontrols.handleview.EditControlPopup; import net.kdt.pojavlaunch.prefs.LauncherPreferences; import org.lwjgl.glfw.CallbackBridge; @SuppressLint({"ViewConstructor", "AppCompatCustomView"}) public class ControlButton extends TextView implements ControlInterface { private final Paint mRectPaint = new Paint(); protected ControlData mProperties; private final ControlLayout mControlLayout; /* Cache value from the ControlData radius for drawing purposes */ private float mComputedRadius; protected boolean mIsToggled = false; protected boolean mIsPointerOutOfBounds = false; public ControlButton(ControlLayout layout, ControlData properties) { super(layout.getContext()); mControlLayout = layout; setGravity(Gravity.CENTER); setAllCaps(LauncherPreferences.PREF_BUTTON_ALL_CAPS); setTextColor(Color.WHITE); setPadding(4, 4, 4, 4); setTextSize(14); // Nullify the default size setting setOutlineProvider(null); // Disable shadow casting, removing one drawing pass //setOnLongClickListener(this); //When a button is created, the width/height has yet to be processed to fit the scaling. setProperties(preProcessProperties(properties, layout)); injectBehaviors(); } @Override public View getControlView() {return this;} public ControlData getProperties() { return mProperties; } public void setProperties(ControlData properties, boolean changePos) { mProperties = properties; ControlInterface.super.setProperties(properties, changePos); mComputedRadius = ControlInterface.super.computeCornerRadius(mProperties.cornerRadius); if (mProperties.isToggle) { //For the toggle layer final TypedValue value = new TypedValue(); getContext().getTheme().resolveAttribute(R.attr.colorAccent, value, true); mRectPaint.setColor(value.data); mRectPaint.setAlpha(128); } else { mRectPaint.setColor(Color.WHITE); mRectPaint.setAlpha(60); } setText(properties.name); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (mIsToggled || (!mProperties.isToggle && isActivated())) canvas.drawRoundRect(0, 0, getWidth(), getHeight(), mComputedRadius, mComputedRadius, mRectPaint); } public void loadEditValues(EditControlPopup editControlPopup){ editControlPopup.loadValues(getProperties()); } /** Add another instance of the ControlButton to the parent layout */ public void cloneButton(){ ControlData cloneData = new ControlData(getProperties()); cloneData.dynamicX = "0.5 * ${screen_width}"; cloneData.dynamicY = "0.5 * ${screen_height}"; ((ControlLayout) getParent()).addControlButton(cloneData); } /** Remove any trace of this button from the layout */ public void removeButton() { getControlLayoutParent().getLayout().mControlDataList.remove(getProperties()); getControlLayoutParent().removeView(this); } @SuppressLint("ClickableViewAccessibility") @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getActionMasked()){ case MotionEvent.ACTION_MOVE: //Send the event to be taken as a mouse action if(getProperties().passThruEnabled && CallbackBridge.isGrabbing()){ View gameSurface = getControlLayoutParent().getGameSurface(); if(gameSurface != null) gameSurface.dispatchTouchEvent(event); } //If out of bounds if(event.getX() < getControlView().getLeft() || event.getX() > getControlView().getRight() || event.getY() < getControlView().getTop() || event.getY() > getControlView().getBottom()){ if(getProperties().isSwipeable && !mIsPointerOutOfBounds){ //Remove keys if(!triggerToggle()) { sendKeyPresses(false); } } mIsPointerOutOfBounds = true; getControlLayoutParent().onTouch(this, event); break; } //Else if we now are in bounds if(mIsPointerOutOfBounds) { getControlLayoutParent().onTouch(this, event); //RE-press the button if(getProperties().isSwipeable && !getProperties().isToggle){ sendKeyPresses(true); } } mIsPointerOutOfBounds = false; break; case MotionEvent.ACTION_DOWN: // 0 case MotionEvent.ACTION_POINTER_DOWN: // 5 if(!getProperties().isToggle){ sendKeyPresses(true); } break; case MotionEvent.ACTION_UP: // 1 case MotionEvent.ACTION_CANCEL: // 3 case MotionEvent.ACTION_POINTER_UP: // 6 if(getProperties().passThruEnabled){ View gameSurface = getControlLayoutParent().getGameSurface(); if(gameSurface != null) gameSurface.dispatchTouchEvent(event); } if(mIsPointerOutOfBounds) getControlLayoutParent().onTouch(this, event); mIsPointerOutOfBounds = false; if(!triggerToggle()) { sendKeyPresses(false); } break; default: return false; } return super.onTouchEvent(event); } @SuppressWarnings("BooleanMethodIsAlwaysInverted") public boolean triggerToggle(){ //returns true a the toggle system is triggered if(mProperties.isToggle){ mIsToggled = !mIsToggled; invalidate(); sendKeyPresses(mIsToggled); return true; } return false; } public void sendKeyPresses(boolean isDown){ setActivated(isDown); for(int keycode : mProperties.keycodes){ if(keycode >= GLFW_KEY_UNKNOWN){ sendKeyPress(keycode, CallbackBridge.getCurrentMods(), isDown); CallbackBridge.setModifiers(keycode, isDown); }else{ Log.i("punjabilauncher", "sendSpecialKey("+keycode+","+isDown+")"); sendSpecialKey(keycode, isDown); } } } private void sendSpecialKey(int keycode, boolean isDown){ switch (keycode) { case ControlData.SPECIALBTN_KEYBOARD: if(isDown) MainActivity.switchKeyboardState(); break; case ControlData.SPECIALBTN_TOGGLECTRL: if(isDown)MainActivity.mControlLayout.toggleControlVisible(); break; case ControlData.SPECIALBTN_VIRTUALMOUSE: if(isDown) MainActivity.toggleMouse(getContext()); break; case ControlData.SPECIALBTN_MOUSEPRI: sendMouseButton(LwjglGlfwKeycode.GLFW_MOUSE_BUTTON_LEFT, isDown); break; case ControlData.SPECIALBTN_MOUSEMID: sendMouseButton(LwjglGlfwKeycode.GLFW_MOUSE_BUTTON_MIDDLE, isDown); break; case ControlData.SPECIALBTN_MOUSESEC: sendMouseButton(LwjglGlfwKeycode.GLFW_MOUSE_BUTTON_RIGHT, isDown); break; case ControlData.SPECIALBTN_SCROLLDOWN: if (!isDown) CallbackBridge.sendScroll(0, 1d); break; case ControlData.SPECIALBTN_SCROLLUP: if (!isDown) CallbackBridge.sendScroll(0, -1d); break; case ControlData.SPECIALBTN_MENU: mControlLayout.notifyAppMenu(); break; } } @Override public boolean hasOverlappingRendering() { return false; } }
8,958
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
CharacterSenderStrategy.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/customcontrols/keyboard/CharacterSenderStrategy.java
package net.kdt.pojavlaunch.customcontrols.keyboard; /** Simple interface for sending chars through whatever bridge will be necessary */ public interface CharacterSenderStrategy { /** Called when there is a character to delete, may be called multiple times in a row */ void sendBackspace(); /** Called when we want to send enter specifically */ void sendEnter(); /** Called when there is a character to send, may be called multiple times in a row */ void sendChar(char character); }
511
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
AwtCharSender.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/customcontrols/keyboard/AwtCharSender.java
package net.kdt.pojavlaunch.customcontrols.keyboard; import net.kdt.pojavlaunch.AWTInputBridge; import net.kdt.pojavlaunch.AWTInputEvent; /** Send chars via the AWT Bridgee */ public class AwtCharSender implements CharacterSenderStrategy { @Override public void sendBackspace() { AWTInputBridge.sendKey(' ', AWTInputEvent.VK_BACK_SPACE); } @Override public void sendEnter() { AWTInputBridge.sendKey(' ', AWTInputEvent.VK_ENTER); } @Override public void sendChar(char character) { AWTInputBridge.sendChar(character); } }
585
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
LwjglCharSender.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/customcontrols/keyboard/LwjglCharSender.java
package net.kdt.pojavlaunch.customcontrols.keyboard; import static org.lwjgl.glfw.CallbackBridge.sendKeyPress; import net.kdt.pojavlaunch.LwjglGlfwKeycode; import org.lwjgl.glfw.CallbackBridge; /** Sends keys via the CallBackBridge */ public class LwjglCharSender implements CharacterSenderStrategy { @Override public void sendBackspace() { CallbackBridge.sendKeycode(LwjglGlfwKeycode.GLFW_KEY_BACKSPACE, '\u0008', 0, 0, true); CallbackBridge.sendKeycode(LwjglGlfwKeycode.GLFW_KEY_BACKSPACE, '\u0008', 0, 0, false); } @Override public void sendEnter() { sendKeyPress(LwjglGlfwKeycode.GLFW_KEY_ENTER); } @Override public void sendChar(char character) { CallbackBridge.sendChar(character, 0); } }
769
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
TouchCharInput.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/customcontrols/keyboard/TouchCharInput.java
package net.kdt.pojavlaunch.customcontrols.keyboard; import static android.content.Context.INPUT_METHOD_SERVICE; import android.annotation.SuppressLint; import android.content.Context; import android.util.AttributeSet; import android.view.KeyEvent; import android.view.inputmethod.InputMethodManager; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import net.kdt.pojavlaunch.R; /** * This class is intended for sending characters used in chat via the virtual keyboard */ public class TouchCharInput extends androidx.appcompat.widget.AppCompatEditText { public static final String TEXT_FILLER = " "; public TouchCharInput(@NonNull Context context) { this(context, null); } public TouchCharInput(@NonNull Context context, @Nullable AttributeSet attrs) { this(context, attrs, R.attr.editTextStyle); } public TouchCharInput(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); setup(); } private boolean mIsDoingInternalChanges = false; private CharacterSenderStrategy mCharacterSender; /** * We take the new chars, and send them to the game. * If less chars are present, remove some. * The text is always cleaned up. */ @Override protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) { super.onTextChanged(text, start, lengthBefore, lengthAfter); if(mIsDoingInternalChanges)return; if(mCharacterSender != null){ for(int i=0; i < lengthBefore; ++i){ mCharacterSender.sendBackspace(); } for(int i=start, count = 0; count < lengthAfter; ++i){ mCharacterSender.sendChar(text.charAt(i)); ++count; } } //Reset the keyboard state if(text.length() < 1) clear(); } /** * When we change from app to app, the keyboard gets disabled. * So, we disable the object */ @Override public void onWindowFocusChanged(boolean hasWindowFocus) { super.onWindowFocusChanged(hasWindowFocus); disable(); } /** * Intercepts the back key to disable focus * Does not affect the rest of the activity. */ @Override public boolean onKeyPreIme(final int keyCode, final KeyEvent event) { if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) { disable(); } return super.onKeyPreIme(keyCode, event); } /** * Toggle on and off the soft keyboard, depending of the state */ public void switchKeyboardState(){ InputMethodManager imm = (InputMethodManager) getContext().getSystemService(INPUT_METHOD_SERVICE); // Allow, regardless of whether or not a hardware keyboard is declared if(hasFocus()){ clear(); disable(); }else{ enable(); imm.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT); } } /** * Clear the EditText from any leftover inputs * It does not affect the in-game input */ @SuppressLint("SetTextI18n") public void clear(){ mIsDoingInternalChanges = true; //Braille space, doesn't trigger keyboard auto-complete //replacing directly the text without though setText avoids notifying changes setText(TEXT_FILLER); setSelection(TEXT_FILLER.length()); mIsDoingInternalChanges = false; } /** Regain ability to exist, take focus and have some text being input */ public void enable(){ setEnabled(true); setFocusable(true); setVisibility(VISIBLE); requestFocus(); } /** Lose ability to exist, take focus and have some text being input */ public void disable(){ clear(); setVisibility(GONE); clearFocus(); setEnabled(false); //setFocusable(false); } /** Send the enter key. */ private void sendEnter(){ mCharacterSender.sendEnter(); clear(); } /** Just sets the char sender that should be used. */ public void setCharacterSender(CharacterSenderStrategy characterSender){ mCharacterSender = characterSender; } /** This function deals with anything that has to be executed when the constructor is called */ private void setup(){ setOnEditorActionListener((textView, i, keyEvent) -> { sendEnter(); clear(); disable(); return false; }); clear(); disable(); } }
4,726
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
GamepadButton.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/customcontrols/gamepad/GamepadButton.java
package net.kdt.pojavlaunch.customcontrols.gamepad; import android.view.KeyEvent; /** * Simple button able to store its state and some properties */ public class GamepadButton { public int[] keycodes; public boolean isToggleable = false; private boolean mIsDown = false; private boolean mIsToggled = false; public void update(KeyEvent event){ boolean isKeyDown = (event.getAction() == KeyEvent.ACTION_DOWN); update(isKeyDown); } public void update(boolean isKeyDown){ if(isKeyDown != mIsDown){ mIsDown = isKeyDown; if(isToggleable){ if(isKeyDown){ mIsToggled = !mIsToggled; Gamepad.sendInput(keycodes, mIsToggled); } return; } Gamepad.sendInput(keycodes, mIsDown); } } public void resetButtonState(){ if(mIsDown || mIsToggled){ Gamepad.sendInput(keycodes, false); } mIsDown = false; mIsToggled = false; } public boolean isDown(){ return isToggleable ? mIsToggled : mIsDown; } }
1,156
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
GamepadJoystick.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/customcontrols/gamepad/GamepadJoystick.java
package net.kdt.pojavlaunch.customcontrols.gamepad; import static net.kdt.pojavlaunch.prefs.LauncherPreferences.PREF_DEADZONE_SCALE; import android.util.Log; import android.view.InputDevice; import android.view.MotionEvent; import net.kdt.pojavlaunch.utils.MathUtils; public class GamepadJoystick { //Directions public static final int DIRECTION_NONE = -1; //GamepadJoystick at the center public static final int DIRECTION_EAST = 0; public static final int DIRECTION_NORTH_EAST = 1; public static final int DIRECTION_NORTH = 2; public static final int DIRECTION_NORTH_WEST = 3; public static final int DIRECTION_WEST = 4; public static final int DIRECTION_SOUTH_WEST = 5; public static final int DIRECTION_SOUTH = 6; public static final int DIRECTION_SOUTH_EAST = 7; private final InputDevice mInputDevice; private final int mHorizontalAxis; private final int mVerticalAxis; private float mVerticalAxisValue = 0; private float mHorizontalAxisValue = 0; public GamepadJoystick(int horizontalAxis, int verticalAxis, InputDevice device){ mHorizontalAxis = horizontalAxis; mVerticalAxis = verticalAxis; this.mInputDevice = device; } public double getAngleRadian(){ //From -PI to PI // TODO misuse of the deadzone here ! return -Math.atan2(getVerticalAxis(), getHorizontalAxis()); } public double getAngleDegree(){ //From 0 to 360 degrees double result = Math.toDegrees(getAngleRadian()); if(result < 0) result += 360; return result; } public double getMagnitude(){ float x = Math.abs(mHorizontalAxisValue); float y = Math.abs(mVerticalAxisValue); return MathUtils.dist(0,0, x, y); } public float getVerticalAxis(){ return mVerticalAxisValue; } public float getHorizontalAxis(){ return mHorizontalAxisValue; } public static boolean isJoystickEvent(MotionEvent event){ return (event.getSource() & InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK && event.getAction() == MotionEvent.ACTION_MOVE; } public int getHeightDirection(){ if(getMagnitude() == 0) return DIRECTION_NONE; return ((int) ((getAngleDegree()+22.5)/45)) % 8; } /* Setters */ public void setXAxisValue(float value){ this.mHorizontalAxisValue = value; } public void setYAxisValue(float value){ this.mVerticalAxisValue = value; } }
2,545
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
GamepadDpad.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/customcontrols/gamepad/GamepadDpad.java
package net.kdt.pojavlaunch.customcontrols.gamepad; import static android.view.InputDevice.KEYBOARD_TYPE_ALPHABETIC; import static android.view.InputDevice.SOURCE_GAMEPAD; import static android.view.KeyEvent.KEYCODE_DPAD_CENTER; import static android.view.KeyEvent.KEYCODE_DPAD_DOWN; import static android.view.KeyEvent.KEYCODE_DPAD_LEFT; import static android.view.KeyEvent.KEYCODE_DPAD_RIGHT; import static android.view.KeyEvent.KEYCODE_DPAD_UP; import android.view.InputDevice; import android.view.KeyEvent; import android.view.MotionEvent; public class GamepadDpad { private int mLastKeycode = KEYCODE_DPAD_CENTER; /** * Convert the event to a 2 int array: keycode and keyAction, similar to a keyEvent * @param event The motion to convert * @return int[0] keycode, int[1] keyAction */ public int[] convertEvent(MotionEvent event){ // Use the hat axis value to find the D-pad direction float xaxis = event.getAxisValue(MotionEvent.AXIS_HAT_X); float yaxis = event.getAxisValue(MotionEvent.AXIS_HAT_Y); int action = KeyEvent.ACTION_DOWN; // Check if the AXIS_HAT_X value is -1 or 1, and set the D-pad // LEFT and RIGHT direction accordingly. if (Float.compare(xaxis, -1.0f) == 0) { mLastKeycode = KEYCODE_DPAD_LEFT; } else if (Float.compare(xaxis, 1.0f) == 0) { mLastKeycode = KEYCODE_DPAD_RIGHT; } // Check if the AXIS_HAT_Y value is -1 or 1, and set the D-pad // UP and DOWN direction accordingly. else if (Float.compare(yaxis, -1.0f) == 0) { mLastKeycode = KEYCODE_DPAD_UP; } else if (Float.compare(yaxis, 1.0f) == 0) { mLastKeycode = KEYCODE_DPAD_DOWN; }else { //No keycode change action = KeyEvent.ACTION_UP; } return new int[]{mLastKeycode, action}; } @SuppressWarnings("unused") public static boolean isDpadEvent(MotionEvent event) { // Check that input comes from a device with directional pads. // And... also the joystick since it declares sometimes as a joystick. return (event.getSource() & InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK; } public static boolean isDpadEvent(KeyEvent event){ //return ((event.getSource() & InputDevice.SOURCE_DPAD) == InputDevice.SOURCE_DPAD) && (event.getDevice().getKeyboardType() == KEYBOARD_TYPE_NON_ALPHABETIC); return event.isFromSource(SOURCE_GAMEPAD) && event.getDevice().getKeyboardType() != KEYBOARD_TYPE_ALPHABETIC; } }
2,592
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
Gamepad.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/customcontrols/gamepad/Gamepad.java
package net.kdt.pojavlaunch.customcontrols.gamepad; import static android.view.MotionEvent.AXIS_HAT_X; import static android.view.MotionEvent.AXIS_HAT_Y; import static android.view.MotionEvent.AXIS_LTRIGGER; import static android.view.MotionEvent.AXIS_RTRIGGER; import static android.view.MotionEvent.AXIS_RZ; import static android.view.MotionEvent.AXIS_X; import static android.view.MotionEvent.AXIS_Y; import static android.view.MotionEvent.AXIS_Z; import android.content.Context; import android.view.Choreographer; import android.view.InputDevice; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.Toast; import androidx.core.content.res.ResourcesCompat; import androidx.core.math.MathUtils; import net.kdt.pojavlaunch.GrabListener; import net.kdt.pojavlaunch.LwjglGlfwKeycode; import net.kdt.pojavlaunch.R; import net.kdt.pojavlaunch.Tools; import net.kdt.pojavlaunch.prefs.LauncherPreferences; import net.kdt.pojavlaunch.utils.MCOptionUtils; import org.lwjgl.glfw.CallbackBridge; import static net.kdt.pojavlaunch.Tools.currentDisplayMetrics; import static net.kdt.pojavlaunch.customcontrols.gamepad.GamepadJoystick.DIRECTION_EAST; import static net.kdt.pojavlaunch.customcontrols.gamepad.GamepadJoystick.DIRECTION_NONE; import static net.kdt.pojavlaunch.customcontrols.gamepad.GamepadJoystick.DIRECTION_NORTH; import static net.kdt.pojavlaunch.customcontrols.gamepad.GamepadJoystick.DIRECTION_NORTH_EAST; import static net.kdt.pojavlaunch.customcontrols.gamepad.GamepadJoystick.DIRECTION_NORTH_WEST; import static net.kdt.pojavlaunch.customcontrols.gamepad.GamepadJoystick.DIRECTION_SOUTH; import static net.kdt.pojavlaunch.customcontrols.gamepad.GamepadJoystick.DIRECTION_SOUTH_EAST; import static net.kdt.pojavlaunch.customcontrols.gamepad.GamepadJoystick.DIRECTION_SOUTH_WEST; import static net.kdt.pojavlaunch.customcontrols.gamepad.GamepadJoystick.DIRECTION_WEST; import static net.kdt.pojavlaunch.customcontrols.gamepad.GamepadJoystick.isJoystickEvent; import static net.kdt.pojavlaunch.prefs.LauncherPreferences.PREF_DEADZONE_SCALE; import static net.kdt.pojavlaunch.utils.MCOptionUtils.getMcScale; import static org.lwjgl.glfw.CallbackBridge.sendKeyPress; import static org.lwjgl.glfw.CallbackBridge.sendMouseButton; import fr.spse.gamepad_remapper.GamepadHandler; import fr.spse.gamepad_remapper.Settings; public class Gamepad implements GrabListener, GamepadHandler { /* Resolution scaler option, allow downsizing a window */ private final float mScaleFactor = LauncherPreferences.DEFAULT_PREF.getInt("resolutionRatio",100)/100f; /* Sensitivity, adjusted according to screen size */ private final double mSensitivityFactor = (1.4 * (1080f/ currentDisplayMetrics.heightPixels)); private final ImageView mPointerImageView; private final GamepadJoystick mLeftJoystick; private int mCurrentJoystickDirection = DIRECTION_NONE; private final GamepadJoystick mRightJoystick; private float mLastHorizontalValue = 0.0f; private float mLastVerticalValue = 0.0f; private static final double MOUSE_MAX_ACCELERATION = 2f; private double mMouseMagnitude; private double mMouseAngle; private double mMouseSensitivity = 19; private final GamepadMap mGameMap = GamepadMap.getDefaultGameMap(); private final GamepadMap mMenuMap = GamepadMap.getDefaultMenuMap(); private GamepadMap mCurrentMap = mGameMap; // The negation is to force trigger the onGrabState private boolean isGrabbing = !CallbackBridge.isGrabbing(); /* Choreographer with time to compute delta on ticking */ private final Choreographer mScreenChoreographer; private long mLastFrameTime; /* Listen for change in gui scale */ @SuppressWarnings("FieldCanBeLocal") //the field is used in a WeakReference private final MCOptionUtils.MCOptionListener mGuiScaleListener = () -> notifyGUISizeChange(getMcScale()); public Gamepad(View contextView, InputDevice inputDevice){ Settings.setDeadzoneScale(PREF_DEADZONE_SCALE); mScreenChoreographer = Choreographer.getInstance(); Choreographer.FrameCallback frameCallback = new Choreographer.FrameCallback() { @Override public void doFrame(long frameTimeNanos) { tick(frameTimeNanos); mScreenChoreographer.postFrameCallback(this); } }; mScreenChoreographer.postFrameCallback(frameCallback); mLastFrameTime = System.nanoTime(); /* Add the listener for the cross hair */ MCOptionUtils.addMCOptionListener(mGuiScaleListener); mLeftJoystick = new GamepadJoystick(AXIS_X, AXIS_Y, inputDevice); mRightJoystick = new GamepadJoystick(AXIS_Z, AXIS_RZ, inputDevice); Context ctx = contextView.getContext(); mPointerImageView = new ImageView(contextView.getContext()); mPointerImageView.setImageDrawable(ResourcesCompat.getDrawable(ctx.getResources(), R.drawable.ic_gamepad_pointer, ctx.getTheme())); mPointerImageView.getDrawable().setFilterBitmap(false); int size = (int) ((22 * getMcScale()) / mScaleFactor); mPointerImageView.setLayoutParams(new FrameLayout.LayoutParams(size, size)); CallbackBridge.sendCursorPos(CallbackBridge.windowWidth/2f, CallbackBridge.windowHeight/2f); ((ViewGroup)contextView.getParent()).addView(mPointerImageView); placePointerView(CallbackBridge.physicalWidth/2, CallbackBridge.physicalHeight/2); CallbackBridge.addGrabListener(this); } public void updateJoysticks(){ updateDirectionalJoystick(); updateMouseJoystick(); } public void notifyGUISizeChange(int newSize){ //Change the pointer size to match UI int size = (int) ((22 * newSize) / mScaleFactor); mPointerImageView.post(() -> mPointerImageView.setLayoutParams(new FrameLayout.LayoutParams(size, size))); } public static void sendInput(int[] keycodes, boolean isDown){ for(int keycode : keycodes){ switch (keycode){ case GamepadMap.MOUSE_SCROLL_DOWN: if(isDown) CallbackBridge.sendScroll(0, -1); break; case GamepadMap.MOUSE_SCROLL_UP: if(isDown) CallbackBridge.sendScroll(0, 1); break; case LwjglGlfwKeycode.GLFW_MOUSE_BUTTON_RIGHT: sendMouseButton(LwjglGlfwKeycode.GLFW_MOUSE_BUTTON_RIGHT, isDown); break; case LwjglGlfwKeycode.GLFW_MOUSE_BUTTON_LEFT: sendMouseButton(LwjglGlfwKeycode.GLFW_MOUSE_BUTTON_LEFT, isDown); break; default: sendKeyPress(keycode, CallbackBridge.getCurrentMods(), isDown); break; } CallbackBridge.setModifiers(keycode, isDown); } } public static boolean isGamepadEvent(MotionEvent event){ return isJoystickEvent(event); } public static boolean isGamepadEvent(KeyEvent event){ boolean isGamepad = ((event.getSource() & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD) || ((event.getDevice() != null) && ((event.getDevice().getSources() & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD)); return isGamepad && GamepadDpad.isDpadEvent(event); } /** * Send the new mouse position, computing the delta * @param frameTimeNanos The time to render the frame, used to compute mouse delta */ private void tick(long frameTimeNanos){ //update mouse position long newFrameTime = System.nanoTime(); if(mLastHorizontalValue != 0 || mLastVerticalValue != 0){ double acceleration = Math.pow(mMouseMagnitude, MOUSE_MAX_ACCELERATION); if(acceleration > 1) acceleration = 1; // Compute delta since last tick time float deltaX = (float) (Math.cos(mMouseAngle) * acceleration * mMouseSensitivity); float deltaY = (float) (Math.sin(mMouseAngle) * acceleration * mMouseSensitivity); newFrameTime = System.nanoTime(); // More accurate delta float deltaTimeScale = ((newFrameTime - mLastFrameTime) / 16666666f); // Scale of 1 = 60Hz deltaX *= deltaTimeScale; deltaY *= deltaTimeScale; CallbackBridge.mouseX += deltaX; CallbackBridge.mouseY -= deltaY; if(!isGrabbing){ CallbackBridge.mouseX = MathUtils.clamp(CallbackBridge.mouseX, 0, CallbackBridge.windowWidth); CallbackBridge.mouseY = MathUtils.clamp(CallbackBridge.mouseY, 0, CallbackBridge.windowHeight); placePointerView((int) (CallbackBridge.mouseX / mScaleFactor), (int) (CallbackBridge.mouseY/ mScaleFactor)); } //Send the mouse to the game CallbackBridge.sendCursorPos(CallbackBridge.mouseX, CallbackBridge.mouseY); } // Update last nano time mLastFrameTime = newFrameTime; } private void updateMouseJoystick(){ GamepadJoystick currentJoystick = isGrabbing ? mRightJoystick : mLeftJoystick; float horizontalValue = currentJoystick.getHorizontalAxis(); float verticalValue = currentJoystick.getVerticalAxis(); if(horizontalValue != mLastHorizontalValue || verticalValue != mLastVerticalValue){ mLastHorizontalValue = horizontalValue; mLastVerticalValue = verticalValue; mMouseMagnitude = currentJoystick.getMagnitude(); mMouseAngle = currentJoystick.getAngleRadian(); tick(System.nanoTime()); return; } mLastHorizontalValue = horizontalValue; mLastVerticalValue = verticalValue; mMouseMagnitude = currentJoystick.getMagnitude(); mMouseAngle = currentJoystick.getAngleRadian(); } private void updateDirectionalJoystick(){ GamepadJoystick currentJoystick = isGrabbing ? mLeftJoystick : mRightJoystick; int lastJoystickDirection = mCurrentJoystickDirection; mCurrentJoystickDirection = currentJoystick.getHeightDirection(); if(mCurrentJoystickDirection == lastJoystickDirection) return; sendDirectionalKeycode(lastJoystickDirection, false, getCurrentMap()); sendDirectionalKeycode(mCurrentJoystickDirection, true, getCurrentMap()); } private GamepadMap getCurrentMap(){ return mCurrentMap; } private static void sendDirectionalKeycode(int direction, boolean isDown, GamepadMap map){ switch (direction){ case DIRECTION_NORTH: sendInput(map.DIRECTION_FORWARD, isDown); break; case DIRECTION_NORTH_EAST: sendInput(map.DIRECTION_FORWARD, isDown); sendInput(map.DIRECTION_RIGHT, isDown); break; case DIRECTION_EAST: sendInput(map.DIRECTION_RIGHT, isDown); break; case DIRECTION_SOUTH_EAST: sendInput(map.DIRECTION_RIGHT, isDown); sendInput(map.DIRECTION_BACKWARD, isDown); break; case DIRECTION_SOUTH: sendInput(map.DIRECTION_BACKWARD, isDown); break; case DIRECTION_SOUTH_WEST: sendInput(map.DIRECTION_BACKWARD, isDown); sendInput(map.DIRECTION_LEFT, isDown); break; case DIRECTION_WEST: sendInput(map.DIRECTION_LEFT, isDown); break; case DIRECTION_NORTH_WEST: sendInput(map.DIRECTION_FORWARD, isDown); sendInput(map.DIRECTION_LEFT, isDown); break; } } /** Place the pointer on the screen, offsetting the image size */ private void placePointerView(int x, int y){ mPointerImageView.setX(x - mPointerImageView.getWidth()/2f); mPointerImageView.setY(y - mPointerImageView.getHeight()/2f); } /** Update the grabbing state, and change the currentMap, mouse position and sensibility */ @Override public void onGrabState(boolean isGrabbing) { boolean lastGrabbingValue = this.isGrabbing; this.isGrabbing = isGrabbing; if(lastGrabbingValue == isGrabbing) return; // Switch grabbing state then mCurrentMap.resetPressedState(); if(isGrabbing){ mCurrentMap = mGameMap; mPointerImageView.setVisibility(View.INVISIBLE); mMouseSensitivity = 18; return; } mCurrentMap = mMenuMap; sendDirectionalKeycode(mCurrentJoystickDirection, false, mGameMap); // removing what we were doing CallbackBridge.sendCursorPos(CallbackBridge.windowWidth/2f, CallbackBridge.windowHeight/2f); placePointerView(CallbackBridge.physicalWidth/2, CallbackBridge.physicalHeight/2); mPointerImageView.setVisibility(View.VISIBLE); // Sensitivity in menu is MC and HARDWARE resolution dependent mMouseSensitivity = 19 * mScaleFactor / mSensitivityFactor; } @Override public void handleGamepadInput(int keycode, float value) { boolean isKeyEventDown = value == 1f; switch (keycode){ case KeyEvent.KEYCODE_BUTTON_A: getCurrentMap().BUTTON_A.update(isKeyEventDown); break; case KeyEvent.KEYCODE_BUTTON_B: getCurrentMap().BUTTON_B.update(isKeyEventDown); break; case KeyEvent.KEYCODE_BUTTON_X: getCurrentMap().BUTTON_X.update(isKeyEventDown); break; case KeyEvent.KEYCODE_BUTTON_Y: getCurrentMap().BUTTON_Y.update(isKeyEventDown); break; //Shoulders case KeyEvent.KEYCODE_BUTTON_L1: getCurrentMap().SHOULDER_LEFT.update(isKeyEventDown); break; case KeyEvent.KEYCODE_BUTTON_R1: getCurrentMap().SHOULDER_RIGHT.update(isKeyEventDown); break; //Triggers case KeyEvent.KEYCODE_BUTTON_L2: getCurrentMap().TRIGGER_LEFT.update(isKeyEventDown); break; case KeyEvent.KEYCODE_BUTTON_R2: getCurrentMap().TRIGGER_RIGHT.update(isKeyEventDown); break; //L3 || R3 case KeyEvent.KEYCODE_BUTTON_THUMBL: getCurrentMap().THUMBSTICK_LEFT.update(isKeyEventDown); break; case KeyEvent.KEYCODE_BUTTON_THUMBR: getCurrentMap().THUMBSTICK_RIGHT.update(isKeyEventDown); break; //DPAD case KeyEvent.KEYCODE_DPAD_UP: getCurrentMap().DPAD_UP.update(isKeyEventDown); break; case KeyEvent.KEYCODE_DPAD_DOWN: getCurrentMap().DPAD_DOWN.update(isKeyEventDown); break; case KeyEvent.KEYCODE_DPAD_LEFT: getCurrentMap().DPAD_LEFT.update(isKeyEventDown); break; case KeyEvent.KEYCODE_DPAD_RIGHT: getCurrentMap().DPAD_RIGHT.update(isKeyEventDown); break; case KeyEvent.KEYCODE_DPAD_CENTER: getCurrentMap().DPAD_RIGHT.update(false); getCurrentMap().DPAD_LEFT.update(false); getCurrentMap().DPAD_UP.update(false); getCurrentMap().DPAD_DOWN.update(false); break; //Start/select case KeyEvent.KEYCODE_BUTTON_START: getCurrentMap().BUTTON_START.update(isKeyEventDown); break; case KeyEvent.KEYCODE_BUTTON_SELECT: getCurrentMap().BUTTON_SELECT.update(isKeyEventDown); break; /* Now, it is time for motionEvents */ case AXIS_HAT_X: getCurrentMap().DPAD_RIGHT.update(value > 0.85); getCurrentMap().DPAD_LEFT.update(value < -0.85); break; case AXIS_HAT_Y: getCurrentMap().DPAD_DOWN.update(value > 0.85); getCurrentMap().DPAD_UP.update(value < -0.85); break; // Left joystick case AXIS_X: mLeftJoystick.setXAxisValue(value); updateJoysticks(); break; case AXIS_Y: mLeftJoystick.setYAxisValue(value); updateJoysticks(); break; // Right joystick case AXIS_Z: mRightJoystick.setXAxisValue(value); updateJoysticks(); break; case AXIS_RZ: mRightJoystick.setYAxisValue(value); updateJoysticks(); break; // Triggers case AXIS_RTRIGGER: getCurrentMap().TRIGGER_RIGHT.update(value > 0.5); break; case AXIS_LTRIGGER: getCurrentMap().TRIGGER_LEFT.update(value > 0.5); break; default: sendKeyPress(LwjglGlfwKeycode.GLFW_KEY_SPACE, CallbackBridge.getCurrentMods(), isKeyEventDown); break; } } }
17,567
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z