diff --git a/AndEngine/src/org/anddev/andengine/opengl/font/Font.java b/AndEngine/src/org/anddev/andengine/opengl/font/Font.java index 6591f9746..2558f50ff 100644 --- a/AndEngine/src/org/anddev/andengine/opengl/font/Font.java +++ b/AndEngine/src/org/anddev/andengine/opengl/font/Font.java @@ -222,7 +222,6 @@ public synchronized void update(final GL10 pGL) { bitmap.recycle(); } lettersPendingToBeDrawnToTexture.clear(); - System.gc(); } } diff --git a/AndEngine/src/org/anddev/andengine/opengl/texture/TextureManager.java b/AndEngine/src/org/anddev/andengine/opengl/texture/TextureManager.java index 8cf6a8332..6a91704d1 100644 --- a/AndEngine/src/org/anddev/andengine/opengl/texture/TextureManager.java +++ b/AndEngine/src/org/anddev/andengine/opengl/texture/TextureManager.java @@ -169,11 +169,6 @@ public synchronized void updateTextures(final GL10 pGL) { texturesManaged.remove(textureToBeUnloaded); } } - - /* Finally invoke the GC if anything has changed. */ - if(texturesToBeLoadedCount > 0 || texturesToBeUnloadedCount > 0){ - System.gc(); - } } // =========================================================== diff --git a/AndEngine/src/org/anddev/andengine/util/path/Path.java b/AndEngine/src/org/anddev/andengine/util/path/Path.java index 7fd2fda22..79053a019 100644 --- a/AndEngine/src/org/anddev/andengine/util/path/Path.java +++ b/AndEngine/src/org/anddev/andengine/util/path/Path.java @@ -119,7 +119,7 @@ public int getToTileColumn() { // Inner and Anonymous Classes // =========================================================== - public class Step { + public static class Step { // =========================================================== // Constants // =========================================================== diff --git a/src/com/dgsrz/bancho/security/SecurityUtils.java b/src/com/dgsrz/bancho/security/SecurityUtils.java index 1b76a8533..fad1ccd26 100644 --- a/src/com/dgsrz/bancho/security/SecurityUtils.java +++ b/src/com/dgsrz/bancho/security/SecurityUtils.java @@ -78,7 +78,7 @@ public static void getAppSignature(Context context, String packageName) { return; } PackageManager pkgMgr = context.getPackageManager(); - PackageInfo info = null; + PackageInfo info; Signature[] signatures; try { @@ -90,13 +90,12 @@ public static void getAppSignature(Context context, String packageName) { info = pkgMgr.getPackageInfo(packageName, PackageManager.GET_SIGNING_CERTIFICATES); SigningInfo signInfo = info.signingInfo; - if(signInfo.hasMultipleSigners()) { + if (signInfo.hasMultipleSigners()) { signatures = signInfo.getApkContentsSigners(); - appSignature = getHashCode(signatures[0].toByteArray()); }else { signatures = signInfo.getSigningCertificateHistory(); - appSignature = getHashCode(signatures[0].toByteArray()); } + appSignature = getHashCode(signatures[0].toByteArray()); }else { info = pkgMgr.getPackageInfo(packageName, PackageManager.GET_SIGNATURES); if(info != null && info.signatures != null && info.signatures.length > 0) { @@ -104,8 +103,7 @@ public static void getAppSignature(Context context, String packageName) { appSignature = getHashCode(sign.toByteArray()); } } - } catch (PackageManager.NameNotFoundException e) { - return; + } catch (PackageManager.NameNotFoundException ignored) { } } diff --git a/src/com/dgsrz/bancho/ui/StoryBoardTestActivity.java b/src/com/dgsrz/bancho/ui/StoryBoardTestActivity.java index 2e1bd72b3..2f47be3fc 100644 --- a/src/com/dgsrz/bancho/ui/StoryBoardTestActivity.java +++ b/src/com/dgsrz/bancho/ui/StoryBoardTestActivity.java @@ -80,7 +80,6 @@ public Scene onLoadScene() { BassAudioPlayer.initDevice(); try { - System.gc(); OsbParser.instance.parse(FOLDER + PATH); } catch (IOException e) { e.printStackTrace(); diff --git a/src/com/edlplan/favorite/FavoriteLibrary.java b/src/com/edlplan/favorite/FavoriteLibrary.java index 57c557f7f..ab21c081d 100644 --- a/src/com/edlplan/favorite/FavoriteLibrary.java +++ b/src/com/edlplan/favorite/FavoriteLibrary.java @@ -143,9 +143,7 @@ public void save() { object.put(entry.getKey(), array); } cover(object.toString(2), json); - } catch (IOException e) { - e.printStackTrace(); - } catch (JSONException e) { + } catch (IOException | JSONException e) { e.printStackTrace(); } } diff --git a/src/com/edlplan/framework/support/batch/BatchEngine.java b/src/com/edlplan/framework/support/batch/BatchEngine.java index e7710c95b..f7abf8681 100644 --- a/src/com/edlplan/framework/support/batch/BatchEngine.java +++ b/src/com/edlplan/framework/support/batch/BatchEngine.java @@ -9,7 +9,7 @@ public class BatchEngine { public static GL10 pGL; public static ShaderGlobals shaderGlobals = new ShaderGlobals(); - private static AbstractBatch savedbatch = null; + private static AbstractBatch savedbatch = null; private static boolean flushing = false; public static ShaderGlobals getShaderGlobals() { @@ -38,12 +38,12 @@ public static void setGlobalCamera(Camera camera) { shaderGlobals.camera.set(camera); } - static void bind(AbstractBatch batch) { + static void bind(AbstractBatch batch) { flush(); savedbatch = batch; } - static void unbind(AbstractBatch batch) { + static void unbind(AbstractBatch batch) { if (savedbatch == batch) { savedbatch = null; } @@ -58,7 +58,7 @@ public static void flush() { } } - public static AbstractBatch currentBatch() { + public static AbstractBatch currentBatch() { return savedbatch; } } diff --git a/src/com/edlplan/framework/support/batch/object/MultipleFlippableTextureQuad.java b/src/com/edlplan/framework/support/batch/object/MultipleFlippableTextureQuad.java index a43532b64..ab4349165 100644 --- a/src/com/edlplan/framework/support/batch/object/MultipleFlippableTextureQuad.java +++ b/src/com/edlplan/framework/support/batch/object/MultipleFlippableTextureQuad.java @@ -70,7 +70,7 @@ public void initialWithTextureListWithScale(List textures, float switchTexture(0); } - public class TextureEntry { + public static class TextureEntry { public Vec2 size = new Vec2(); diff --git a/src/com/edlplan/framework/support/graphics/BlendProperty.java b/src/com/edlplan/framework/support/graphics/BlendProperty.java index 918673454..6666ab7f9 100644 --- a/src/com/edlplan/framework/support/graphics/BlendProperty.java +++ b/src/com/edlplan/framework/support/graphics/BlendProperty.java @@ -6,7 +6,7 @@ import com.edlplan.framework.support.batch.BatchEngine; import com.edlplan.framework.utils.interfaces.Copyable; -public class BlendProperty implements Copyable { +public class BlendProperty implements Copyable { public boolean enable = true; @@ -61,7 +61,7 @@ public boolean equals(Object obj) { } @Override - public Copyable copy() { + public BlendProperty copy() { return new BlendProperty(this); } } diff --git a/src/com/edlplan/framework/support/graphics/CanvasData.java b/src/com/edlplan/framework/support/graphics/CanvasData.java index 0d743659a..cfd960aa5 100644 --- a/src/com/edlplan/framework/support/graphics/CanvasData.java +++ b/src/com/edlplan/framework/support/graphics/CanvasData.java @@ -5,7 +5,7 @@ import com.edlplan.framework.utils.interfaces.Copyable; import com.edlplan.framework.utils.interfaces.Recycleable; -public class CanvasData implements Recycleable, Copyable { +public class CanvasData implements Recycleable, Copyable { private float width; @@ -153,7 +153,7 @@ public void recycle() { } @Override - public Copyable copy() { + public CanvasData copy() { return new CanvasData(this); } } diff --git a/src/com/edlplan/framework/support/graphics/texture/TexturePool.java b/src/com/edlplan/framework/support/graphics/texture/TexturePool.java index 9229fdd3b..c199e359a 100644 --- a/src/com/edlplan/framework/support/graphics/texture/TexturePool.java +++ b/src/com/edlplan/framework/support/graphics/texture/TexturePool.java @@ -24,6 +24,7 @@ import java.io.File; import java.util.ArrayList; import java.util.Collections; +import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; @@ -102,7 +103,7 @@ public void packAll(Iterator collection, Consumer onPackDrawDone testAddRaw(t); } - Collections.sort(infos, (p1, p2) -> Integer.compare(p1.pageIndex, p2.pageIndex)); + Collections.sort(infos, (a, b) -> Integer.compare(a.pageIndex, b.pageIndex)); ListIterator iterator = infos.listIterator(); diff --git a/src/com/edlplan/framework/support/osb/EGFStoryboardSprite.java b/src/com/edlplan/framework/support/osb/EGFStoryboardSprite.java index 06ed43d9b..7843c55ea 100644 --- a/src/com/edlplan/framework/support/osb/EGFStoryboardSprite.java +++ b/src/com/edlplan/framework/support/osb/EGFStoryboardSprite.java @@ -1,5 +1,6 @@ package com.edlplan.framework.support.osb; +import com.edlplan.edlosbsupport.command.SpriteCommand; import com.edlplan.edlosbsupport.command.Target; import com.edlplan.edlosbsupport.player.CommandBooleanHandleTimeline; import com.edlplan.edlosbsupport.player.CommandColor4HandleTimeline; diff --git a/src/com/edlplan/framework/support/osb/StoryboardSprite.java b/src/com/edlplan/framework/support/osb/StoryboardSprite.java index d72e9e9c0..3926691b0 100644 --- a/src/com/edlplan/framework/support/osb/StoryboardSprite.java +++ b/src/com/edlplan/framework/support/osb/StoryboardSprite.java @@ -196,9 +196,7 @@ private void loadFromCache() { } }); - Tracker.createTmpNode("LoadPlayer").wrap(() -> { - osbPlayer.loadStoryboard(storyboard); - }).then(System.out::println); + Tracker.createTmpNode("LoadPlayer").wrap(() -> osbPlayer.loadStoryboard(storyboard)).then(System.out::println); } public void loadStoryboard(String osuFile) { @@ -255,9 +253,7 @@ public void loadStoryboard(String osuFile) { } }); - Tracker.createTmpNode("LoadPlayer").wrap(() -> { - osbPlayer.loadStoryboard(storyboard); - }).then(System.out::println); + Tracker.createTmpNode("LoadPlayer").wrap(() -> osbPlayer.loadStoryboard(storyboard)).then(System.out::println); } diff --git a/src/com/edlplan/framework/support/timing/RunnableHandler.java b/src/com/edlplan/framework/support/timing/RunnableHandler.java index 83f606477..53523444a 100644 --- a/src/com/edlplan/framework/support/timing/RunnableHandler.java +++ b/src/com/edlplan/framework/support/timing/RunnableHandler.java @@ -12,7 +12,7 @@ public class RunnableHandler extends Loopable implements IRunnableHandler { private Loopable.Flag flag = Loopable.Flag.Run; public RunnableHandler() { - bufferedRunnables = new SafeList(); + bufferedRunnables = new SafeList<>(); } @Override @@ -69,7 +69,7 @@ public Loopable.Flag getFlag() { return flag; } - private class DelayedRunnable { + private static class DelayedRunnable { public Runnable r; public double delay; diff --git a/src/com/edlplan/framework/support/util/Tracker.java b/src/com/edlplan/framework/support/util/Tracker.java index d6ae4751d..43faaff48 100644 --- a/src/com/edlplan/framework/support/util/Tracker.java +++ b/src/com/edlplan/framework/support/util/Tracker.java @@ -1,5 +1,7 @@ package com.edlplan.framework.support.util; +import androidx.annotation.NonNull; + import com.edlplan.framework.support.Framework; import com.edlplan.framework.utils.advance.ConsumerContainer; import com.edlplan.framework.utils.interfaces.Consumer; @@ -28,8 +30,8 @@ public class Tracker { static { - nodes = new ArrayList(); - namemap = new HashMap(); + nodes = new ArrayList<>(); + namemap = new HashMap<>(); DrawArray = register(DRAW_ARRAY); PrepareVertexData = register(PREPARE_VERTEX_DATA); @@ -63,7 +65,7 @@ public static void printlnAsTime(int ms) { } public static Consumer printByTag(String tag) { - return t -> System.out.println(String.format("[%s] %dms", tag, t)); + return t -> System.out.printf("[%s] %dms%n", tag, t); } public static class TrackNode { @@ -121,16 +123,15 @@ public ConsumerContainer wrap(Runnable runnable) { return new ConsumerContainer<>(this); } + @NonNull @Override public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("------------------------------------\n"); - sb.append("name : " + name + " (" + id + ")\n"); - sb.append("totalTime : " + totalTimeMS + "ms\n"); - sb.append("trackedTimes : " + trackedTimes + "\n"); - sb.append("------------------------------------"); - return sb.toString(); + return "------------------------------------\n" + + "name : " + name + " (" + id + ")\n" + + "totalTime : " + totalTimeMS + "ms\n" + + "trackedTimes : " + trackedTimes + "\n" + + "------------------------------------"; } } } \ No newline at end of file diff --git a/src/com/edlplan/osu/support/object/StdSliderPathMaker.java b/src/com/edlplan/osu/support/object/StdSliderPathMaker.java index 393fa7c8d..d76d0b08e 100644 --- a/src/com/edlplan/osu/support/object/StdSliderPathMaker.java +++ b/src/com/edlplan/osu/support/object/StdSliderPathMaker.java @@ -44,7 +44,7 @@ public List calculateSubPath(List subPoints) { public LinePath calculatePath() { path.clear(); - List subControlPoints = new ArrayList(); + List subControlPoints = new ArrayList<>(); for (int i = 0; i < getControlPoint().size(); i++) { subControlPoints.add(getControlPoint().get(i)); if (i == getControlPoint().size() - 1 || getControlPoint().get(i).equals(getControlPoint().get(i + 1))) { diff --git a/src/com/edlplan/osu/support/slider/DrawLinePath.java b/src/com/edlplan/osu/support/slider/DrawLinePath.java index 22b3d4159..e777ef59a 100644 --- a/src/com/edlplan/osu/support/slider/DrawLinePath.java +++ b/src/com/edlplan/osu/support/slider/DrawLinePath.java @@ -32,7 +32,6 @@ public DrawLinePath(AbstractPath p, float width) { public DrawLinePath() { alpha = 1; - this.width = width; } public DrawLinePath reset(AbstractPath p, float width) { diff --git a/src/com/edlplan/osu/support/slider/SliderBody2D.java b/src/com/edlplan/osu/support/slider/SliderBody2D.java index 4c3b07a5e..e1439ed6e 100644 --- a/src/com/edlplan/osu/support/slider/SliderBody2D.java +++ b/src/com/edlplan/osu/support/slider/SliderBody2D.java @@ -17,7 +17,7 @@ public class SliderBody2D extends AbstractSliderBody { - private static final ThreadLocal localCache = new ThreadLocal() { + private static final ThreadLocal localCache = new ThreadLocal<>() { @Override public BuildCache get() { BuildCache cache = super.get(); diff --git a/src/com/edlplan/osu/support/timing/TimingPoint.java b/src/com/edlplan/osu/support/timing/TimingPoint.java index 93846d847..8d6c80d1d 100644 --- a/src/com/edlplan/osu/support/timing/TimingPoint.java +++ b/src/com/edlplan/osu/support/timing/TimingPoint.java @@ -106,14 +106,13 @@ public void setKiaiMode(boolean kiaiMode) { @Override public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append(getTime()).append(","); - sb.append(getBeatLength()).append(","); - sb.append(getMeter()).append(","); - sb.append(getSampleType()).append(","); - sb.append(getSampleSet()).append(","); - sb.append(U.toVString(isInherited())).append(","); - sb.append(((isKiaiMode()) ? 1 : 0) + ((isOmitFirstBarSignature()) ? 8 : 0)); - return sb.toString(); + String sb = getTime() + "," + + getBeatLength() + "," + + getMeter() + "," + + getSampleType() + "," + + getSampleSet() + "," + + U.toVString(isInherited()) + "," + + (((isKiaiMode()) ? 1 : 0) + ((isOmitFirstBarSignature()) ? 8 : 0)); + return sb; } } diff --git a/src/com/edlplan/osu/support/timing/controlpoint/ControlPoints.java b/src/com/edlplan/osu/support/timing/controlpoint/ControlPoints.java index b2febcfb7..419fb3bca 100644 --- a/src/com/edlplan/osu/support/timing/controlpoint/ControlPoints.java +++ b/src/com/edlplan/osu/support/timing/controlpoint/ControlPoints.java @@ -5,7 +5,9 @@ import java.util.ArrayList; import java.util.Collections; +import java.util.Comparator; import java.util.List; +import java.util.Objects; public class ControlPoints { private final ArrayList timingPoints = new ArrayList<>(); @@ -171,9 +173,9 @@ public DifficultyControlPoint getDifficultyPointAt(double time) { DifficultyControlPoint difficultyControlPoint = binarySearch(difficultyPoints, time, defaultDifficultyPoint); if (difficultyControlPoint == null) { return defaultDifficultyPoint; - } else { - return difficultyControlPoint; } + + return difficultyControlPoint; } private T binarySearch(List list, double time, T prePoint) { diff --git a/src/com/edlplan/replay/OsuDroidReplayPack.java b/src/com/edlplan/replay/OsuDroidReplayPack.java index 8e1848cd2..6e919740b 100644 --- a/src/com/edlplan/replay/OsuDroidReplayPack.java +++ b/src/com/edlplan/replay/OsuDroidReplayPack.java @@ -27,31 +27,32 @@ public static void packTo(File file, OsuDroidReplay replay) throws Exception { } public static byte[] pack(OsuDroidReplay replay) throws Exception { - ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - ZipOutputStream outputStream = new ZipOutputStream(byteArrayOutputStream); - //try { - outputStream.putNextEntry(new ZipEntry("entry.json")); + try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + ZipOutputStream outputStream = new ZipOutputStream(byteArrayOutputStream)){ + outputStream.putNextEntry(new ZipEntry("entry.json")); - JSONObject entryJson = new JSONObject(); - entryJson.put("version", 1); - entryJson.put("replaydata", replay.toJSON()); + JSONObject entryJson = new JSONObject(); + entryJson.put("version", 1); + entryJson.put("replaydata", replay.toJSON()); - outputStream.write(entryJson.toString(2).getBytes()); + outputStream.write(entryJson.toString(2).getBytes()); - outputStream.putNextEntry(new ZipEntry(replay.getReplayFileName())); + outputStream.putNextEntry(new ZipEntry(replay.getReplayFileName())); - File file = replay.isAbsoluteReplay() ? - new File(replay.getReplayFile()) : new File(OdrConfig.getScoreDir(), replay.getReplayFileName()); - FileInputStream inputStream = new FileInputStream(file); + File file = replay.isAbsoluteReplay() ? + new File(replay.getReplayFile()) : new File(OdrConfig.getScoreDir(), replay.getReplayFileName()); - byte[] buffer = new byte[1024]; - int l; - while ((l = inputStream.read(buffer)) != -1) { - outputStream.write(buffer, 0, l); - } + try (FileInputStream inputStream = new FileInputStream(file)) { + byte[] buffer = new byte[1024]; + int l; + while ((l = inputStream.read(buffer)) != -1) { + outputStream.write(buffer, 0, l); + } + } - outputStream.finish(); - return byteArrayOutputStream.toByteArray(); + outputStream.finish(); + return byteArrayOutputStream.toByteArray(); + } } public static ReplayEntry unpack(InputStream raw) throws IOException, JSONException { diff --git a/src/com/edlplan/replay/SongsLibrary.java b/src/com/edlplan/replay/SongsLibrary.java index 221f59fd2..fd6c4a8a3 100644 --- a/src/com/edlplan/replay/SongsLibrary.java +++ b/src/com/edlplan/replay/SongsLibrary.java @@ -30,7 +30,7 @@ public static SongsLibrary get() { } public String toSetLocal(String raw) { - String osu = raw.substring(raw.indexOf("/") + 1, raw.length()); + String osu = raw.substring(raw.indexOf("/") + 1); if (osu2set.containsKey(osu)) { return osu2set.get(osu); } else { diff --git a/src/com/edlplan/ui/ActivityOverlay.kt b/src/com/edlplan/ui/ActivityOverlay.kt index f1c2960fd..9d00347d2 100644 --- a/src/com/edlplan/ui/ActivityOverlay.kt +++ b/src/com/edlplan/ui/ActivityOverlay.kt @@ -9,24 +9,22 @@ import java.util.* object ActivityOverlay { private var fragmentManager: FragmentManager? = null - private val displayingOverlay: MutableList = ArrayList() + private val displayingOverlay = mutableListOf() private var context: Activity? = null private var containerId = 0 + private val stateMap = mutableMapOf() @JvmStatic fun initial(activity: AppCompatActivity, id: Int) { context = activity containerId = id fragmentManager = activity.supportFragmentManager - if (fragmentManager == null) { - throw RuntimeException("FragmentManager not found!") - } } @JvmStatic @Synchronized fun onBackPress(): Boolean { if (fragmentManager != null && displayingOverlay.size > 0) { - val overlay: Fragment? = displayingOverlay[displayingOverlay.size - 1] + val overlay: Fragment = displayingOverlay[displayingOverlay.size - 1] if(overlay is BackPressListener) { overlay.callDismissOnBackPress() } @@ -48,7 +46,7 @@ object ActivityOverlay { @Synchronized fun addOverlay(fragment: Fragment, tag: String?) { if (fragmentManager != null) { - if (fragment.isAdded()) { + if (fragment.isAdded) { return } if (displayingOverlay.contains(fragment) || fragmentManager!!.findFragmentByTag(tag) != null) { @@ -66,6 +64,24 @@ object ActivityOverlay { } } + @Synchronized + fun saveState(tag: String?) { + val fragment = fragmentManager!!.findFragmentByTag(tag) + if (fragmentManager != null && fragment?.isAdded == true) { + stateMap[tag!!] = fragmentManager!!.saveFragmentInstanceState(fragment) + } + } + + @Synchronized + fun loadState(tag: String?): Fragment.SavedState? { + val fragment = fragmentManager!!.findFragmentByTag(tag) + if (fragmentManager != null && fragment?.isAdded == true) { + return stateMap.remove(tag!!) + } + + return null + } + fun runOnUiThread(runnable: Runnable?) { context!!.runOnUiThread(runnable) } diff --git a/src/com/edlplan/ui/SkinPathPreference.java b/src/com/edlplan/ui/SkinPathPreference.java index 9bc4a7666..ecb8a39c7 100644 --- a/src/com/edlplan/ui/SkinPathPreference.java +++ b/src/com/edlplan/ui/SkinPathPreference.java @@ -35,7 +35,7 @@ public SkinPathPreference(Context context) { public void reloadSkinList() { try { File skinMain = new File(Config.getSkinTopPath()); - Map skins = new HashMap(Config.getSkins()); + Map skins = new HashMap<>(Config.getSkins()); int skinsSize = (skins.size() > 0) ? skins.size() + 1 : 1; Debug.i("Skins count:" + skinsSize); CharSequence[] entries = new CharSequence[skinsSize]; diff --git a/src/com/edlplan/ui/fragment/BaseFragment.kt b/src/com/edlplan/ui/fragment/BaseFragment.kt index fc1ccd0fb..553ed1638 100644 --- a/src/com/edlplan/ui/fragment/BaseFragment.kt +++ b/src/com/edlplan/ui/fragment/BaseFragment.kt @@ -73,6 +73,14 @@ abstract class BaseFragment : Fragment(), BackPressListener { onDismissListener?.OnDismiss() } + fun save() { + ActivityOverlay.saveState(this.javaClass.name + "@" + this.hashCode()) + } + + fun load(): SavedState? { + return ActivityOverlay.loadState(this.javaClass.name + "@" + this.hashCode()) + } + override fun callDismissOnBackPress() { if (isDismissOnBackPress) { dismiss() diff --git a/src/com/edlplan/ui/fragment/FavoriteManagerFragment.java b/src/com/edlplan/ui/fragment/FavoriteManagerFragment.java index 55fb25fda..e182ee90b 100644 --- a/src/com/edlplan/ui/fragment/FavoriteManagerFragment.java +++ b/src/com/edlplan/ui/fragment/FavoriteManagerFragment.java @@ -104,7 +104,7 @@ public String getSelected() { return selected; } - public void showToSelectFloder(OnSelectListener onSelectListener) { + public void showToSelectFolder(OnSelectListener onSelectListener) { onLoadViewFunc = () -> { adapter = new SelectAdapter(onSelectListener); ((RecyclerView) findViewById(R.id.main_recycler_view)).setAdapter(adapter); @@ -112,7 +112,7 @@ public void showToSelectFloder(OnSelectListener onSelectListener) { show(); } - public void showToAddToFloder(String track) { + public void showToAddToFolder(String track) { onLoadViewFunc = () -> { adapter = new AddAdapter(track); ((RecyclerView) findViewById(R.id.main_recycler_view)).setAdapter(adapter); @@ -143,7 +143,7 @@ public VH(View itemView) { } } - public abstract class FMAdapter extends RecyclerView.Adapter { + public abstract static class FMAdapter extends RecyclerView.Adapter { protected List folders; @@ -194,7 +194,7 @@ public AddAdapter(String track) { public void onBindViewHolder(@NonNull VH holder, int position) { final String f = folders.get(position); holder.folderName.setText(String.format("%s (%s)", - f, FavoriteLibrary.get().getMaps(f) == null ? "*" : ("" + FavoriteLibrary.get().getMaps(f).size()))); + f, FavoriteLibrary.get().getMaps(f) == null ? "*" : (String.valueOf(FavoriteLibrary.get().getMaps(f).size())))); holder.button1.setText(R.string.favorite_delete); if (position == 0) { holder.button2.setText("( • ̀ω•́ )✧"); @@ -233,20 +233,18 @@ public void onClick(View v) { if (FavoriteLibrary.get().inFolder(f, track)) { FavoriteLibrary.get().remove(f, track); holder.folderName.setText(String.format("%s (%s)", - f, FavoriteLibrary.get().getMaps(f) == null ? "*" : ("" + FavoriteLibrary.get().getMaps(f).size()))); + f, FavoriteLibrary.get().getMaps(f) == null ? "*" : (String.valueOf(FavoriteLibrary.get().getMaps(f).size())))); holder.button2.setText(R.string.favorite_add); } else { FavoriteLibrary.get().add(f, track); holder.folderName.setText(String.format("%s (%s)", - f, FavoriteLibrary.get().getMaps(f) == null ? "*" : ("" + FavoriteLibrary.get().getMaps(f).size()))); + f, FavoriteLibrary.get().getMaps(f) == null ? "*" : (String.valueOf(FavoriteLibrary.get().getMaps(f).size())))); holder.button2.setText(R.string.favorite_remove); } }); if (position == 0) { - holder.button1.setOnClickListener(view -> { - ToastLogger.showText(StringTable.get(R.string.favorite_warning_on_delete_default), false); - }); + holder.button1.setOnClickListener(view -> ToastLogger.showText(StringTable.get(R.string.favorite_warning_on_delete_default), false)); holder.button2.setOnClickListener(view -> { }); } @@ -265,7 +263,7 @@ public SelectAdapter(OnSelectListener onSelectListener) { public void onBindViewHolder(@NonNull VH holder, int position) { final String f = folders.get(position); holder.folderName.setText(String.format("%s (%s)", - f, FavoriteLibrary.get().getMaps(f) == null ? "*" : ("" + FavoriteLibrary.get().getMaps(f).size()))); + f, FavoriteLibrary.get().getMaps(f) == null ? "*" : (String.valueOf(FavoriteLibrary.get().getMaps(f).size())))); holder.button1.setText(R.string.favorite_delete); holder.button2.setText(R.string.favorite_select); @@ -315,9 +313,7 @@ public void onClick(View v) { }); if (position == 0) { - holder.button1.setOnClickListener(view -> { - ToastLogger.showText(StringTable.get(R.string.favorite_warning_on_delete_default), false); - }); + holder.button1.setOnClickListener(view -> ToastLogger.showText(StringTable.get(R.string.favorite_warning_on_delete_default), false)); } } } diff --git a/src/com/edlplan/ui/fragment/FilterMenuFragment.java b/src/com/edlplan/ui/fragment/FilterMenuFragment.java deleted file mode 100644 index d120e7a85..000000000 --- a/src/com/edlplan/ui/fragment/FilterMenuFragment.java +++ /dev/null @@ -1,329 +0,0 @@ -package com.edlplan.ui.fragment; - -import android.animation.Animator; -import android.annotation.SuppressLint; -import android.content.Context; -import android.content.SharedPreferences; -import androidx.preference.PreferenceManager; -import androidx.annotation.StringRes; -import android.text.Editable; -import android.text.TextWatcher; -import android.view.KeyEvent; -import android.view.View; -import android.widget.Button; -import android.widget.CheckBox; -import android.widget.EditText; -import android.widget.TextView; - -import com.edlplan.framework.easing.Easing; -import com.edlplan.framework.support.util.Updater; -import com.edlplan.ui.BaseAnimationListener; -import com.edlplan.ui.EasingHelper; - -import com.reco1l.framework.lang.Execution; -import org.anddev.andengine.entity.scene.Scene; - -import ru.nsu.ccfit.zuev.osu.helper.StringTable; -import ru.nsu.ccfit.zuev.osu.menu.IFilterMenu; -import ru.nsu.ccfit.zuev.osu.menu.SongMenu; -import ru.nsu.ccfit.zuev.osuplus.R; - -public class FilterMenuFragment extends BaseFragment implements IFilterMenu { - - private static Context configContext = null; - private static String savedFolder; - private static boolean savedFavOnly = false; - private static String savedFilter = null; - private Scene scene = null; - private EditText filter; - private SongMenu menu; - private CheckBox favoritesOnly; - private TextView favoriteFolder; - private Button orderButton; - //private TextView openMapInfo; - - private Updater updater; - - public FilterMenuFragment() { - setDismissOnBackgroundClick(true); - } - - - @Override - protected int getLayoutID() { - return R.layout.fragment_filtermenu; - } - - @Override - protected void onLoadView() { - reloadViewData(); - playOnLoadAnim(); - } - - private void playOnLoadAnim() { - View body = findViewById(R.id.frg_body); - body.setAlpha(0); - body.setTranslationX(400); - body.animate().cancel(); - body.animate() - .translationX(0) - .alpha(1) - .setInterpolator(EasingHelper.asInterpolator(Easing.InOutQuad)) - .setDuration(150) - .start(); - playBackgroundHideInAnim(150); - } - - private void playEndAnim(Runnable action) { - View body = findViewById(R.id.frg_body); - body.animate().cancel(); - body.animate() - .translationXBy(400) - .alpha(0) - .setDuration(200) - .setInterpolator(EasingHelper.asInterpolator(Easing.InOutQuad)) - .setListener(new BaseAnimationListener() { - @Override - public void onAnimationEnd(Animator animation) { - if (action != null) { - action.run(); - } - } - }) - .start(); - playBackgroundHideOutAnim(200); - } - - private void updateFavChecked() { - favoritesOnly.setText(favoritesOnly.isChecked() ? - R.string.menu_search_favsenabled : R.string.menu_search_favsdisabled); - } - - private void updateOrderButton() { - SongMenu.SortOrder order = getOrder(); - @StringRes int s; - switch (order) { - case Title: - s = R.string.menu_search_sort_title; - break; - case Artist: - s = R.string.menu_search_sort_artist; - break; - case Date: - s = R.string.menu_search_sort_date; - break; - case Bpm: - s = R.string.menu_search_sort_bpm; - break; - case Stars: - s = R.string.menu_search_sort_stars; - break; - case Length: - s = R.string.menu_search_sort_length; - break; - default: - s = R.string.menu_search_sort_creator; - break; - } - orderButton.setText(s); - } - - private void updateFavFolderText() { - if (savedFolder != null) { - favoriteFolder.setText(savedFolder); - } - if (favoriteFolder.getText().length() == 0) { - favoriteFolder.setText(StringTable.get(R.string.favorite_default)); - } - } - - @Override - public void dismiss() { - playEndAnim(super::dismiss); - } - - @Override - public String getFilter() { - return filter == null ? "" : (filter.getText() == null ? "" : filter.getText().toString()); - } - - @Override - public SongMenu.SortOrder getOrder() { - final SharedPreferences prefs = PreferenceManager - .getDefaultSharedPreferences(configContext); - final int sortOrder = prefs.getInt("sortorder", 0); - return SongMenu.SortOrder.values()[sortOrder % SongMenu.SortOrder.values().length]; - } - - @SuppressLint("ApplySharedPref") - private void saveOrder(SongMenu.SortOrder order) { - PreferenceManager - .getDefaultSharedPreferences(configContext) - .edit() - .putInt("sortorder", order.ordinal()) - .commit(); - } - - private void nextOrder() { - SongMenu.SortOrder order = getOrder(); - order = SongMenu.SortOrder.values()[(order.ordinal() + 1) % SongMenu.SortOrder.values().length]; - saveOrder(order); - } - - @Override - public boolean isFavoritesOnly() { - return favoritesOnly.isChecked(); - } - - @Override - public String getFavoriteFolder() { - return favoriteFolder == null ? - null : StringTable.get(R.string.favorite_default).equals(favoriteFolder.getText().toString()) ? - null : favoriteFolder.getText().toString(); - } - - @Override - public void loadConfig(Context context) { - configContext = context; - Execution.uiThread(this::reloadViewData); - } - - @Override - public Scene getScene() { - return scene; - } - - @Override - public void hideMenu() { - updateUpdater(); - scene = null; - dismiss(); - } - - @Override - public void showMenu(SongMenu parent) { - this.menu = parent; - scene = new Scene(); - scene.setBackgroundEnabled(false); - if (parent != null) { - //parent.scene.setChildScene( - // scene, false, - // true, true); - } - updater = new Updater() { - @Override - public Runnable createEventRunnable() { - return () -> parent.loadFilter(FilterMenuFragment.this); - } - - @Override - public void postEvent(Runnable r) { - parent.getScene().postRunnable(r); - } - }; - show(); - } - - @Override - public void onDetach() { - super.onDetach(); - if (menu != null) { - final SongMenu menu = this.menu; - menu.getScene().postRunnable(() -> { - //menu.getScene().clearChildScene(); - menu.loadFilter(this); - }); - this.menu = null; - } - scene = null; - } - - @Override - public void onAttach(Context context) { - super.onAttach(context); - reloadViewData(); - } - - private void updateUpdater() { - if (updater != null) { - updater.update(); - } - } - - //private void openMapinfoDialog() { - // MapInfoFragment dialog = new MapInfoFragment(); - // TrackInfo selectedTrack = GlobalManager.getInstance().getSongMenu().getSelectedTrack(); - // DifficultyReCalculator diffReCalculator = new DifficultyReCalculator(); - // if (selectedTrack != null) - // dialog.showWithMap(selectedTrack, ModMenu.getInstance().getSpeed(), diffReCalculator.getCS(selectedTrack)); - // diffReCalculator = null; - //} - - public void reloadViewData() { - if (isCreated()) { - filter = findViewById(R.id.searchEditText); - favoritesOnly = findViewById(R.id.showFav); - orderButton = findViewById(R.id.sortButton); - favoriteFolder = findViewById(R.id.favFolder); - //openMapInfo = findViewById(R.id.openMapInfo); - - favoritesOnly.setOnCheckedChangeListener((buttonView, isChecked) -> { - updateFavChecked(); - updateUpdater(); - savedFavOnly = isChecked; - }); - orderButton.setOnClickListener(v -> { - nextOrder(); - updateOrderButton(); - updateUpdater(); - }); - findViewById(R.id.favFolderLayout).setOnClickListener(v -> { - FavoriteManagerFragment favoriteManagerFragment = new FavoriteManagerFragment(); - favoriteManagerFragment.showToSelectFloder(t -> { - savedFolder = t; - favoriteFolder.setText(t == null ? StringTable.get(R.string.favorite_default) : t); - updateUpdater(); - }); - }); - filter.setOnEditorActionListener((v, actionId, event) -> { - if (event == null) { - return false; - } - - if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER) { - hideMenu(); - return true; - } - return false; - }); - filter.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) { - savedFilter = s.toString(); - updateUpdater(); - } - }); - - //openMapInfo.setOnClickListener(v -> { - // openMapinfoDialog(); - //}); - //openMapInfo.setText("MapInfo"); - - favoritesOnly.setChecked(savedFavOnly); - if (savedFilter != null && savedFilter.length() > 0) { - filter.setText(savedFilter); - } - updateOrderButton(); - updateFavChecked(); - updateFavFolderText(); - } - } -} diff --git a/src/com/edlplan/ui/fragment/FilterMenuFragment.kt b/src/com/edlplan/ui/fragment/FilterMenuFragment.kt new file mode 100644 index 000000000..04317f14d --- /dev/null +++ b/src/com/edlplan/ui/fragment/FilterMenuFragment.kt @@ -0,0 +1,296 @@ +package com.edlplan.ui.fragment + +import android.animation.Animator +import android.content.Context +import android.os.Bundle +import android.text.Editable +import android.text.TextWatcher +import android.view.KeyEvent +import android.view.View +import android.widget.Button +import android.widget.CheckBox +import android.widget.EditText +import android.widget.TextView +import androidx.preference.PreferenceManager +import com.edlplan.framework.easing.Easing +import com.edlplan.framework.support.util.Updater +import com.edlplan.ui.BaseAnimationListener +import com.edlplan.ui.EasingHelper +import com.reco1l.framework.lang.uiThread +import org.anddev.andengine.engine.handler.IUpdateHandler +import org.anddev.andengine.entity.scene.Scene +import ru.nsu.ccfit.zuev.osu.helper.InputManager +import ru.nsu.ccfit.zuev.osu.helper.StringTable +import ru.nsu.ccfit.zuev.osu.menu.IFilterMenu +import ru.nsu.ccfit.zuev.osu.menu.SongMenu +import ru.nsu.ccfit.zuev.osu.GlobalManager.getInstance as getGlobal +import ru.nsu.ccfit.zuev.osuplus.R + +class FilterMenuFragment : BaseFragment(), IUpdateHandler, IFilterMenu { + private var configContext: Context? = null + private var savedFolder: String? = null + private var savedFavOnly = false + private var savedFilter: String? = null + private var scene: Scene? = null + private lateinit var filter: EditText + private var menu: SongMenu? = null + private lateinit var favoritesOnly: CheckBox + private lateinit var favoriteFolder: TextView + private lateinit var sortButton: Button + private var updater: Updater? = null + + init { + isDismissOnBackgroundClick = true + } + + override val layoutID: Int + get() = R.layout.fragment_filtermenu + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + val (folder, favOnly, filter) = restoreState() + savedFolder = folder + savedFavOnly = favOnly + savedFilter = filter + } + + override fun onLoadView() { + reloadViewData() + playOnLoadAnim() + } + + override fun getFilter(): String { + return filter.text.toString() + } + + override fun getOrder(): SongMenu.SortOrder { + val prefs = + PreferenceManager.getDefaultSharedPreferences(configContext) + val order = prefs.getInt("sortorder", 0) + return SongMenu.SortOrder.values()[order % SongMenu.SortOrder.values().size] + } + + override fun isFavoritesOnly(): Boolean = favoritesOnly.isChecked + + override fun getFavoriteFolder(): String = + if (StringTable.get(R.string.favorite_default) == favoriteFolder.text) "" else favoriteFolder.text.toString() + + override fun loadConfig(context: Context?) { + configContext = context + uiThread(this::reloadViewData) + } + + override fun getScene(): Scene = scene!! + + override fun hideMenu() { + updateUpdater() + scene = null + dismiss() + } + + override fun showMenu(parent: SongMenu?) { + this.menu = parent!! + scene = Scene() + scene!!.isBackgroundEnabled = false + updater = object : Updater() { + override fun createEventRunnable(): Runnable = + Runnable { parent.loadFilter(this@FilterMenuFragment) } + + override fun postEvent(r: Runnable?) = parent.scene.postRunnable(r) + } + show() + } + + override fun onDetach() { + super.onDetach() + menu?.scene?.postRunnable { menu?.loadFilter(this) } + menu = null + scene = null + } + + override fun onAttach(context: Context) { + super.onAttach(context) + reloadViewData() + } + + override fun dismiss() { + playEndAnim { super.dismiss() } + getGlobal().songMenu.unloadFilterFragment() + saveState(savedFolder, savedFavOnly, savedFilter) + } + + private fun reloadViewData() { + if (isCreated) { + filter = findViewById(R.id.searchEditText)!! + favoritesOnly = findViewById(R.id.showFav)!! + sortButton = findViewById(R.id.sortButton)!! + favoriteFolder = findViewById(R.id.favFolder)!! + + favoritesOnly.setOnCheckedChangeListener { _, isChecked -> + updateFavChecked() + updateUpdater() + savedFavOnly = isChecked + } + + sortButton.setOnClickListener { + nextOrder() + updateOrderButton() + updateUpdater() + } + + findViewById(R.id.favFolderLayout)!!.setOnClickListener { + val favoriteManagerFragment = FavoriteManagerFragment() + favoriteManagerFragment.showToSelectFolder { + savedFolder = it + favoriteFolder.text = it ?: StringTable.get(R.string.favorite_default) + updateUpdater() + } + } + + filter.setOnEditorActionListener { _, _, event -> + if (event != null && event.keyCode == KeyEvent.KEYCODE_ENTER) { + hideMenu() + return@setOnEditorActionListener true + } + false + } + + filter.addTextChangedListener( + object : TextWatcher { + override fun beforeTextChanged( + s: CharSequence, + start: Int, + count: Int, + after: Int + ) { + } + + override fun onTextChanged( + s: CharSequence, + start: Int, + before: Int, + count: Int + ) { + } + + override fun afterTextChanged(s: Editable) { + savedFilter = s.toString() + updateUpdater() + } + } + ) + + favoritesOnly.isChecked = savedFavOnly + + if (savedFilter?.isNotEmpty() == true) { + filter.setText(savedFilter) + } + + updateOrderButton() + updateFavChecked() + updateFavFolderText() + } + } + + private fun playOnLoadAnim() { + val body = findViewById(R.id.frg_body)!! + body.alpha = 0f + body.translationX = 400f + body.animate().cancel() + body.animate() + .alpha(1f) + .translationX(0f) + .setInterpolator(EasingHelper.asInterpolator(Easing.InOutQuad)) + .setDuration(300) + .start() + playBackgroundHideInAnim(150) + } + + private fun playEndAnim(action: () -> Unit) { + val body = findViewById(R.id.frg_body)!! + body.animate().cancel() + body.animate() + .alpha(0f) + .translationX(400f) + .setInterpolator(EasingHelper.asInterpolator(Easing.InOutQuad)) + .setDuration(300) + .setListener( + object : BaseAnimationListener() { + override fun onAnimationEnd(animation: Animator) { + action() + } + } + ) + .start() + playBackgroundHideOutAnim(150) + } + + private fun updateFavChecked() { + favoritesOnly.text = + if (favoritesOnly.isChecked) getString(R.string.menu_search_favsenabled) else getString( + R.string.menu_search_favsdisabled + ) + } + + private fun updateOrderButton() { + val s = when (order) { + SongMenu.SortOrder.Title -> StringTable.get(R.string.menu_search_sort_title) + SongMenu.SortOrder.Artist -> StringTable.get(R.string.menu_search_sort_artist) + SongMenu.SortOrder.Creator -> StringTable.get(R.string.menu_search_sort_creator) + SongMenu.SortOrder.Date -> StringTable.get(R.string.menu_search_sort_date) + SongMenu.SortOrder.Bpm -> StringTable.get(R.string.menu_search_sort_bpm) + SongMenu.SortOrder.Stars -> StringTable.get(R.string.menu_search_sort_stars) + SongMenu.SortOrder.Length -> StringTable.get(R.string.menu_search_sort_length) + } + + sortButton.text = s + } + + private fun updateFavFolderText() { + favoriteFolder.text = + savedFolder.orEmpty().ifEmpty { StringTable.get(R.string.favorite_default) } + } + + private fun nextOrder() { + var order = order + order = SongMenu.SortOrder.values()[(order.ordinal + 1) % SongMenu.SortOrder.values().size] + saveOrder(order) + } + + private fun saveOrder(order: SongMenu.SortOrder) { + PreferenceManager + .getDefaultSharedPreferences(configContext) + .edit() + .putInt("sortorder", order.ordinal) + .commit() + } + + private fun updateUpdater() { + updater?.update() + } + + override fun onUpdate(pSecondsElapsed: Float) { + if (InputManager.getInstance().isChanged) { + filter.setText(InputManager.getInstance().text) + } + } + + override fun reset() { + TODO("Not yet implemented") + } + + // Due to how the fragment lifecycle works in this context, the state needs to be saved manually + private companion object { + var folder: String? = null + var favOnly = false + var filter: String? = null + + fun saveState(savedFolder: String?, savedFavOnly: Boolean, savedFilter: String?) { + folder = savedFolder + favOnly = savedFavOnly + filter = savedFilter + } + + fun restoreState() = Triple(folder, favOnly, filter) + } +} \ No newline at end of file diff --git a/src/com/edlplan/ui/fragment/InGameSettingMenu.java b/src/com/edlplan/ui/fragment/InGameSettingMenu.java deleted file mode 100644 index bbf10e5b4..000000000 --- a/src/com/edlplan/ui/fragment/InGameSettingMenu.java +++ /dev/null @@ -1,556 +0,0 @@ -package com.edlplan.ui.fragment; - -import android.animation.Animator; -import android.annotation.SuppressLint; -import android.graphics.Color; -import android.view.View; -import android.widget.CheckBox; -import android.widget.RelativeLayout; -import android.widget.SeekBar; -import android.widget.SeekBar.OnSeekBarChangeListener; -import android.widget.TextView; - -import androidx.preference.PreferenceManager; - -import com.edlplan.framework.easing.Easing; -import com.edlplan.framework.math.FMath; -import com.edlplan.ui.BaseAnimationListener; -import com.edlplan.ui.EasingHelper; - -import java.util.Locale; - -import com.reco1l.legacy.Multiplayer; -import org.anddev.andengine.input.touch.TouchEvent; - -import ru.nsu.ccfit.zuev.osu.Config; -import ru.nsu.ccfit.zuev.osu.GlobalManager; -import ru.nsu.ccfit.zuev.osu.game.cursor.flashlight.FlashLightEntity; -import ru.nsu.ccfit.zuev.osu.game.mods.GameMod; -import ru.nsu.ccfit.zuev.osu.menu.ModMenu; -import ru.nsu.ccfit.zuev.osuplus.R; - -public class InGameSettingMenu extends BaseFragment { - - private static InGameSettingMenu menu; - - private View speedModifyRow; - private SeekBar speedModifyBar; - private TextView speedModifyText; - private CheckBox speedModifyToggle; - - private View followDelayRow; - private SeekBar followDelayBar; - private TextView followDelayText; - - private View forceDifficultyStatisticsSplitter; - - private RelativeLayout customARLayout; - private CheckBox customARToggle; - private TextView customARText; - private SeekBar customARBar; - - private RelativeLayout customODLayout; - private CheckBox customODToggle; - private TextView customODText; - private SeekBar customODBar; - - private RelativeLayout customCSLayout; - private CheckBox customCSToggle; - private TextView customCSText; - private SeekBar customCSBar; - - private RelativeLayout customHPLayout; - private CheckBox customHPToggle; - private TextView customHPText; - private SeekBar customHPBar; - - - private final int greenColor = Color.parseColor("#62c700"); - - public static InGameSettingMenu getInstance() { - if (menu == null) { - menu = new InGameSettingMenu(); - } - return menu; - } - - @Override - protected int getLayoutID() { - return R.layout.fragment_in_game_option; - } - - @Override - protected void onLoadView() { - reload(); - findViewById(R.id.frg_header).animate().cancel(); - findViewById(R.id.frg_header).setAlpha(0); - findViewById(R.id.frg_header).setTranslationY(100); - findViewById(R.id.frg_header).animate() - .alpha(1) - .translationY(0) - .setDuration(200) - .setInterpolator(EasingHelper.asInterpolator(Easing.InOutQuad)) - .start(); - } - - @SuppressLint({"ClickableViewAccessibility", "ApplySharedPref"}) - private void reload() { - View showMoreButton = findViewById(R.id.showMoreButton); - if (showMoreButton == null) { - return; - } - showMoreButton.setOnTouchListener((v, event) -> { - if (event.getAction() == TouchEvent.ACTION_DOWN) { - v.animate().cancel(); - v.animate().scaleY(0.9f).scaleX(0.9f).translationY(v.getHeight() * 0.1f).setDuration(100).start(); - toggleSettingPanel(); - return true; - } else if (event.getAction() == TouchEvent.ACTION_UP) { - v.animate().cancel(); - v.animate().scaleY(1).scaleX(1).setDuration(100).translationY(0).start(); - return true; - } - return false; - }); - - speedModifyRow = findViewById(R.id.speed_modify); - followDelayRow = findViewById(R.id.follow_delay_row); - - forceDifficultyStatisticsSplitter = findViewById(R.id.force_diffstat_split_view); - - customARLayout = findViewById(R.id.custom_ar_layout); - customARBar = findViewById(R.id.custom_ar_bar); - customARText = findViewById(R.id.custom_ar_text); - customARToggle = findViewById(R.id.custom_ar_toggle); - - customODLayout = findViewById(R.id.custom_od_layout); - customODBar = findViewById(R.id.custom_od_bar); - customODText = findViewById(R.id.custom_od_text); - customODToggle = findViewById(R.id.custom_od_toggle); - - customCSLayout = findViewById(R.id.custom_cs_layout); - customCSBar = findViewById(R.id.custom_cs_bar); - customCSText = findViewById(R.id.custom_cs_text); - customCSToggle = findViewById(R.id.custom_cs_toggle); - - customHPLayout = findViewById(R.id.custom_hp_layout); - customHPBar = findViewById(R.id.custom_hp_bar); - customHPText = findViewById(R.id.custom_hp_text); - customHPToggle = findViewById(R.id.custom_hp_toggle); - - findViewById(R.id.frg_background).setClickable(false); - - CheckBox enableStoryboard = findViewById(R.id.enableStoryboard); - enableStoryboard.setChecked(Config.isEnableStoryboard()); - enableStoryboard.setOnCheckedChangeListener((buttonView, isChecked) -> { - Config.setEnableStoryboard(isChecked); - PreferenceManager.getDefaultSharedPreferences(getContext()).edit() - .putBoolean("enableStoryboard", isChecked) - .commit(); - }); - - CheckBox showScoreboard = findViewById(R.id.showScoreboard); - showScoreboard.setChecked(Config.isShowScoreboard()); - showScoreboard.setOnCheckedChangeListener((buttonView, isChecked) -> { - Config.setShowScoreboard(isChecked); - PreferenceManager.getDefaultSharedPreferences(getContext()).edit() - .putBoolean("showscoreboard", isChecked) - .commit(); - }); - - CheckBox enableVideo = findViewById(R.id.enableVideo); - enableVideo.setChecked(Config.isVideoEnabled()); - enableVideo.setOnCheckedChangeListener((buttonView, isChecked) -> { - Config.setVideoEnabled(isChecked); - PreferenceManager.getDefaultSharedPreferences(getContext()).edit() - .putBoolean("enableVideo", isChecked) - .commit(); - }); - - CheckBox enableNCWhenSpeedChange = findViewById(R.id.enableNCwhenSpeedChange); - enableNCWhenSpeedChange.setChecked(ModMenu.getInstance().isEnableNCWhenSpeedChange()); - enableNCWhenSpeedChange.setOnCheckedChangeListener((buttonView, isChecked) -> { - ModMenu.getInstance().setEnableNCWhenSpeedChange(isChecked); - }); - - speedModifyText = findViewById(R.id.changeSpeedText); - - speedModifyToggle = findViewById(R.id.enableSpeedChange); - speedModifyToggle.setChecked(ModMenu.getInstance().getChangeSpeed() != 1.0f); - speedModifyToggle.setOnCheckedChangeListener((buttonView, isChecked) -> { - if (!isChecked) { - ModMenu.getInstance().setChangeSpeed(1.0f); - speedModifyText.setText(String.format(Locale.getDefault(), "%.2fx", ModMenu.getInstance().getChangeSpeed())); - speedModifyBar.setProgress(10); - ModMenu.getInstance().updateMultiplierText(); - } - else if(ModMenu.getInstance().getChangeSpeed() == 1.0f){ - speedModifyToggle.setChecked(false); - } - }); - - SeekBar backgroundBrightness = findViewById(R.id.backgroundBrightnessBar); - backgroundBrightness.setProgress( - PreferenceManager.getDefaultSharedPreferences(getContext()).getInt("bgbrightness", 25)); - backgroundBrightness.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { - @Override - public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - ((TextView) findViewById(R.id.brightPreviewText)).setText(String.valueOf(progress)); - ((TextView) findViewById(R.id.bgBrightnessText)).setText(progress + "%"); - int p = Math.round(FMath.clamp(255 * (progress / 100f), 0, 255)); - findViewById(R.id.brightnessPreview).setBackgroundColor(Color.argb(255, p, p, p)); - } - - @Override - public void onStartTrackingTouch(SeekBar seekBar) { - findViewById(R.id.brightnessPreviewLayout).setVisibility(View.VISIBLE); - int progress = seekBar.getProgress(); - ((TextView) findViewById(R.id.brightPreviewText)).setText(String.valueOf(progress)); - ((TextView) findViewById(R.id.bgBrightnessText)).setText(progress + "%"); - int p = Math.round(FMath.clamp(255 * (progress / 100f), 0, 255)); - findViewById(R.id.brightnessPreview).setBackgroundColor(Color.argb(255, p, p, p)); - } - - @Override - public void onStopTrackingTouch(SeekBar seekBar) { - findViewById(R.id.brightnessPreviewLayout).setVisibility(View.GONE); - int progress = seekBar.getProgress(); - ((TextView) findViewById(R.id.bgBrightnessText)).setText(progress + "%"); - Config.setBackgroundBrightness(seekBar.getProgress() / 100f); - PreferenceManager.getDefaultSharedPreferences(getContext()) - .edit() - .putInt("bgbrightness", progress) - .commit(); - } - }); - ((TextView) findViewById(R.id.bgBrightnessText)).setText( - PreferenceManager.getDefaultSharedPreferences(getContext()).getInt("bgbrightness", 25) + "%"); - - speedModifyBar = findViewById(R.id.changeSpeedBar); - speedModifyBar.setProgress((int)(ModMenu.getInstance().getChangeSpeed() * 20 - 10)); - speedModifyBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { - @Override - public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - float p = 0.5f + 0.05f * progress; - speedModifyText.setText(String.format(Locale.getDefault(), "%.2fx", p)); - if (p == 1.0f){ - speedModifyToggle.setChecked(false); - } - else { - speedModifyToggle.setChecked(true); - ModMenu.getInstance().updateMultiplierText(); - } - } - - @Override - public void onStartTrackingTouch(SeekBar seekBar) { - int progress = seekBar.getProgress(); - float p = 0.5f + 0.05f * progress; - speedModifyText.setText(String.format(Locale.getDefault(), "%.2fx", p)); - if (p == 1.0f){ - speedModifyToggle.setChecked(false); - } - else { - speedModifyToggle.setChecked(true); - ModMenu.getInstance().updateMultiplierText(); - } - } - - @Override - public void onStopTrackingTouch(SeekBar seekBar) { - int progress = seekBar.getProgress(); - float p = 0.5f + 0.05f * progress; - speedModifyText.setText(String.format(Locale.getDefault(), "%.2fx", p)); - ModMenu.getInstance().setChangeSpeed(p); - if (p == 1.0f){ - speedModifyToggle.setChecked(false); - } - else { - speedModifyToggle.setChecked(true); - ModMenu.getInstance().updateMultiplierText(); - } - } - }); - speedModifyText.setText(String.format(Locale.getDefault(), "%.2fx", ModMenu.getInstance().getChangeSpeed())); - - followDelayText = findViewById(R.id.flashlightFollowDelayText); - followDelayBar = findViewById(R.id.flashlightFollowDelayBar); - followDelayBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { - - boolean containsFlashlight = false; - - @Override - public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - - if (!containsFlashlight) - return; - - ModMenu.getInstance().setFLfollowDelay((float) Math.round(progress * 1200f) / (10f * 1000f)); - followDelayText.setText(progress * FlashLightEntity.defaultMoveDelayMS + "ms"); - } - - @Override - public void onStartTrackingTouch(SeekBar seekBar) { - containsFlashlight = ModMenu.getInstance().getMod().contains(GameMod.MOD_FLASHLIGHT); - } - - @Override - public void onStopTrackingTouch(SeekBar seekBar) { - if (containsFlashlight) - return; - - seekBar.setProgress(0); - ModMenu.getInstance().resetFLFollowDelay(); - followDelayText.setText((int) (ModMenu.getInstance().getFLfollowDelay() * 1000) + "ms"); - } - }); - - initializeDifficultyAdjustViews(); - updateVisibility(); - } - - - private void initializeDifficultyAdjustViews() { - - customARBar.setMax(125); - customODBar.setMax(110); - customCSBar.setMax(150); - customHPBar.setMax(110); - - customARToggle.setOnCheckedChangeListener(null); - customODToggle.setOnCheckedChangeListener(null); - customCSToggle.setOnCheckedChangeListener(null); - customHPToggle.setOnCheckedChangeListener(null); - - updateDifficultyAdjustValues(); - - customARToggle.setOnCheckedChangeListener((view, isChecked) -> { - - ModMenu.getInstance().setCustomAR(isChecked ? customARBar.getProgress() / 10f : null); - customARBar.setEnabled(isChecked); - - updateDifficultyAdjustValues(); - }); - - customODToggle.setOnCheckedChangeListener((view, isChecked) -> { - - ModMenu.getInstance().setCustomOD(isChecked ? customODBar.getProgress() / 10f : null); - customODBar.setEnabled(isChecked); - - updateDifficultyAdjustValues(); - }); - - customCSToggle.setOnCheckedChangeListener((view, isChecked) -> { - - ModMenu.getInstance().setCustomCS(isChecked ? customCSBar.getProgress() / 10f : null); - customCSBar.setEnabled(isChecked); - - updateDifficultyAdjustValues(); - }); - - customHPToggle.setOnCheckedChangeListener((view, isChecked) -> { - - ModMenu.getInstance().setCustomHP(isChecked ? customHPBar.getProgress() / 10f : null); - customHPBar.setEnabled(isChecked); - - updateDifficultyAdjustValues(); - }); - - - customARBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { - - public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - if (fromUser) { - ModMenu.getInstance().setCustomAR(progress / 10f); - } - customARText.setText(String.valueOf(progress / 10f)); - } - - public void onStopTrackingTouch(SeekBar seekBar) { - ModMenu.getInstance().updateMultiplierText(); - } - - public void onStartTrackingTouch(SeekBar seekBar) {} - }); - - customODBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { - - public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - if (fromUser) { - ModMenu.getInstance().setCustomOD(progress / 10f); - } - customODText.setText(String.valueOf(progress / 10f)); - } - - public void onStopTrackingTouch(SeekBar seekBar) { - ModMenu.getInstance().updateMultiplierText(); - } - - public void onStartTrackingTouch(SeekBar seekBar) {} - }); - - customCSBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { - - public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - if (fromUser) { - ModMenu.getInstance().setCustomCS(progress / 10f); - } - customCSText.setText(String.valueOf(progress / 10f)); - } - - public void onStopTrackingTouch(SeekBar seekBar) { - ModMenu.getInstance().updateMultiplierText(); - } - - public void onStartTrackingTouch(SeekBar seekBar) {} - }); - - customHPBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { - - public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - if (fromUser) { - ModMenu.getInstance().setCustomHP(progress / 10f); - } - customHPText.setText(String.valueOf(progress / 10f)); - } - - public void onStopTrackingTouch(SeekBar seekBar) { - ModMenu.getInstance().updateMultiplierText(); - } - - public void onStartTrackingTouch(SeekBar seekBar) {} - }); - } - - private void updateDifficultyAdjustValues() { - - var track = GlobalManager.getInstance().getSelectedTrack(); - var visibility = View.VISIBLE; - - if (Multiplayer.room != null) { - var settings = Multiplayer.room.getGameplaySettings(); - - if (!Multiplayer.isRoomHost() && - (!settings.isFreeMod() || !settings.getAllowForceDifficultyStatistics())) { - visibility = View.GONE; - } - } - - forceDifficultyStatisticsSplitter.setVisibility(visibility); - - var customAR = ModMenu.getInstance().getCustomAR(); - customARLayout.setVisibility(visibility); - customARToggle.setChecked(customAR != null); - customARBar.setEnabled(customAR != null); - customARBar.setProgress((int) ((customAR != null ? customAR : track != null ? track.getApproachRate() : 10) * 10)); - customARText.setText(String.valueOf(customARBar.getProgress() / 10f)); - - var customOD = ModMenu.getInstance().getCustomOD(); - customODLayout.setVisibility(visibility); - customODToggle.setChecked(customOD != null); - customODBar.setEnabled(customOD != null); - customODBar.setProgress((int) ((customOD != null ? customOD : track != null ? track.getOverallDifficulty() : 10) * 10)); - customODText.setText(String.valueOf(customODBar.getProgress() / 10f)); - - var customCS = ModMenu.getInstance().getCustomCS(); - customCSLayout.setVisibility(visibility); - customCSToggle.setChecked(customCS != null); - customCSBar.setEnabled(customCS != null); - customCSBar.setProgress((int) ((customCS != null ? customCS : track != null ? track.getCircleSize() : 10) * 10)); - customCSText.setText(String.valueOf(customCSBar.getProgress() / 10f)); - - var customHP = ModMenu.getInstance().getCustomHP(); - customHPLayout.setVisibility(visibility); - customHPToggle.setChecked(customHP != null); - customHPBar.setEnabled(customHP != null); - customHPBar.setProgress((int) ((customHP != null ? customHP : track != null ? track.getHpDrain() : 10) * 10)); - customHPText.setText(String.valueOf(customHPBar.getProgress() / 10f)); - - ModMenu.getInstance().updateMultiplierText(); - } - - - @Override - public void dismiss() { - super.dismiss(); - ModMenu.getInstance().hideByFrag(); - } - - public boolean isSettingPanelShow() { - return findViewById(R.id.fullLayout) != null && Math.abs(findViewById(R.id.fullLayout).getTranslationY()) < 10; - } - - private void updateVisibility() { - // Updating FL follow delay text value - var flFollowDelay = ModMenu.getInstance().getFLfollowDelay(); - followDelayRow.setVisibility(ModMenu.getInstance().getMod().contains(GameMod.MOD_FLASHLIGHT) ? View.VISIBLE : View.GONE); - followDelayBar.setProgress((int) (flFollowDelay * 1000 / FlashLightEntity.defaultMoveDelayMS)); - followDelayText.setText((int) (flFollowDelay * 1000) + "ms"); - - // Updating speed multiplier seekbar visibility - if (Multiplayer.isMultiplayer) - speedModifyRow.setVisibility(Multiplayer.isRoomHost() ? View.VISIBLE : View.GONE); - } - - @SuppressLint("ClickableViewAccessibility") - protected void toggleSettingPanel() { - updateVisibility(); - - if (isSettingPanelShow()) { - playHidePanelAnim(); - findViewById(R.id.frg_background).setOnTouchListener(null); - findViewById(R.id.frg_background).setClickable(false); - } else { - playShowPanelAnim(); - findViewById(R.id.frg_background).setOnTouchListener((v, event) -> { - if (event.getAction() == TouchEvent.ACTION_DOWN) { - if (isSettingPanelShow()) { - toggleSettingPanel(); - return true; - } - } - return false; - }); - findViewById(R.id.frg_background).setClickable(true); - } - } - - protected void playShowPanelAnim() { - View fullLayout = findViewById(R.id.fullLayout); - if (fullLayout != null) { - fullLayout.animate().cancel(); - fullLayout.animate() - .translationY(0) - .setDuration(200) - .setInterpolator(EasingHelper.asInterpolator(Easing.InOutQuad)) - .setListener(new BaseAnimationListener() { - @Override - public void onAnimationEnd(Animator animation) { - super.onAnimationEnd(animation); - findViewById(R.id.frg_background).setClickable(true); - findViewById(R.id.frg_background).setOnClickListener(v -> playHidePanelAnim()); - } - }) - .start(); - } - } - - protected void playHidePanelAnim() { - View fullLayout = findViewById(R.id.fullLayout); - if (fullLayout != null) { - fullLayout.animate().cancel(); - fullLayout.animate() - .translationY(findViewById(R.id.optionBody).getHeight()) - .setDuration(200) - .setInterpolator(EasingHelper.asInterpolator(Easing.InOutQuad)) - .setListener(new BaseAnimationListener() { - @Override - public void onAnimationEnd(Animator animation) { - super.onAnimationEnd(animation); - findViewById(R.id.frg_background).setClickable(false); - } - }) - .start(); - } - } -} diff --git a/src/com/edlplan/ui/fragment/InGameSettingMenu.kt b/src/com/edlplan/ui/fragment/InGameSettingMenu.kt new file mode 100644 index 000000000..0489ed7bd --- /dev/null +++ b/src/com/edlplan/ui/fragment/InGameSettingMenu.kt @@ -0,0 +1,566 @@ +package com.edlplan.ui.fragment + +import android.animation.Animator +import android.os.Bundle +import android.view.View +import android.widget.CheckBox +import android.widget.LinearLayout +import android.widget.RelativeLayout +import android.widget.SeekBar +import android.widget.SeekBar.OnSeekBarChangeListener +import android.widget.TextView +import androidx.preference.PreferenceManager +import com.edlplan.framework.easing.Easing +import com.edlplan.framework.math.FMath +import com.edlplan.ui.BaseAnimationListener +import com.edlplan.ui.EasingHelper +import com.reco1l.framework.lang.uiThread +import com.reco1l.legacy.Multiplayer +import org.anddev.andengine.input.touch.TouchEvent +import ru.nsu.ccfit.zuev.osu.Config +import ru.nsu.ccfit.zuev.osu.GlobalManager +import ru.nsu.ccfit.zuev.osu.game.cursor.flashlight.FlashLightEntity +import ru.nsu.ccfit.zuev.osu.game.mods.GameMod +import ru.nsu.ccfit.zuev.osu.menu.ModMenu +import ru.nsu.ccfit.zuev.osuplus.R +import java.util.Locale +import kotlin.math.abs +import kotlin.math.roundToInt + +class InGameSettingMenu : BaseFragment() { + private lateinit var speedModifyRow: View + private lateinit var speedModifyBar: SeekBar + private lateinit var speedModifyText: TextView + private lateinit var speedModifyToggle: CheckBox + + private lateinit var followDelayRow: View + private lateinit var followDelayBar: SeekBar + private lateinit var followDelayText: TextView + + private lateinit var forceDifficultyStatisticsSplitter: View + + private lateinit var customARLayout: RelativeLayout + private lateinit var customARToggle: CheckBox + private lateinit var customARText: TextView + private lateinit var customARBar: SeekBar + + private lateinit var customODLayout: RelativeLayout + private lateinit var customODToggle: CheckBox + private lateinit var customODText: TextView + private lateinit var customODBar: SeekBar + + private lateinit var customCSLayout: RelativeLayout + private lateinit var customCSToggle: CheckBox + private lateinit var customCSText: TextView + private lateinit var customCSBar: SeekBar + + private lateinit var customHPLayout: RelativeLayout + private lateinit var customHPToggle: CheckBox + private lateinit var customHPText: TextView + private lateinit var customHPBar: SeekBar + + override val layoutID: Int + get() = R.layout.fragment_in_game_option + + override fun onLoadView() { + reload(load()) + } + + override fun onSaveInstanceState(outState: Bundle) = outState.run { + super.onSaveInstanceState(this) + + putInt("speedModifyRow", speedModifyRow.visibility) + putInt("speedModifyBar", speedModifyBar.progress) + putString("speedModifyText", speedModifyText.text.toString()) + putBoolean("speedModifyToggle", speedModifyToggle.isChecked) + + putInt("followDelayRow", followDelayRow.visibility) + putInt("followDelayBar", followDelayBar.progress) + putString("followDelayText", followDelayText.text.toString()) + + putInt("forceDifficultyStatisticsSplitter", forceDifficultyStatisticsSplitter.visibility) + + putInt("customARLayout", customARLayout.visibility) + putBoolean("customARToggle", customARToggle.isChecked) + putString("customARText", customARText.text.toString()) + putInt("customARBar", customARBar.progress) + + putInt("customODLayout", customODLayout.visibility) + putBoolean("customODToggle", customODToggle.isChecked) + putString("customODText", customODText.text.toString()) + putInt("customODBar", customODBar.progress) + + putInt("customCSLayout", customCSLayout.visibility) + putBoolean("customCSToggle", customCSToggle.isChecked) + putString("customCSText", customCSText.text.toString()) + putInt("customCSBar", customCSBar.progress) + + putInt("customHPLayout", customHPLayout.visibility) + putBoolean("customHPToggle", customHPToggle.isChecked) + putString("customHPText", customHPText.text.toString()) + putInt("customHPBar", customHPBar.progress) + + putBoolean("enableStoryboard", findViewById(R.id.enableStoryboard)!!.isChecked) + putBoolean("showScoreboard", findViewById(R.id.showScoreboard)!!.isChecked) + putBoolean("enableVideo", findViewById(R.id.enableVideo)!!.isChecked) + putBoolean("enableNCwhenSpeedChange", findViewById(R.id.enableNCwhenSpeedChange)!!.isChecked) + putInt("backgroundBrightness", findViewById(R.id.backgroundBrightnessBar)!!.progress) + } + + private fun reload(state: SavedState?) { + if (state != null) { + this.setInitialSavedState(state) + } + + val showMore = findViewById(R.id.showMoreButton) ?: return + showMore.setOnTouchListener { v, event -> + if (event.action == TouchEvent.ACTION_DOWN) { + v.animate().cancel() + v.animate().scaleX(0.9f).scaleY(0.9f).translationY(v.height * 0.1f).setDuration(100) + .start() + toggleSettingPanel() + return@setOnTouchListener true + } else if (event.action == TouchEvent.ACTION_UP) { + v.animate().cancel() + v.animate().scaleX(1f).scaleY(1f).translationY(0f).setDuration(100).start() + return@setOnTouchListener true + } + false + } + + speedModifyRow = findViewById(R.id.speed_modify)!! + followDelayRow = findViewById(R.id.follow_delay_row)!! + + forceDifficultyStatisticsSplitter = findViewById(R.id.force_diffstat_split_view)!! + + customARLayout = findViewById(R.id.custom_ar_layout)!! + customARBar = findViewById(R.id.custom_ar_bar)!! + customARText = findViewById(R.id.custom_ar_text)!! + customARToggle = findViewById(R.id.custom_ar_toggle)!! + + customODLayout = findViewById(R.id.custom_od_layout)!! + customODBar = findViewById(R.id.custom_od_bar)!! + customODText = findViewById(R.id.custom_od_text)!! + customODToggle = findViewById(R.id.custom_od_toggle)!! + + customCSLayout = findViewById(R.id.custom_cs_layout)!! + customCSBar = findViewById(R.id.custom_cs_bar)!! + customCSText = findViewById(R.id.custom_cs_text)!! + customCSToggle = findViewById(R.id.custom_cs_toggle)!! + + customHPLayout = findViewById(R.id.custom_hp_layout)!! + customHPBar = findViewById(R.id.custom_hp_bar)!! + customHPText = findViewById(R.id.custom_hp_text)!! + customHPToggle = findViewById(R.id.custom_hp_toggle)!! + + findViewById(R.id.frg_background)!!.isClickable = false + + findViewById(R.id.enableStoryboard)!!.apply { + isChecked = Config.isEnableStoryboard() + setOnCheckedChangeListener { _, isChecked -> + Config.setEnableStoryboard(isChecked) + PreferenceManager.getDefaultSharedPreferences(context).edit() + .putBoolean("enableStoryboard", isChecked).commit() + } + } + + findViewById(R.id.showScoreboard)!!.apply { + isChecked = Config.isShowScoreboard() + setOnCheckedChangeListener { _, isChecked -> + Config.setShowScoreboard(isChecked) + PreferenceManager.getDefaultSharedPreferences(context).edit() + .putBoolean("showscoreboard", isChecked).commit() + } + } + + findViewById(R.id.enableVideo)!!.apply { + isChecked = Config.isVideoEnabled() + setOnCheckedChangeListener { _, isChecked -> + Config.setVideoEnabled(isChecked) + PreferenceManager.getDefaultSharedPreferences(context).edit() + .putBoolean("enableVideo", isChecked).commit() + } + } + + findViewById(R.id.enableNCwhenSpeedChange)!!.apply { + isChecked = ModMenu.getInstance().isEnableNCWhenSpeedChange + setOnCheckedChangeListener { _, isChecked -> + ModMenu.getInstance().isEnableNCWhenSpeedChange = isChecked + } + } + + speedModifyText = findViewById(R.id.changeSpeedText)!! + + speedModifyToggle = findViewById(R.id.enableSpeedChange)!! + speedModifyToggle.isChecked = ModMenu.getInstance().changeSpeed != 1f + speedModifyToggle.setOnCheckedChangeListener { _, isChecked -> + speedModifyBar.isEnabled = isChecked + if (!isChecked) { + ModMenu.getInstance().changeSpeed = 1f + speedModifyBar.progress = 10 + speedModifyText.text = String.format(Locale.getDefault(), "%.2fx", ModMenu.getInstance().changeSpeed) + ModMenu.getInstance().updateMultiplierText() + } + } + + val backgroundBrightness = findViewById(R.id.backgroundBrightnessBar)!! + backgroundBrightness.progress = PreferenceManager.getDefaultSharedPreferences(context) + .getInt("bgbrightness", 25) + backgroundBrightness.setOnSeekBarChangeListener( + object : OnSeekBarChangeListener { + override fun onProgressChanged( + seekBar: SeekBar?, + progress: Int, + fromUser: Boolean + ) { + findViewById(R.id.brightPreviewText)!!.text = progress.toString() + findViewById(R.id.bgBrightnessText)!!.text = "$progress%" + val clamped = FMath.clamp(255 * (progress / 100f), 0f, 255f).roundToInt() + findViewById(R.id.brightnessPreview)!!.setBackgroundColor( + 0xFF shl 24 or (clamped shl 16) or (clamped shl 8) or clamped + ) + } + + override fun onStartTrackingTouch(seekBar: SeekBar?) { + findViewById(R.id.brightnessPreviewLayout)!!.visibility = + View.VISIBLE + val progress = seekBar!!.progress + findViewById(R.id.brightPreviewText)!!.text = progress.toString() + findViewById(R.id.bgBrightnessText)!!.text = "$progress%" + val clamped = FMath.clamp(255 * (progress / 100f), 0f, 255f).roundToInt() + findViewById(R.id.brightnessPreview)!!.setBackgroundColor( + 0xFF shl 24 or (clamped shl 16) or (clamped shl 8) or clamped + ) + } + + override fun onStopTrackingTouch(seekBar: SeekBar?) { + findViewById(R.id.brightnessPreviewLayout)!!.visibility = + View.GONE + val progress = seekBar!!.progress + findViewById(R.id.bgBrightnessText)!!.text = "$progress%" + Config.setBackgroundBrightness(seekBar.progress / 100f) + PreferenceManager.getDefaultSharedPreferences(context).edit() + .putInt("bgbrightness", progress).commit() + } + } + ) + + findViewById(R.id.bgBrightnessText)!!.text = "${ + PreferenceManager.getDefaultSharedPreferences(context).getInt("bgbrightness", 25) + }%" + + speedModifyBar = findViewById(R.id.changeSpeedBar)!! + speedModifyBar.apply { + progress = (ModMenu.getInstance().changeSpeed * 20 - 10).toInt() + isEnabled = speedModifyToggle.isChecked + + setOnSeekBarChangeListener( + object : OnSeekBarChangeListener { + override fun onProgressChanged( + seekBar: SeekBar?, + progress: Int, + fromUser: Boolean + ) = update(progress) + + override fun onStartTrackingTouch(seekBar: SeekBar?) = update(seekBar!!.progress) + + override fun onStopTrackingTouch(seekBar: SeekBar?) = update(seekBar!!.progress) + + private fun update(progress: Int) { + val p = 0.5f + 0.05f * progress + speedModifyText.text = String.format(Locale.getDefault(), "%.2fx", p) + ModMenu.getInstance().changeSpeed = p + ModMenu.getInstance().updateMultiplierText() + } + } + ) + } + + speedModifyText.text = + String.format(Locale.getDefault(), "%.2fx", ModMenu.getInstance().changeSpeed) + + followDelayText = findViewById(R.id.flashlightFollowDelayText)!! + followDelayBar = findViewById(R.id.flashlightFollowDelayBar)!! + followDelayBar.setOnSeekBarChangeListener( + object : OnSeekBarChangeListener { + + var containsFlashlight = false + + override fun onProgressChanged( + seekBar: SeekBar?, + progress: Int, + fromUser: Boolean + ) { + if (!containsFlashlight) return + + ModMenu.getInstance().fLfollowDelay = + ((progress * ModMenu.DEFAULT_FL_FOLLOW_DELAY).roundToInt()).toFloat() // (progress * 1200f / (10f * 1000f)).roundToInt().toFloat() + followDelayText.text = "${progress * FlashLightEntity.defaultMoveDelayMS}ms" + } + + override fun onStartTrackingTouch(seekBar: SeekBar?) { + containsFlashlight = ModMenu.getInstance().mod.contains(GameMod.MOD_FLASHLIGHT) + } + + override fun onStopTrackingTouch(seekBar: SeekBar?) { + if (containsFlashlight) return + + seekBar!!.progress = 0 + ModMenu.getInstance().resetFLFollowDelay() + followDelayText.text = + "${(ModMenu.getInstance().fLfollowDelay * 1000f).toInt()}ms" + } + } + ) + + initializeDifficultyAdjustViews() + updateVisibility() + } + + private fun initializeDifficultyAdjustViews() { + customARBar.max = 125 + customODBar.max = 110 + customCSBar.max = 150 + customHPBar.max = 110 + + customARToggle.setOnCheckedChangeListener(null) + customODToggle.setOnCheckedChangeListener(null) + customCSToggle.setOnCheckedChangeListener(null) + customHPToggle.setOnCheckedChangeListener(null) + + updateDifficultyAdjustValues() + + customARToggle.setOnCheckedChangeListener { _, isChecked -> + ModMenu.getInstance().customAR = if (isChecked) customARBar.progress / 10f else null + customARBar.isEnabled = isChecked + + updateDifficultyAdjustValues() + } + + customODToggle.setOnCheckedChangeListener { _, isChecked -> + ModMenu.getInstance().customOD = if (isChecked) customODBar.progress / 10f else null + customODBar.isEnabled = isChecked + + updateDifficultyAdjustValues() + } + + customCSToggle.setOnCheckedChangeListener { _, isChecked -> + ModMenu.getInstance().customCS = if (isChecked) customCSBar.progress / 10f else null + customCSBar.isEnabled = isChecked + + updateDifficultyAdjustValues() + } + + customHPToggle.setOnCheckedChangeListener { _, isChecked -> + ModMenu.getInstance().customHP = if (isChecked) customHPBar.progress / 10f else null + customHPBar.isEnabled = isChecked + + updateDifficultyAdjustValues() + } + + customARBar.setOnSeekBarChangeListener( + object : OnSeekBarChangeListener { + override fun onProgressChanged( + seekBar: SeekBar?, + progress: Int, + fromUser: Boolean + ) { + if (fromUser) ModMenu.getInstance().customAR = progress / 10f + customARText.text = "${progress / 10f}" + } + + override fun onStartTrackingTouch(seekBar: SeekBar?) {} + + override fun onStopTrackingTouch(seekBar: SeekBar?) { + ModMenu.getInstance().updateMultiplierText() + } + } + ) + + customODBar.setOnSeekBarChangeListener( + object : OnSeekBarChangeListener { + override fun onProgressChanged( + seekBar: SeekBar?, + progress: Int, + fromUser: Boolean + ) { + if (fromUser) ModMenu.getInstance().customOD = progress / 10f + customODText.text = "${progress / 10f}" + } + + override fun onStartTrackingTouch(seekBar: SeekBar?) {} + + override fun onStopTrackingTouch(seekBar: SeekBar?) { + ModMenu.getInstance().updateMultiplierText() + } + } + ) + + customCSBar.setOnSeekBarChangeListener( + object : OnSeekBarChangeListener { + override fun onProgressChanged( + seekBar: SeekBar?, + progress: Int, + fromUser: Boolean + ) { + if (fromUser) ModMenu.getInstance().customCS = progress / 10f + customCSText.text = "${progress / 10f}" + } + + override fun onStartTrackingTouch(seekBar: SeekBar?) {} + + override fun onStopTrackingTouch(seekBar: SeekBar?) { + ModMenu.getInstance().updateMultiplierText() + } + } + ) + + customHPBar.setOnSeekBarChangeListener( + object : OnSeekBarChangeListener { + override fun onProgressChanged( + seekBar: SeekBar?, + progress: Int, + fromUser: Boolean + ) { + if (fromUser) ModMenu.getInstance().customHP = progress / 10f + customHPText.text = "${progress / 10f}" + } + + override fun onStartTrackingTouch(seekBar: SeekBar?) {} + + override fun onStopTrackingTouch(seekBar: SeekBar?) { + ModMenu.getInstance().updateMultiplierText() + } + } + ) + } + + private fun updateDifficultyAdjustValues() { + val track = GlobalManager.getInstance().selectedTrack + var visibility = View.VISIBLE + + if (Multiplayer.room != null) { + val settings = Multiplayer.room!!.gameplaySettings + + if (!Multiplayer.isRoomHost && (!settings.isFreeMod || !settings.allowForceDifficultyStatistics)) { + visibility = View.GONE + } + } + + forceDifficultyStatisticsSplitter.visibility = visibility + + val customAR = ModMenu.getInstance().customAR + customARLayout.visibility = visibility + customARToggle.isChecked = customAR != null + customARBar.isEnabled = customAR != null + customARBar.progress = (((customAR ?: track?.approachRate) ?: 10f) * 10).toInt() + customARText.text = "${customARBar.progress / 10f}" + + val customOD = ModMenu.getInstance().customOD + customODLayout.visibility = visibility + customODToggle.isChecked = customOD != null + customODBar.isEnabled = customOD != null + customODBar.progress = (((customOD ?: track?.overallDifficulty) ?: 10f) * 10).toInt() + customODText.text = "${customODBar.progress / 10f}" + + val customCS = ModMenu.getInstance().customCS + customCSLayout.visibility = visibility + customCSToggle.isChecked = customCS != null + customCSBar.isEnabled = customCS != null + customCSBar.progress = (((customCS ?: track?.circleSize) ?: 10f) * 10).toInt() + customCSText.text = "${customCSBar.progress / 10f}" + + val customHP = ModMenu.getInstance().customHP + customHPLayout.visibility = visibility + customHPToggle.isChecked = customHP != null + customHPBar.isEnabled = customHP != null + customHPBar.progress = (((customHP ?: track?.hpDrain) ?: 10f) * 10).toInt() + customHPText.text = "${customHPBar.progress / 10f}" + + ModMenu.getInstance().updateMultiplierText() + } + + override fun dismiss() { + super.dismiss() + uiThread { super.save() } + ModMenu.getInstance().hideByFrag() + } + + private fun isSettingPanelShow(): Boolean { + return abs(findViewById(R.id.fullLayout)?.translationY ?: 11f) < 10 + } + + private fun updateVisibility() { + val flFollowDelay = ModMenu.getInstance().fLfollowDelay + followDelayRow.visibility = + if (ModMenu.getInstance().mod.contains(GameMod.MOD_FLASHLIGHT)) View.VISIBLE else View.GONE + followDelayBar.progress = + (flFollowDelay * 1000f / FlashLightEntity.defaultMoveDelayMS).toInt() + followDelayText.text = "${(flFollowDelay * 1000f).toInt()}ms" + + if (Multiplayer.isMultiplayer) { + speedModifyRow.visibility = if (Multiplayer.isRoomHost) View.VISIBLE else View.GONE + } + } + + private fun toggleSettingPanel() { + updateVisibility() + + val background = findViewById(R.id.frg_background)!! + if (isSettingPanelShow()) { + playHidePanelAnim() + background.setOnTouchListener(null) + background.isClickable = false + } else { + playShowPanelAnim() + background.setOnTouchListener { _, event -> + if (event.action == TouchEvent.ACTION_DOWN && isSettingPanelShow()) { + toggleSettingPanel() + return@setOnTouchListener true + } + false + } + background.isClickable = true + } + } + + private fun playShowPanelAnim() { + val layout = findViewById(R.id.fullLayout) + layout?.animate()?.cancel() + layout?.animate() + ?.translationY(0f) + ?.setDuration(200) + ?.setInterpolator(EasingHelper.asInterpolator(Easing.InOutQuad)) + ?.setListener( + object : BaseAnimationListener() { + override fun onAnimationEnd(animation: Animator?) { + super.onAnimationEnd(animation) + val background = findViewById(R.id.frg_background)!! + background.isClickable = true + background.setOnClickListener { + playShowPanelAnim() + } + } + } + ) + ?.start() + } + + private fun playHidePanelAnim() { + val layout = findViewById(R.id.fullLayout) + layout?.animate()?.cancel() + layout?.animate() + ?.translationY(findViewById(R.id.optionBody)!!.height.toFloat()) + ?.setDuration(200) + ?.setInterpolator(EasingHelper.asInterpolator(Easing.InOutQuad)) + ?.setListener( + object : BaseAnimationListener() { + override fun onAnimationEnd(animation: Animator?) { + super.onAnimationEnd(animation) + findViewById(R.id.frg_background)!!.isClickable = false + } + } + ) + ?.start() + } +} \ No newline at end of file diff --git a/src/com/edlplan/ui/fragment/MapInfoFragment.java b/src/com/edlplan/ui/fragment/MapInfoFragment.java index f54ba1d93..faeb7d918 100644 --- a/src/com/edlplan/ui/fragment/MapInfoFragment.java +++ b/src/com/edlplan/ui/fragment/MapInfoFragment.java @@ -25,9 +25,7 @@ protected void onLoadView() { text = findViewById(R.id.mapinfo_text); text.setText(info); Button exit = findViewById(R.id.mapinfo_exit); - exit.setOnClickListener(v -> { - dismiss(); - }); + exit.setOnClickListener(v -> dismiss()); playOnLoadAnim(); } diff --git a/src/com/edlplan/ui/fragment/PropsMenuFragment.java b/src/com/edlplan/ui/fragment/PropsMenuFragment.java index ab7e1ce52..7605264ba 100644 --- a/src/com/edlplan/ui/fragment/PropsMenuFragment.java +++ b/src/com/edlplan/ui/fragment/PropsMenuFragment.java @@ -44,7 +44,7 @@ protected void onLoadView() { offset = findViewById(R.id.offsetBox); isFav = findViewById(R.id.addToFav); - offset.setText(props.getOffset() + ""); + offset.setText(String.valueOf(props.getOffset())); isFav.setChecked(props.isFavorite()); isFav.setOnCheckedChangeListener((buttonView, isChecked) -> { @@ -82,7 +82,7 @@ public void afterTextChanged(Editable s) { } if (needRest) { offset.removeTextChangedListener(this); - offset.setText(o + ""); + offset.setText(String.valueOf(o)); offset.setSelection(pos); offset.addTextChangedListener(this); } @@ -93,7 +93,6 @@ public void afterTextChanged(Editable s) { props.setOffset(0); saveProp(); } - return; } } }); @@ -101,7 +100,7 @@ public void afterTextChanged(Editable s) { findViewById(R.id.manageFavButton).setOnClickListener(v -> { FavoriteManagerFragment dialog = new FavoriteManagerFragment(); //TODO : 铺面引用还是全局耦合的,需要分离 - dialog.showToAddToFloder(ScoreLibrary.getTrackDir(GlobalManager.getInstance().getSelectedTrack().getFilename())); + dialog.showToAddToFolder(ScoreLibrary.getTrackDir(GlobalManager.getInstance().getSelectedTrack().getFilename())); }); findViewById(R.id.deleteBeatmap).setOnClickListener(v -> { diff --git a/src/com/edlplan/ui/fragment/ScoreMenuFragment.java b/src/com/edlplan/ui/fragment/ScoreMenuFragment.java index fb453d9e4..1f8477ddd 100644 --- a/src/com/edlplan/ui/fragment/ScoreMenuFragment.java +++ b/src/com/edlplan/ui/fragment/ScoreMenuFragment.java @@ -40,9 +40,7 @@ protected int getLayoutID() { protected void onLoadView() { findViewById(R.id.exportReplay).setOnClickListener(v -> { List replays = OdrDatabase.get().getReplayById(scoreId); - if (replays.size() == 0) { - return; - } else { + if (replays.size() > 0) { try { OsuDroidReplay replay = replays.get(0); final File file = new File( @@ -81,9 +79,7 @@ public void onClick(View v) { confirm.showForResult(isAccepted -> { if (isAccepted) { List replays = OdrDatabase.get().getReplayById(scoreId); - if (replays.size() == 0) { - return; - } else { + if (replays.size() > 0) { try { if (OdrDatabase.get().deleteReplay(scoreId) == 0) { Snackbar.make(v, "Failed to delete replay!", 1500) diff --git a/src/com/edlplan/ui/fragment/SettingsFragment.kt b/src/com/edlplan/ui/fragment/SettingsFragment.kt index 40093cbb2..7d4fa93d3 100644 --- a/src/com/edlplan/ui/fragment/SettingsFragment.kt +++ b/src/com/edlplan/ui/fragment/SettingsFragment.kt @@ -67,7 +67,7 @@ abstract class SettingsFragment : PreferenceFragmentCompat(), BackPressListener override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { isCreated = true - root = super.onCreateView(inflater, container, savedInstanceState) + root = super.onCreateView(inflater, container, savedInstanceState) onLoadView() return root } diff --git a/src/com/edlplan/ui/fragment/WebViewFragment.java b/src/com/edlplan/ui/fragment/WebViewFragment.java index 51d627c43..9469515df 100644 --- a/src/com/edlplan/ui/fragment/WebViewFragment.java +++ b/src/com/edlplan/ui/fragment/WebViewFragment.java @@ -41,14 +41,12 @@ protected int getLayoutID() { @Override protected void onLoadView() { - webview = (WebView) findViewById(R.id.web); + webview = findViewById(R.id.web); WebSettings webSettings = webview.getSettings(); webSettings.setJavaScriptEnabled(true); webSettings.setUserAgentString("osudroid"); - ((ImageButton) findViewById(R.id.close_button)).setOnClickListener(v -> { - dismiss(); - }); + findViewById(R.id.close_button).setOnClickListener(v -> dismiss()); webview.setWebViewClient(new WebViewClient() { @Override diff --git a/src/com/reco1l/api/chimu/CheesegullAPI.kt b/src/com/reco1l/api/chimu/CheesegullAPI.kt index acbfbfe5a..ac1a7ba50 100644 --- a/src/com/reco1l/api/chimu/CheesegullAPI.kt +++ b/src/com/reco1l/api/chimu/CheesegullAPI.kt @@ -2,7 +2,6 @@ package com.reco1l.api.chimu import com.reco1l.framework.extensions.mapInto import com.reco1l.framework.extensions.mapIntoListOf -import com.reco1l.framework.net.JsonContent import com.reco1l.framework.net.JsonRequester import com.reco1l.framework.net.QueryContent diff --git a/src/com/reco1l/framework/extensions/StringExt.kt b/src/com/reco1l/framework/extensions/StringExt.kt index 928084e22..d6b2ae066 100644 --- a/src/com/reco1l/framework/extensions/StringExt.kt +++ b/src/com/reco1l/framework/extensions/StringExt.kt @@ -21,7 +21,7 @@ fun String.toDate() = DateFormat.format(this, Date()).toString() * * @see [URLDecoder.decode] */ -fun String.decodeUtf8() = URLDecoder.decode(this, StandardCharsets.UTF_8.name()) +fun String.decodeUtf8(): String = URLDecoder.decode(this, StandardCharsets.UTF_8.name()) /** * Remove all characters in a filename that are invalid in the filesystem. diff --git a/src/com/reco1l/framework/lang/execution/Async.java b/src/com/reco1l/framework/lang/execution/Async.java index 893e6931a..300a2ebaf 100644 --- a/src/com/reco1l/framework/lang/execution/Async.java +++ b/src/com/reco1l/framework/lang/execution/Async.java @@ -7,41 +7,18 @@ /** * @author Reco1l + * @author ammar + * Originally created by Reco1l, adapted by ammar. */ public final class Async { - /** - * This prefix is set to the thread name that's created by the Executor, this is useful to identify asynchronous threads. - */ - public static final String THREAD_PREFIX = "async::"; + private static final ExecutorService GLOBAL_EXECUTOR = Executors.newSingleThreadExecutor( + runnable -> new Thread(runnable, "async::" + Thread.currentThread().getName()) + ); - //----------------------------------------------------------------------------------------------------------------// - - private final ExecutorService mExecutor; - - //----------------------------------------------------------------------------------------------------------------// - - private Async(Runnable task) - { - mExecutor = Executors.newSingleThreadExecutor(); - - mExecutor.execute(() -> { - Thread.currentThread().setName(THREAD_PREFIX + Thread.currentThread().getName()); - task.run(); - mExecutor.shutdown(); - }); + public static void run(@NonNull Runnable task) { + GLOBAL_EXECUTOR.execute(task); } - //----------------------------------------------------------------------------------------------------------------// - - public static Async run(@NonNull Runnable task) - { - return new Async(task); - } - - public ExecutorService getExecutor() - { - return mExecutor; - } } diff --git a/src/com/reco1l/framework/net/JsonRequester.kt b/src/com/reco1l/framework/net/JsonRequester.kt index aec3f7023..af19da0ab 100644 --- a/src/com/reco1l/framework/net/JsonRequester.kt +++ b/src/com/reco1l/framework/net/JsonRequester.kt @@ -5,7 +5,6 @@ import com.reco1l.framework.extensions.logIfDebug import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.RequestBody.Companion.toRequestBody import okhttp3.Response -import org.json.JSONException import org.json.JSONObject class JsonRequester(url: String) : Requester(url) diff --git a/src/com/reco1l/legacy/ui/ChimuWebView.java b/src/com/reco1l/legacy/ui/ChimuWebView.java deleted file mode 100644 index 13677a55d..000000000 --- a/src/com/reco1l/legacy/ui/ChimuWebView.java +++ /dev/null @@ -1,238 +0,0 @@ -package com.reco1l.legacy.ui; - -import android.content.Intent; -import android.graphics.Bitmap; -import android.net.Uri; -import android.view.View; -import com.edlplan.ui.fragment.LoadingFragment; -import com.edlplan.ui.fragment.WebViewFragment; -import com.reco1l.framework.extensions.StringUtil; -import com.reco1l.framework.net.Downloader; -import com.reco1l.framework.net.IDownloaderObserver; -import com.reco1l.framework.net.SizeMeasure; -import com.reco1l.legacy.Multiplayer; -import com.reco1l.legacy.ui.multiplayer.RoomScene; -import im.delight.android.webview.AdvancedWebView; -import net.lingala.zip4j.ZipFile; -import org.apache.commons.io.FilenameUtils; -import ru.nsu.ccfit.zuev.osu.*; -import ru.nsu.ccfit.zuev.osu.helper.FileUtils; -import ru.nsu.ccfit.zuev.osu.helper.StringTable; -import ru.nsu.ccfit.zuev.osuplus.R; - -import java.io.File; -import java.io.IOException; - -import static android.content.Intent.ACTION_VIEW; -import static android.os.Environment.DIRECTORY_DOWNLOADS; - -@SuppressWarnings("DataFlowIssue") -public class ChimuWebView extends WebViewFragment implements IDownloaderObserver -{ - - public static final Uri MIRROR = Uri.parse("https://chimu.moe/en/beatmaps?mode=0"); - - public static final ChimuWebView INSTANCE = new ChimuWebView(); - - public static final String FILE_EXTENSION = ".osz"; - - //----------------------------------------------------------------------------------------------------------------// - - private DownloadingFragment mFragment; - - private AdvancedWebView mWebView; - - private String mCurrentFilename; - - private final MainActivity mActivity = GlobalManager.getInstance().getMainActivity(); - - //----------------------------------------------------------------------------------------------------------------// - - public ChimuWebView() - { - super.setURL(MIRROR.toString()); - } - - //----------------------------------------------------------------------------------------------------------------// - - @Override - protected int getLayoutID() - { - return R.layout.fragment_chimu; - } - - //----------------------------------------------------------------------------------------------------------------// - - @Override - protected void onLoadView() - { - super.onLoadView(); - - mWebView = findViewById(R.id.web); - assert mWebView != null; - - mWebView.addPermittedHostname(MIRROR.getHost()); - mWebView.setListener(mActivity, new AdvancedWebView.Listener() - { - final LoadingFragment fragment = new LoadingFragment(); - - @Override - public void onPageStarted(String url, Bitmap favicon) - { - fragment.show(); - } - - @Override - public void onPageFinished(String url) - { - fragment.dismiss(); - } - - @Override - public void onPageError(int errorCode, String description, String failingUrl) - { - - } - - @Override - public void onDownloadRequested(String url, String filename, String mimeType, long contentLength, String contentDisposition, String userAgent) - { - startDownload(url, filename); - } - - @Override - public void onExternalPageRequest(String url) - { - Intent intent = new Intent(ACTION_VIEW, Uri.parse(url)); - startActivity(intent); - } - }); - } - - public void startDownload(String url, String filename) - { - String name = StringUtil.decodeUtf8(filename); - filename = StringUtil.forFilesystem(name); - - if (!filename.endsWith(FILE_EXTENSION)) - { - ToastLogger.showText("Failed to start download, invalid file extension.", true); - return; - } - - mCurrentFilename = FilenameUtils.removeExtension(name); - - File directory = mActivity.getExternalFilesDir(DIRECTORY_DOWNLOADS); - File file = new File(directory, filename + FILE_EXTENSION); - - Downloader downloader = new Downloader(file, url); - - mFragment = new DownloadingFragment(); - mFragment.setDownloader(downloader, () -> { - - mFragment.getText().setVisibility(View.VISIBLE); - mFragment.getText().setText(R.string.chimu_connecting); - mFragment.getButton().setVisibility(View.VISIBLE); - mFragment.getButton().setText(R.string.chimu_cancel); - - downloader.setObserver(ChimuWebView.this); - downloader.download(); - - mFragment.getButton().setOnClickListener(v -> downloader.cancel()); - }); - mFragment.show(); - } - - //----------------------------------------------------------------------------------------------------------------// - - @Override - public void dismiss() - { - mWebView.destroy(); - super.dismiss(); - } - - //----------------------------------------------------------------------------------------------------------------// - - @Override - public void onDownloadStart(Downloader downloader) - { - mActivity.runOnUiThread(() -> { - mFragment.getText().setText(StringTable.format(R.string.chimu_downloading, mCurrentFilename)); - }); - } - - @Override - public void onDownloadEnd(Downloader downloader) - { - mActivity.runOnUiThread(() -> { - mFragment.getProgressBar().setVisibility(View.GONE); - mFragment.getProgressBar().setIndeterminate(true); - mFragment.getProgressBar().setVisibility(View.VISIBLE); - - mFragment.getText().setText(StringTable.format(R.string.chimu_importing, mCurrentFilename)); - mFragment.getButton().setVisibility(View.GONE); - }); - - File file = downloader.getFile(); - - try (ZipFile zip = new ZipFile(file)) - { - if (!zip.isValidZipFile()) - { - mActivity.runOnUiThread(mFragment::dismiss); - ToastLogger.showText("Import failed, invalid ZIP file.", true); - return; - } - - if (!FileUtils.extractZip(file.getPath(), Config.getBeatmapPath())) - { - mActivity.runOnUiThread(mFragment::dismiss); - ToastLogger.showText("Import failed, unable to extract ZIP file.", true); - return; - } - - LibraryManager.INSTANCE.updateLibrary(true); - } - catch (IOException e) - { - ToastLogger.showText("Import failed: " + e.getMessage(), true); - } - mActivity.runOnUiThread(mFragment::dismiss); - - if (Multiplayer.isConnected()) - RoomScene.INSTANCE.onRoomBeatmapChange(Multiplayer.room.getBeatmap()); - } - - @Override - public void onDownloadCancel(Downloader downloader) - { - ToastLogger.showText("Download canceled.", true); - mActivity.runOnUiThread(mFragment::dismiss); - } - - @Override - public void onDownloadUpdate(Downloader downloader) - { - String info = String.format("\n%.3f kb/s (%d%%)", downloader.getSpeed(SizeMeasure.MBPS), (int) downloader.getProgress()); - - mActivity.runOnUiThread(() -> { - mFragment.getText().setText(StringTable.format(R.string.chimu_downloading, mCurrentFilename) + info); - mFragment.getProgressBar().setIndeterminate(false); - mFragment.getProgressBar().setProgress((int) downloader.getProgress()); - }); - } - - @Override - public void onDownloadFail(Downloader downloader) - { - mActivity.runOnUiThread(mFragment::dismiss); - - if (downloader.getException() != null) - { - ToastLogger.showText("Download failed: " + downloader.getException().getMessage(), true); - return; - } - ToastLogger.showText("Download failed.", true); - } -} diff --git a/src/com/reco1l/legacy/ui/ChimuWebView.kt b/src/com/reco1l/legacy/ui/ChimuWebView.kt new file mode 100644 index 000000000..28b34a09c --- /dev/null +++ b/src/com/reco1l/legacy/ui/ChimuWebView.kt @@ -0,0 +1,185 @@ +package com.reco1l.legacy.ui + +import android.content.Intent +import android.content.Intent.ACTION_VIEW +import android.graphics.Bitmap +import android.net.Uri +import android.os.Environment.DIRECTORY_DOWNLOADS +import android.view.View +import com.edlplan.ui.fragment.LoadingFragment +import com.edlplan.ui.fragment.WebViewFragment +import com.reco1l.framework.net.IDownloaderObserver +import im.delight.android.webview.AdvancedWebView +import ru.nsu.ccfit.zuev.osu.GlobalManager +import ru.nsu.ccfit.zuev.osuplus.R + +import com.reco1l.framework.extensions.decodeUtf8 +import com.reco1l.framework.extensions.forFilesystem +import com.reco1l.framework.net.Downloader +import com.reco1l.framework.net.SizeMeasure +import com.reco1l.legacy.Multiplayer +import com.reco1l.legacy.ui.multiplayer.RoomScene +import net.lingala.zip4j.ZipFile +import org.apache.commons.io.FilenameUtils +import ru.nsu.ccfit.zuev.osu.Config +import ru.nsu.ccfit.zuev.osu.LibraryManager +import ru.nsu.ccfit.zuev.osu.ToastLogger +import ru.nsu.ccfit.zuev.osu.helper.FileUtils +import ru.nsu.ccfit.zuev.osu.helper.StringTable +import java.io.IOException + +object ChimuWebView : WebViewFragment(), IDownloaderObserver { + private val MIRROR: Uri = Uri.parse("https://chimu.moe/en/beatmaps?mode=0") + const val FILE_EXTENSION = ".osz" + + private lateinit var mFragment: DownloadingFragment + private lateinit var mWebView: AdvancedWebView + private lateinit var mCurrentFilename: String + + private val mActivity = GlobalManager.getInstance().mainActivity + + init { + super.setURL(MIRROR.toString()) + } + + override val layoutID: Int + get() = R.layout.fragment_chimu + + override fun onLoadView() { + super.onLoadView() + mWebView = findViewById(R.id.web)!! + mWebView.addPermittedHostname(MIRROR.host) + mWebView.setListener(mActivity, + object : AdvancedWebView.Listener { + val fragment = LoadingFragment() + + override fun onPageStarted(url: String?, favicon: Bitmap?) = fragment.show() + + override fun onPageFinished(url: String?) = fragment.dismiss() + + override fun onPageError( + errorCode: Int, + description: String?, + failingUrl: String? + ) { + } + + override fun onDownloadRequested( + url: String?, + suggestedFilename: String?, + mimeType: String?, + contentLength: Long, + contentDisposition: String?, + userAgent: String? + ) { + startDownload(url!!, suggestedFilename!!) + } + + override fun onExternalPageRequest(url: String?) = + startActivity(Intent(ACTION_VIEW, Uri.parse(url))) + } + ) + } + + fun startDownload(url: String, suggestedFilename: String) { + val name = suggestedFilename.decodeUtf8() + val filename = name.forFilesystem() + + if (!filename.endsWith(FILE_EXTENSION)) { + ToastLogger.showText("Failed to start download. Invalid file extension", true) + return + } + + mCurrentFilename = FilenameUtils.removeExtension(filename) + + val directory = mActivity.getExternalFilesDir(DIRECTORY_DOWNLOADS) + val file = directory?.resolve(filename + FILE_EXTENSION)!! + + val downloader = Downloader(file, url) + + mFragment = DownloadingFragment() + mFragment.setDownloader(downloader) { + mFragment.text.visibility = View.VISIBLE + mFragment.text.text = getString(R.string.chimu_connecting) + mFragment.button.visibility = View.VISIBLE + mFragment.button.text = getString(R.string.chimu_cancel) + + downloader.observer = this@ChimuWebView + downloader.download() + + mFragment.button.setOnClickListener { + downloader.cancel() + } + } + mFragment.show() + } + + override fun dismiss() { + mWebView.destroy() + super.dismiss() + } + + override fun onDownloadStart(downloader: Downloader) { + mActivity.runOnUiThread { + mFragment.text.text = StringTable.format(R.string.chimu_downloading, mCurrentFilename) + } + } + + override fun onDownloadEnd(downloader: Downloader) { + mActivity.runOnUiThread { + mFragment.progressBar.visibility = View.GONE + mFragment.progressBar.isIndeterminate = true + mFragment.progressBar.visibility = View.VISIBLE + + mFragment.text.text = StringTable.format(R.string.chimu_importing, mCurrentFilename) + mFragment.button.visibility = View.GONE + } + + val file = downloader.file + + try { + ZipFile(file).use { + if (!it.isValidZipFile) { + mActivity.runOnUiThread(mFragment::dismiss) + ToastLogger.showText("Import failed, invalid ZIP file.", true) + return + } + + if (!FileUtils.extractZip(file.path, Config.getBeatmapPath())) { + mActivity.runOnUiThread(mFragment::dismiss) + ToastLogger.showText("Import failed, failed to extract ZIP file.", true) + return + } + + LibraryManager.INSTANCE.updateLibrary(true) + } + } catch (e: IOException) { + ToastLogger.showText("Import failed:" + e.message, true) + } + + mActivity.runOnUiThread(mFragment::dismiss) + + if (Multiplayer.isConnected) + RoomScene.onRoomBeatmapChange(Multiplayer.room!!.beatmap) + } + + override fun onDownloadCancel(downloader: Downloader) { + ToastLogger.showText("Download canceled.", true) + mActivity.runOnUiThread(mFragment::dismiss) + } + + override fun onDownloadUpdate(downloader: Downloader) { + val info = String.format("\n%.3f kb/s (%d%%)", downloader.getSpeed(SizeMeasure.MBPS), downloader.progress.toInt()) + + mActivity.runOnUiThread { + mFragment.text.text = StringTable.format(R.string.chimu_downloading, mCurrentFilename) + info + mFragment.progressBar.isIndeterminate = false + mFragment.progressBar.progress = downloader.progress.toInt() + } + } + + override fun onDownloadFail(downloader: Downloader) { + mActivity.runOnUiThread(mFragment::dismiss) + ToastLogger.showText("Download failed. " + downloader.exception?.message, true) + } +} \ No newline at end of file diff --git a/src/com/reco1l/legacy/ui/DownloadingFragment.java b/src/com/reco1l/legacy/ui/DownloadingFragment.java deleted file mode 100644 index d044da15a..000000000 --- a/src/com/reco1l/legacy/ui/DownloadingFragment.java +++ /dev/null @@ -1,88 +0,0 @@ -package com.reco1l.legacy.ui; - -import android.text.TextUtils; -import android.view.View; -import android.widget.Button; -import android.widget.ProgressBar; -import android.widget.TextView; -import com.edlplan.ui.fragment.LoadingFragment; -import com.google.android.material.progressindicator.CircularProgressIndicator; -import com.reco1l.framework.net.Downloader; -import ru.nsu.ccfit.zuev.osuplus.R; - -public class DownloadingFragment extends LoadingFragment -{ - - private Downloader mDownloader; - private Runnable mAwaitCall; - - private Button mButton; - private TextView mText; - private CircularProgressIndicator mProgressBar; - - //----------------------------------------------------------------------------------------------------------------// - - public void setDownloader(Downloader downloader, Runnable await) - { - mAwaitCall = await; - mDownloader = downloader; - } - - //----------------------------------------------------------------------------------------------------------------// - - @Override - protected int getLayoutID() - { - return R.layout.fragment_downloading; - } - - //----------------------------------------------------------------------------------------------------------------// - - @Override - protected void onLoadView() - { - super.onLoadView(); - - mText = findViewById(R.id.text); - mButton = findViewById(R.id.button); - mProgressBar = findViewById(R.id.progress); - - mAwaitCall.run(); - } - - //----------------------------------------------------------------------------------------------------------------// - - @Override - public void callDismissOnBackPress() - { - if (mDownloader.isDownloading()) - { - mDownloader.cancel(); - return; - } - super.callDismissOnBackPress(); - } - - //----------------------------------------------------------------------------------------------------------------// - - public ProgressBar getProgressBar() - { - return mProgressBar; - } - - public Button getButton() - { - return mButton; - } - - public TextView getText() - { - return mText; - } - - public void setText(String text) - { - mText.setVisibility(TextUtils.isEmpty(text) ? View.GONE : View.VISIBLE); - mText.setText(text); - } -} \ No newline at end of file diff --git a/src/com/reco1l/legacy/ui/DownloadingFragment.kt b/src/com/reco1l/legacy/ui/DownloadingFragment.kt new file mode 100644 index 000000000..a72b348bf --- /dev/null +++ b/src/com/reco1l/legacy/ui/DownloadingFragment.kt @@ -0,0 +1,59 @@ +package com.reco1l.legacy.ui + +import android.text.TextUtils +import android.view.View +import android.widget.Button +import android.widget.TextView +import com.edlplan.ui.fragment.LoadingFragment +import com.google.android.material.progressindicator.CircularProgressIndicator +import com.reco1l.framework.net.Downloader +import ru.nsu.ccfit.zuev.osuplus.R + +class DownloadingFragment : LoadingFragment() { + private lateinit var mDownloader: Downloader + private lateinit var mAwaitCall: Runnable + private lateinit var mButton: Button + private lateinit var mText: TextView + private lateinit var mProgressBar: CircularProgressIndicator + + fun setDownloader(downloader: Downloader, awaitCall: Runnable) { + mAwaitCall = awaitCall + mDownloader = downloader + } + + override val layoutID: Int + get() = R.layout.fragment_downloading + + override fun onLoadView() { + super.onLoadView() + + mText = findViewById(R.id.text)!! + mButton = findViewById(R.id.button)!! + mProgressBar = findViewById(R.id.progress)!! + + mAwaitCall.run() + } + + override fun callDismissOnBackPress() { + if (mDownloader.isDownloading) { + mDownloader.cancel() + return + } + + super.callDismissOnBackPress() + } + + val progressBar: CircularProgressIndicator + get() = mProgressBar + + val button: Button + get() = mButton + + val text: TextView + get() = mText + + fun setText(text: String) { + mText.visibility = if (TextUtils.isEmpty(text)) View.GONE else View.VISIBLE + mText.text = text + } +} \ No newline at end of file diff --git a/src/com/reco1l/legacy/ui/MainMenu.kt b/src/com/reco1l/legacy/ui/MainMenu.kt index 53702898b..55df59fc4 100644 --- a/src/com/reco1l/legacy/ui/MainMenu.kt +++ b/src/com/reco1l/legacy/ui/MainMenu.kt @@ -78,7 +78,7 @@ class MainMenu(val main: MainScene) getGlobal().songService.isGaming = false getGlobal().engine.scene = main.scene - ChimuWebView.INSTANCE.show() + ChimuWebView.show() } else { main.musicControl(MusicOption.PLAY) diff --git a/src/com/reco1l/legacy/ui/entity/BeatmapButton.kt b/src/com/reco1l/legacy/ui/entity/BeatmapButton.kt index 291b78a6d..3ce9e2e89 100644 --- a/src/com/reco1l/legacy/ui/entity/BeatmapButton.kt +++ b/src/com/reco1l/legacy/ui/entity/BeatmapButton.kt @@ -5,8 +5,9 @@ import com.reco1l.api.ibancho.RoomAPI import com.reco1l.api.ibancho.data.PlayerStatus.READY import com.reco1l.api.ibancho.data.RoomBeatmap import com.reco1l.framework.extensions.orAsyncCatch -import com.reco1l.legacy.ui.ChimuWebView.FILE_EXTENSION +import com.reco1l.legacy.ui.ChimuWebView as chimuFragment import com.reco1l.legacy.Multiplayer +import com.reco1l.legacy.ui.ChimuWebView.FILE_EXTENSION import com.reco1l.legacy.ui.multiplayer.RoomScene import org.anddev.andengine.entity.sprite.Sprite import org.anddev.andengine.entity.text.ChangeableText @@ -16,7 +17,6 @@ import ru.nsu.ccfit.zuev.osu.RGBColor import ru.nsu.ccfit.zuev.osu.ToastLogger import ru.nsu.ccfit.zuev.osu.menu.MenuItemTrack import ru.nsu.ccfit.zuev.skins.OsuSkin -import com.reco1l.legacy.ui.ChimuWebView.INSTANCE as chimuFragment import ru.nsu.ccfit.zuev.osu.GlobalManager.getInstance as getGlobal import ru.nsu.ccfit.zuev.osu.LibraryManager.INSTANCE as libraryManager import ru.nsu.ccfit.zuev.osu.ResourceManager.getInstance as getResources @@ -24,7 +24,7 @@ import ru.nsu.ccfit.zuev.osu.ResourceManager.getInstance as getResources /** * Simplified version of [MenuItemTrack] */ -open class BeatmapButton : Sprite(0f, 0f, getResources().getTexture("menu-button-background")) +class BeatmapButton : Sprite(0f, 0f, getResources().getTexture("menu-button-background")) { private val trackTitle = ChangeableText(32f, 20f, getResources().getFont("smallFont"), "", 100) diff --git a/src/com/reco1l/legacy/ui/multiplayer/LobbyScene.kt b/src/com/reco1l/legacy/ui/multiplayer/LobbyScene.kt index 685f3ba1f..6c4c1e130 100644 --- a/src/com/reco1l/legacy/ui/multiplayer/LobbyScene.kt +++ b/src/com/reco1l/legacy/ui/multiplayer/LobbyScene.kt @@ -31,7 +31,7 @@ object LobbyScene : Scene() { /**The search fragment*/ - val search = LobbySearch() + val search by lazy { LobbySearch() } /**The search query*/ var searchQuery: String? = null diff --git a/src/com/reco1l/legacy/ui/multiplayer/RoomScene.kt b/src/com/reco1l/legacy/ui/multiplayer/RoomScene.kt index 8bd99752b..f0409320c 100644 --- a/src/com/reco1l/legacy/ui/multiplayer/RoomScene.kt +++ b/src/com/reco1l/legacy/ui/multiplayer/RoomScene.kt @@ -72,7 +72,7 @@ object RoomScene : Scene(), IRoomEventListener, IPlayerEventListener var awaitModsChange = false - val chat = RoomChat() + val chat: RoomChat val chatPreview = ComposedText(0f, 0f, getResources().getFont("smallFont"), 100) @@ -122,6 +122,7 @@ object RoomScene : Scene(), IRoomEventListener, IPlayerEventListener { RoomAPI.playerEventListener = this RoomAPI.roomEventListener = this + chat = RoomChat() } diff --git a/src/com/rian/difficultycalculator/beatmap/hitobject/Slider.java b/src/com/rian/difficultycalculator/beatmap/hitobject/Slider.java index 1e24257eb..db9b9d237 100644 --- a/src/com/rian/difficultycalculator/beatmap/hitobject/Slider.java +++ b/src/com/rian/difficultycalculator/beatmap/hitobject/Slider.java @@ -12,6 +12,7 @@ import java.util.ArrayList; import java.util.Collections; +import java.util.Comparator; import java.util.List; /** @@ -218,7 +219,7 @@ private Slider(Slider source) { } nestedHitObjects.add(tail); - Collections.sort(nestedHitObjects, (o1, o2) -> Double.compare(o1.startTime, o2.startTime)); + Collections.sort(nestedHitObjects, (a, b) -> Double.compare(a.startTime, b.startTime)); } @Override diff --git a/src/com/rian/difficultycalculator/evaluators/RhythmEvaluator.java b/src/com/rian/difficultycalculator/evaluators/RhythmEvaluator.java index 22787b984..df91a9212 100644 --- a/src/com/rian/difficultycalculator/evaluators/RhythmEvaluator.java +++ b/src/com/rian/difficultycalculator/evaluators/RhythmEvaluator.java @@ -119,7 +119,6 @@ public static double evaluateDifficultyOf(DifficultyHitObject current, double gr // Begin counting island until we change speed again. firstDeltaSwitch = true; startRatio = effectiveRatio; - islandSize = 1; } } diff --git a/src/com/rian/difficultycalculator/utils/PathApproximator.java b/src/com/rian/difficultycalculator/utils/PathApproximator.java index dbae1ac3f..534d8a872 100644 --- a/src/com/rian/difficultycalculator/utils/PathApproximator.java +++ b/src/com/rian/difficultycalculator/utils/PathApproximator.java @@ -129,7 +129,7 @@ public static ArrayList approximateCircularArc(List controlPoi } // See: https://en.wikipedia.org/wiki/Circumscribed_circle#Cartesian_coordinates_2 - float d = 2 * (float) (a.x * b.subtract(c).y + b.x * c.subtract(a).y + c.x * a.subtract(b).y); + float d = 2 * (a.x * b.subtract(c).y + b.x * c.subtract(a).y + c.x * a.subtract(b).y); float aSq = a.getLengthSquared(); float bSq = b.getLengthSquared(); float cSq = c.getLengthSquared(); diff --git a/src/net/margaritov/preference/colorpicker/AlphaPatternDrawable.java b/src/net/margaritov/preference/colorpicker/AlphaPatternDrawable.java index 44fc9ac3a..93ba51e68 100644 --- a/src/net/margaritov/preference/colorpicker/AlphaPatternDrawable.java +++ b/src/net/margaritov/preference/colorpicker/AlphaPatternDrawable.java @@ -81,8 +81,8 @@ protected void onBoundsChange(Rect bounds) { int height = bounds.height(); int width = bounds.width(); - numRectanglesHorizontal = (int) Math.ceil((width / mRectangleSize)); - numRectanglesVertical = (int) Math.ceil(height / mRectangleSize); + numRectanglesHorizontal = (int) Math.ceil(((double) width / mRectangleSize)); + numRectanglesVertical = (int) Math.ceil((double) height / mRectangleSize); generatePatternBitmap(); diff --git a/src/net/margaritov/preference/colorpicker/ColorPickerDialog.java b/src/net/margaritov/preference/colorpicker/ColorPickerDialog.java index a2ff7f392..195c659cb 100644 --- a/src/net/margaritov/preference/colorpicker/ColorPickerDialog.java +++ b/src/net/margaritov/preference/colorpicker/ColorPickerDialog.java @@ -104,37 +104,33 @@ private void setUp(int color) { setTitle(mTitle); - mColorPicker = (ColorPickerView) mLayout.findViewById(R.id.color_picker_view); - mOldColor = (ColorPickerPanelView) mLayout.findViewById(R.id.old_color_panel); - mNewColor = (ColorPickerPanelView) mLayout.findViewById(R.id.new_color_panel); + mColorPicker = mLayout.findViewById(R.id.color_picker_view); + mOldColor = mLayout.findViewById(R.id.old_color_panel); + mNewColor = mLayout.findViewById(R.id.new_color_panel); - mHexVal = (EditText) mLayout.findViewById(R.id.hex_val); + mHexVal = mLayout.findViewById(R.id.hex_val); mHexVal.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); mHexDefaultTextColor = mHexVal.getTextColors(); - mHexVal.setOnEditorActionListener(new TextView.OnEditorActionListener() { - - @Override - public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { - if (actionId == EditorInfo.IME_ACTION_DONE) { - InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); - imm.hideSoftInputFromWindow(v.getWindowToken(), 0); - String s = mHexVal.getText().toString(); - if (s.length() > 5 || s.length() < 10) { - try { - int c = ColorPickerPreference.convertToColorInt(s.toString()); - mColorPicker.setColor(c, true); - mHexVal.setTextColor(mHexDefaultTextColor); - } catch (IllegalArgumentException e) { - mHexVal.setTextColor(Color.RED); - } - } else { + mHexVal.setOnEditorActionListener((v, actionId, event) -> { + if (actionId == EditorInfo.IME_ACTION_DONE) { + InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); + imm.hideSoftInputFromWindow(v.getWindowToken(), 0); + String s = mHexVal.getText().toString(); + if (s.length() > 5 || s.length() < 10) { + try { + int c = ColorPickerPreference.convertToColorInt(s); + mColorPicker.setColor(c, true); + mHexVal.setTextColor(mHexDefaultTextColor); + } catch (IllegalArgumentException e) { mHexVal.setTextColor(Color.RED); } - return true; + } else { + mHexVal.setTextColor(Color.RED); } - return false; + return true; } + return false; }); ((LinearLayout) mOldColor.getParent()).setPadding( diff --git a/src/net/margaritov/preference/colorpicker/ColorPickerPanelView.java b/src/net/margaritov/preference/colorpicker/ColorPickerPanelView.java index 6a211b258..4488e1038 100644 --- a/src/net/margaritov/preference/colorpicker/ColorPickerPanelView.java +++ b/src/net/margaritov/preference/colorpicker/ColorPickerPanelView.java @@ -77,10 +77,8 @@ protected void onDraw(Canvas canvas) { final RectF rect = mColorRect; - if (BORDER_WIDTH_PX > 0) { - mBorderPaint.setColor(mBorderColor); - canvas.drawRect(mDrawingRect, mBorderPaint); - } + mBorderPaint.setColor(mBorderColor); + canvas.drawRect(mDrawingRect, mBorderPaint); if (mAlphaPattern != null) { mAlphaPattern.draw(canvas); diff --git a/src/net/margaritov/preference/colorpicker/ColorPickerPreference.java b/src/net/margaritov/preference/colorpicker/ColorPickerPreference.java index 0ce5a8c46..628df46fa 100644 --- a/src/net/margaritov/preference/colorpicker/ColorPickerPreference.java +++ b/src/net/margaritov/preference/colorpicker/ColorPickerPreference.java @@ -109,7 +109,7 @@ public void onBindViewHolder(PreferenceViewHolder holder) { private void setPreviewColor() { if (mView == null) return; ImageView iView = new ImageView(getContext()); - LinearLayout widgetFrameView = ((LinearLayout) mView.findViewById(android.R.id.widget_frame)); + LinearLayout widgetFrameView = mView.findViewById(android.R.id.widget_frame); if (widgetFrameView == null) return; widgetFrameView.setVisibility(View.VISIBLE); widgetFrameView.setPadding( @@ -291,7 +291,7 @@ protected Parcelable onSaveInstanceState() { @Override protected void onRestoreInstanceState(Parcelable state) { - if (state == null || !(state instanceof SavedState)) { + if (!(state instanceof SavedState)) { // Didn't save state for us in onSaveInstanceState super.onRestoreInstanceState(state); return; @@ -322,7 +322,7 @@ public SavedState(Parcelable superState) { @SuppressWarnings("unused") public static final Parcelable.Creator CREATOR = - new Parcelable.Creator() { + new Parcelable.Creator<>() { public SavedState createFromParcel(Parcel in) { return new SavedState(in); } diff --git a/src/net/margaritov/preference/colorpicker/ColorPickerView.java b/src/net/margaritov/preference/colorpicker/ColorPickerView.java index f52760d79..4494012da 100644 --- a/src/net/margaritov/preference/colorpicker/ColorPickerView.java +++ b/src/net/margaritov/preference/colorpicker/ColorPickerView.java @@ -233,10 +233,8 @@ private void drawSatValPanel(Canvas canvas) { final RectF rect = mSatValRect; - if (BORDER_WIDTH_PX > 0) { - mBorderPaint.setColor(mBorderColor); - canvas.drawRect(mDrawingRect.left, mDrawingRect.top, rect.right + BORDER_WIDTH_PX, rect.bottom + BORDER_WIDTH_PX, mBorderPaint); - } + mBorderPaint.setColor(mBorderColor); + canvas.drawRect(mDrawingRect.left, mDrawingRect.top, rect.right + BORDER_WIDTH_PX, rect.bottom + BORDER_WIDTH_PX, mBorderPaint); if (mValShader == null) { mValShader = new LinearGradient(rect.left, rect.top, rect.left, rect.bottom, @@ -255,7 +253,7 @@ private void drawSatValPanel(Canvas canvas) { Point p = satValToPoint(mSat, mVal); mSatValTrackerPaint.setColor(0xff000000); - canvas.drawCircle(p.x, p.y, PALETTE_CIRCLE_TRACKER_RADIUS - 1f * mDensity, mSatValTrackerPaint); + canvas.drawCircle(p.x, p.y, PALETTE_CIRCLE_TRACKER_RADIUS - mDensity, mSatValTrackerPaint); mSatValTrackerPaint.setColor(0xffdddddd); canvas.drawCircle(p.x, p.y, PALETTE_CIRCLE_TRACKER_RADIUS, mSatValTrackerPaint); @@ -266,14 +264,12 @@ private void drawHuePanel(Canvas canvas) { final RectF rect = mHueRect; - if (BORDER_WIDTH_PX > 0) { - mBorderPaint.setColor(mBorderColor); - canvas.drawRect(rect.left - BORDER_WIDTH_PX, - rect.top - BORDER_WIDTH_PX, - rect.right + BORDER_WIDTH_PX, - rect.bottom + BORDER_WIDTH_PX, - mBorderPaint); - } + mBorderPaint.setColor(mBorderColor); + canvas.drawRect(rect.left - BORDER_WIDTH_PX, + rect.top - BORDER_WIDTH_PX, + rect.right + BORDER_WIDTH_PX, + rect.bottom + BORDER_WIDTH_PX, + mBorderPaint); if (mHueShader == null) { mHueShader = new LinearGradient(rect.left, rect.top, rect.left, rect.bottom, buildHueColorArray(), null, TileMode.CLAMP); @@ -303,14 +299,12 @@ private void drawAlphaPanel(Canvas canvas) { final RectF rect = mAlphaRect; - if (BORDER_WIDTH_PX > 0) { - mBorderPaint.setColor(mBorderColor); - canvas.drawRect(rect.left - BORDER_WIDTH_PX, - rect.top - BORDER_WIDTH_PX, - rect.right + BORDER_WIDTH_PX, - rect.bottom + BORDER_WIDTH_PX, - mBorderPaint); - } + mBorderPaint.setColor(mBorderColor); + canvas.drawRect(rect.left - BORDER_WIDTH_PX, + rect.top - BORDER_WIDTH_PX, + rect.right + BORDER_WIDTH_PX, + rect.bottom + BORDER_WIDTH_PX, + mBorderPaint); mAlphaPattern.draw(canvas); @@ -327,7 +321,7 @@ private void drawAlphaPanel(Canvas canvas) { canvas.drawRect(rect, mAlphaPaint); - if (mAlphaSliderText != null && mAlphaSliderText != "") { + if (mAlphaSliderText != null && !mAlphaSliderText.equals("")) { canvas.drawText(mAlphaSliderText, rect.centerX(), rect.centerY() + 4 * mDensity, mAlphaTextPaint); } diff --git a/src/ru/nsu/ccfit/zuev/audio/effect/Metronome.java b/src/ru/nsu/ccfit/zuev/audio/effect/Metronome.java index b8c865552..99729cb1b 100644 --- a/src/ru/nsu/ccfit/zuev/audio/effect/Metronome.java +++ b/src/ru/nsu/ccfit/zuev/audio/effect/Metronome.java @@ -6,14 +6,13 @@ public class Metronome { - private ResourceManager resources = ResourceManager.getInstance(); + private final ResourceManager resources = ResourceManager.getInstance(); - private BassSoundProvider kickSound = resources.getSound("nightcore-kick"); - private BassSoundProvider finishSound = resources.getSound("nightcore-finish"); - private BassSoundProvider clapSound = resources.getSound("nightcore-clap"); - private BassSoundProvider hatSound = resources.getSound("nightcore-hat"); + private final BassSoundProvider kickSound = resources.getSound("nightcore-kick"); + private final BassSoundProvider finishSound = resources.getSound("nightcore-finish"); + private final BassSoundProvider clapSound = resources.getSound("nightcore-clap"); + private final BassSoundProvider hatSound = resources.getSound("nightcore-hat"); - private float volume = 1.0f; private int lastBeatIndex = -1; public void update(float elapsedTime) { @@ -36,23 +35,23 @@ public void update(float elapsedTime) { // 每隔8小节在第4拍kick+finish if (beatIndex % (8 * GameHelper.getTimeSignature()) == 0) { - kickSound.play(volume); + kickSound.play(); if (beatIndex > 0) { - finishSound.play(volume); + finishSound.play(); } return; } // 每小节第4拍kick if (beatInBar % 4 == 0) { - kickSound.play(volume); + kickSound.play(); return; } // 每小节第2拍clap if (beatInBar % 4 == 2) { - clapSound.play(volume); + clapSound.play(); return; } // 每小节奇数拍hat - hatSound.play(volume); + hatSound.play(); } } diff --git a/src/ru/nsu/ccfit/zuev/audio/serviceAudio/SongService.java b/src/ru/nsu/ccfit/zuev/audio/serviceAudio/SongService.java index 6390fd808..7af064be3 100644 --- a/src/ru/nsu/ccfit/zuev/audio/serviceAudio/SongService.java +++ b/src/ru/nsu/ccfit/zuev/audio/serviceAudio/SongService.java @@ -77,7 +77,7 @@ public boolean preLoad(String filePath, PlayMode mode, boolean isLoop) { if (checkFileExist(filePath)) { if (audioFunc == null) return false; if (isLoop) { - audioFunc.setLoop(isLoop); + audioFunc.setLoop(true); } return audioFunc.preLoad(filePath, mode); } @@ -245,7 +245,7 @@ public void setReceiverStuff(BroadcastReceiver receiver, IntentFilter filter) { public boolean checkFileExist(String path) { if (path == null) return false; - if (path.trim().equals("")) return false; + if (path.trim().isEmpty()) return false; else { File songFile = new File(path); if (!songFile.exists()) return false; diff --git a/src/ru/nsu/ccfit/zuev/osu/AppException.java b/src/ru/nsu/ccfit/zuev/osu/AppException.java index a5b3ed576..e74eb2b21 100644 --- a/src/ru/nsu/ccfit/zuev/osu/AppException.java +++ b/src/ru/nsu/ccfit/zuev/osu/AppException.java @@ -211,7 +211,7 @@ public void saveErrorLog(String excpMessage) { logFilePath = savePath + errorlog; } // 没有挂载SD卡,无法写文件 - if (logFilePath.equals("")) { + if (logFilePath.isEmpty()) { return; } File logFile = new File(logFilePath); @@ -340,7 +340,7 @@ public String collectDeviceInfo(Context ctx) { PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(), PackageManager.GET_ACTIVITIES); if (pi != null) { String versionName = pi.versionName == null ? "null" : pi.versionName; - String versionCode = pi.versionCode + ""; + String versionCode = String.valueOf(pi.versionCode); activePackageJson.put("versionName", versionName); activePackageJson.put("versionCode", versionCode); diff --git a/src/ru/nsu/ccfit/zuev/osu/BeatmapInfo.java b/src/ru/nsu/ccfit/zuev/osu/BeatmapInfo.java index 0ca746ea8..c9b343df1 100644 --- a/src/ru/nsu/ccfit/zuev/osu/BeatmapInfo.java +++ b/src/ru/nsu/ccfit/zuev/osu/BeatmapInfo.java @@ -5,7 +5,7 @@ public class BeatmapInfo implements Serializable { private static final long serialVersionUID = -3865268984942011628L; - private final ArrayList tracks = new ArrayList(); + private final ArrayList tracks = new ArrayList<>(); private String title; private String titleUnicode; private String artist; diff --git a/src/ru/nsu/ccfit/zuev/osu/Config.java b/src/ru/nsu/ccfit/zuev/osu/Config.java index 3df3d905f..1b3997769 100644 --- a/src/ru/nsu/ccfit/zuev/osu/Config.java +++ b/src/ru/nsu/ccfit/zuev/osu/Config.java @@ -684,7 +684,7 @@ public static float getCursorSize() { return cursorSize; } - public static void setCursorSize() { + public static void setCursorSize(final float cursorSize) { Config.cursorSize = cursorSize; } @@ -750,7 +750,7 @@ public static String getDefaultCorePath() { public static void loadSkins() { File[] folders = FileUtils.listFiles(new File(skinTopPath), file -> file.isDirectory() && !file.getName().startsWith(".")); - skins = new HashMap(); + skins = new HashMap<>(); for(File folder : folders) { skins.put(folder.getName(), folder.getPath()); Debug.i("skins: " + folder.getName() + " - " + folder.getPath()); @@ -762,7 +762,7 @@ public static Map getSkins(){ } public static void addSkin(String name, String path) { - if(skins == null) skins = new HashMap(); + if(skins == null) skins = new HashMap<>(); skins.put(name, path); } diff --git a/src/ru/nsu/ccfit/zuev/osu/LibraryManager.java b/src/ru/nsu/ccfit/zuev/osu/LibraryManager.java index 3adfcfca2..e54c42342 100644 --- a/src/ru/nsu/ccfit/zuev/osu/LibraryManager.java +++ b/src/ru/nsu/ccfit/zuev/osu/LibraryManager.java @@ -36,9 +36,7 @@ public boolean loadLibraryCache(boolean forceUpdate) { library.clear(); } - ToastLogger.addToLog("Loading library..."); if (!FileUtils.canUseSD()) { - ToastLogger.addToLog("Can't use SD card!"); return true; } @@ -84,7 +82,6 @@ public boolean loadLibraryCache(boolean forceUpdate) { library.addAll((Collection) obj); } - ToastLogger.addToLog("Library loaded"); if (forceUpdate) { checkLibrary(); } @@ -95,7 +92,6 @@ public boolean loadLibraryCache(boolean forceUpdate) { } catch (final IOException | ClassNotFoundException | ClassCastException e) { Debug.e("LibraryManager: " + e.getMessage(), e); } - ToastLogger.addToLog("Cannot load library!"); return false; } @@ -127,7 +123,6 @@ private void checkLibrary() { } public synchronized void scanLibrary() { - ToastLogger.addToLog("Caching library..."); library.clear(); final File dir = new File(Config.getBeatmapPath()); @@ -245,13 +240,13 @@ public void clearCache() { private static void fillEmptyFields(BeatmapInfo info) { info.setCreator(info.getTrack(0).getCreator()); - if (info.getTitle().equals("")) { + if (info.getTitle().isEmpty()) { info.setTitle("unknown"); } - if (info.getArtist().equals("")) { + if (info.getArtist().isEmpty()) { info.setArtist("unknown"); } - if (info.getCreator().equals("")) { + if (info.getCreator().isEmpty()) { info.setCreator("unknown"); } } diff --git a/src/ru/nsu/ccfit/zuev/osu/MainActivity.java b/src/ru/nsu/ccfit/zuev/osu/MainActivity.java index d3d63db86..0450d04d3 100644 --- a/src/ru/nsu/ccfit/zuev/osu/MainActivity.java +++ b/src/ru/nsu/ccfit/zuev/osu/MainActivity.java @@ -6,7 +6,6 @@ import android.content.ComponentName; import android.content.ContentResolver; import android.content.Context; -import android.content.DialogInterface; import android.content.Intent; import android.content.ServiceConnection; import android.content.SharedPreferences; @@ -42,14 +41,15 @@ import com.edlplan.ui.ActivityOverlay; import com.google.firebase.analytics.FirebaseAnalytics; import com.google.firebase.crashlytics.FirebaseCrashlytics; - import com.reco1l.api.ibancho.LobbyAPI; import com.reco1l.framework.lang.Execution; +import com.reco1l.framework.lang.execution.Async; +import com.reco1l.legacy.AccessibilityDetector; +import com.reco1l.legacy.Multiplayer; import com.reco1l.legacy.UpdateManager; import com.reco1l.legacy.ui.multiplayer.LobbyScene; -import com.reco1l.legacy.Multiplayer; import com.reco1l.legacy.ui.multiplayer.RoomScene; -import com.reco1l.legacy.AccessibilityDetector; + import net.lingala.zip4j.ZipFile; import org.anddev.andengine.engine.Engine; @@ -73,6 +73,7 @@ import java.math.RoundingMode; import java.text.DecimalFormat; import java.util.ArrayList; +import java.util.Objects; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; @@ -80,14 +81,12 @@ import ru.nsu.ccfit.zuev.audio.BassAudioPlayer; import ru.nsu.ccfit.zuev.audio.serviceAudio.SaveServiceObject; import ru.nsu.ccfit.zuev.audio.serviceAudio.SongService; -import ru.nsu.ccfit.zuev.osu.async.AsyncTask; import ru.nsu.ccfit.zuev.osu.async.SyncTaskManager; import ru.nsu.ccfit.zuev.osu.game.SpritePool; import ru.nsu.ccfit.zuev.osu.helper.BeatmapDifficultyCalculator; import ru.nsu.ccfit.zuev.osu.helper.FileUtils; import ru.nsu.ccfit.zuev.osu.helper.InputManager; import ru.nsu.ccfit.zuev.osu.helper.StringTable; -import ru.nsu.ccfit.zuev.osu.menu.FilterMenu; import ru.nsu.ccfit.zuev.osu.menu.LoadingScreen; import ru.nsu.ccfit.zuev.osu.menu.ModMenu; import ru.nsu.ccfit.zuev.osu.menu.SplashScene; @@ -99,7 +98,6 @@ public class MainActivity extends BaseGameActivity implements IAccelerometerListener { public static String versionName; - public static SongService songService; public ServiceConnection connection; private PowerManager.WakeLock wakeLock = null; @@ -183,7 +181,7 @@ private void initialGameDirectory() { dir = new File(Config.getBeatmapPath()); if (!(dir.exists() || dir.mkdirs())) { ToastLogger.showText(StringTable.format( - R.string.message_error_createdir, dir.getPath()), + R.string.message_error_createdir, dir.getPath()), true); } else { final SharedPreferences prefs = PreferenceManager @@ -213,7 +211,7 @@ private void initPreferences() { final SharedPreferences prefs = PreferenceManager .getDefaultSharedPreferences(this); - if (prefs.getString("playername", "").equals("")) { + if (Objects.equals(prefs.getString("playername", ""), "")) { final SharedPreferences.Editor editor = prefs.edit(); editor.putString("playername", "Guest"); editor.commit(); @@ -229,20 +227,16 @@ private void initPreferences() { alert.setView(input); alert.setPositiveButton(StringTable.get(R.string.dialog_ok), - new DialogInterface.OnClickListener() { - - public void onClick(final DialogInterface dialog, - final int whichButton) { - final String value = input.getText().toString(); - editor.putString("playername", value); - editor.commit(); - } + (dialog, whichButton) -> { + final String value = input.getText().toString(); + editor.putString("playername", value); + editor.commit(); }); alert.show(); } - if (prefs.getBoolean("qualitySet", false) == false) { + if (!prefs.getBoolean("qualitySet", false)) { final SharedPreferences.Editor editor = prefs.edit(); editor.putBoolean("qualitySet", true); final DisplayMetrics dm = new DisplayMetrics(); @@ -256,7 +250,7 @@ public void onClick(final DialogInterface dialog, editor.commit(); } - if (prefs.getBoolean("onlineSet", false) == false) { + if (!prefs.getBoolean("onlineSet", false)) { Editor editor = prefs.edit(); editor.putBoolean("onlineSet", true); @@ -325,56 +319,52 @@ public void onLoadComplete() { LobbyScene.INSTANCE.init(); RoomScene.INSTANCE.init(); - new AsyncTask() { - @Override - public void run() { - BassAudioPlayer.initDevice(); - GlobalManager.getInstance().init(); - analytics.logEvent(FirebaseAnalytics.Event.APP_OPEN, null); - GlobalManager.getInstance().setLoadingProgress(50); - checkNewSkins(); - Config.loadSkins(); - checkNewBeatmaps(); - if (!LibraryManager.INSTANCE.loadLibraryCache(true)) { - LibraryManager.INSTANCE.scanLibrary(); - System.gc(); - } - SplashScene.INSTANCE.playWelcomeAnimation(); - try { - // Allow the welcome animation to progress before entering onComplete state. - Thread.sleep(2500); - } - catch (InterruptedException ignored) {} - UpdateManager.INSTANCE.onActivityStart(); + Async.run(() -> { + BassAudioPlayer.initDevice(); + GlobalManager.getInstance().init(); + analytics.logEvent(FirebaseAnalytics.Event.APP_OPEN, null); + GlobalManager.getInstance().setLoadingProgress(50); + checkNewSkins(); + Config.loadSkins(); + checkNewBeatmaps(); + + if (!LibraryManager.INSTANCE.loadLibraryCache(true)) { + LibraryManager.INSTANCE.scanLibrary(); } - @Override - public void onComplete() { - GlobalManager.getInstance().setInfo(""); - GlobalManager.getInstance().setLoadingProgress(100); - ResourceManager.getInstance().loadFont("font", null, 28, Color.WHITE); - GlobalManager.getInstance().getEngine().setScene(GlobalManager.getInstance().getMainScene().getScene()); - GlobalManager.getInstance().getMainScene().loadBeatmap(); - initPreferences(); - availableInternalMemory(); - - scheduledExecutor.scheduleAtFixedRate(() -> { - AccessibilityDetector.check(MainActivity.this); - BeatmapDifficultyCalculator.invalidateExpiredCache(); - }, 0, 1000, TimeUnit.MILLISECONDS); - - if (roomInviteLink != null) { - LobbyScene.INSTANCE.connectFromLink(roomInviteLink); - return; - } + SplashScene.INSTANCE.playWelcomeAnimation(); - if (willReplay) { - GlobalManager.getInstance().getMainScene().watchReplay(beatmapToAdd); - willReplay = false; - } + try { + Thread.sleep(2500); + } catch (InterruptedException ignored) { } - }.execute(); + + UpdateManager.INSTANCE.onActivityStart(); + GlobalManager.getInstance().setInfo(""); + GlobalManager.getInstance().setLoadingProgress(100); + ResourceManager.getInstance().loadFont("font", null, 28, Color.WHITE); + GlobalManager.getInstance().getEngine().setScene(GlobalManager.getInstance().getMainScene().getScene()); + GlobalManager.getInstance().getMainScene().loadBeatmap(); + initPreferences(); + availableInternalMemory(); + + scheduledExecutor.scheduleAtFixedRate(() -> { + AccessibilityDetector.check(MainActivity.this); + BeatmapDifficultyCalculator.invalidateExpiredCache(); + }, 0, 100, TimeUnit.MILLISECONDS); + + if (roomInviteLink != null) { + LobbyScene.INSTANCE.connectFromLink(roomInviteLink); + return; + } + + if (willReplay) { + GlobalManager.getInstance().getMainScene().watchReplay(beatmapToAdd); + willReplay = false; + } + }); } + /* Accuracy isn't the best, but it's sufficient enough to determine whether storage is low or not @@ -389,7 +379,7 @@ private void availableInternalMemory() { StatFs stat = new StatFs(internal.getPath()); availableMemory = (double) stat.getAvailableBytes(); String toastMessage = String.format(StringTable.get(R.string.message_low_storage_space), df.format(availableMemory / minMem)); - if(availableMemory < 0.5 * minMem) { //I set 512MiB as a minimum + if (availableMemory < 0.5 * minMem) { //I set 512MiB as a minimum Toast.makeText(this, toastMessage, Toast.LENGTH_SHORT).show(); } Debug.i("Free Space: " + df.format(availableMemory / minMem)); @@ -399,8 +389,8 @@ private void availableInternalMemory() { @Override protected void onSetContentView() { this.mRenderSurfaceView = new RenderSurfaceView(this); - if(Config.isUseDither()) { - this.mRenderSurfaceView.setEGLConfigChooser(8,8,8,8,24,0); + if (Config.isUseDither()) { + this.mRenderSurfaceView.setEGLConfigChooser(8, 8, 8, 8, 24, 0); this.mRenderSurfaceView.getHolder().setFormat(PixelFormat.RGBA_8888); } else { this.mRenderSurfaceView.setEGLConfigChooser(true); @@ -413,7 +403,7 @@ protected void onSetContentView() { mRenderSurfaceView, new RelativeLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, - ViewGroup.LayoutParams.MATCH_PARENT){{ + ViewGroup.LayoutParams.MATCH_PARENT) {{ addRule(RelativeLayout.CENTER_IN_PARENT); }}); @@ -458,7 +448,8 @@ public void checkNewBeatmaps() { if (zip.isValidZipFile()) { beatmaps.add(file.getPath()); } - } catch (IOException ignored) {} + } catch (IOException ignored) { + } } File beatmapDir = new File(Config.getBeatmapPath()); @@ -470,7 +461,8 @@ public void checkNewBeatmaps() { if (zip.isValidZipFile()) { beatmaps.add(file.getPath()); } - } catch (IOException ignored) {} + } catch (IOException ignored) { + } } } @@ -484,7 +476,8 @@ public void checkNewBeatmaps() { if (zip.isValidZipFile()) { beatmaps.add(file.getPath()); } - } catch (IOException ignored) {} + } catch (IOException ignored) { + } } } @@ -521,7 +514,8 @@ public void checkNewSkins() { if (zip.isValidZipFile()) { skins.add(file.getPath()); } - } catch (IOException ignored) {} + } catch (IOException ignored) { + } } } @@ -538,7 +532,8 @@ public void checkNewSkins() { if (zip.isValidZipFile()) { skins.add(file.getPath()); } - } catch (IOException ignored) {} + } catch (IOException ignored) { + } } } @@ -582,8 +577,8 @@ protected void onCreate(Bundle pSavedInstanceState) { try { versionName = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_ACTIVITIES).versionName; + } catch (Exception ignored) { } - catch (Exception ignored) {} if (this.mEngine == null) { return; @@ -597,7 +592,7 @@ protected void onCreate(Bundle pSavedInstanceState) { File f = new File(d, "rawlog.txt"); if (!f.exists()) f.createNewFile(); Runtime.getRuntime().exec("logcat -f " + (f.getAbsolutePath())); - } catch (IOException e) { + } catch (IOException ignored) { } } onBeginBindService(); @@ -661,7 +656,7 @@ public void onResume() { if (songService.hideNotification()) { if (wakeLock != null && wakeLock.isHeld()) wakeLock.release(); GlobalManager.getInstance().getMainScene().loadBeatmapInfo(); - GlobalManager.getInstance().getMainScene().loadTimeingPoints(false); + GlobalManager.getInstance().getMainScene().loadTimingPoints(false); GlobalManager.getInstance().getMainScene().progressBar.setTime(songService.getLength()); GlobalManager.getInstance().getMainScene().progressBar.setPassedTime(songService.getPosition()); GlobalManager.getInstance().getMainScene().musicControl(MainScene.MusicOption.SYNC); @@ -669,7 +664,7 @@ public void onResume() { } } } - + @Override public void onPause() { super.onPause(); @@ -681,13 +676,11 @@ public void onPause() { && GlobalManager.getInstance().getEngine().getScene() == GlobalManager.getInstance().getGameScene().getScene()) { SpritePool.getInstance().purge(); - if (Multiplayer.isMultiplayer) - { + if (Multiplayer.isMultiplayer) { ToastLogger.showText("You've left the match.", true); GlobalManager.getInstance().getGameScene().quit(); Multiplayer.log("Player left the match."); - } - else GlobalManager.getInstance().getGameScene().pause(); + } else GlobalManager.getInstance().getGameScene().pause(); } if (GlobalManager.getInstance().getMainScene() != null) { BeatmapInfo beatmapInfo = GlobalManager.getInstance().getMainScene().beatmapInfo; @@ -732,20 +725,19 @@ && getEngine().getScene() == GlobalManager.getInstance().getGameScene().getScene if (Multiplayer.isConnected() && (getEngine().getScene() == RoomScene.INSTANCE - || getEngine().getScene() == GlobalManager.getInstance().getSongMenu().getScene())) - { - Execution.asyncIgnoreExceptions(() -> RoomScene.INSTANCE.invalidateStatus()); + || getEngine().getScene() == GlobalManager.getInstance().getSongMenu().getScene())) { + Execution.asyncIgnoreExceptions(RoomScene.INSTANCE::invalidateStatus); } } if (hasFocus && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && Config.isHideNaviBar()) { getWindow().getDecorView().setSystemUiVisibility( - View.SYSTEM_UI_FLAG_LAYOUT_STABLE - | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION - | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN - | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION - | View.SYSTEM_UI_FLAG_FULLSCREEN - | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY); + View.SYSTEM_UI_FLAG_LAYOUT_STABLE + | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION + | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN + | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION + | View.SYSTEM_UI_FLAG_FULLSCREEN + | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY); } } @@ -801,14 +793,12 @@ public boolean onKeyDown(final int keyCode, final KeyEvent event) { && GlobalManager.getInstance().getSongMenu() != null && GlobalManager.getInstance().getEngine().getScene() == GlobalManager.getInstance().getSongMenu().getScene() && GlobalManager.getInstance().getSongMenu().getScene().hasChildScene()) { - if (FilterMenu.getInstance().getClass() == FilterMenu.class) { - if (GlobalManager.getInstance().getSongMenu().getScene().getChildScene() == FilterMenu.getInstance() - .getScene()) { - if (keyCode == KeyEvent.KEYCODE_ENTER) { - InputManager.getInstance().toggleKeyboard(); - } - FilterMenu.getInstance().hideMenu(); + if (GlobalManager.getInstance().getSongMenu().getScene().getChildScene() == + GlobalManager.getInstance().getSongMenu().getFilterMenu().getScene()) { + if (keyCode == KeyEvent.KEYCODE_ENTER) { + InputManager.getInstance().toggleKeyboard(); } + GlobalManager.getInstance().getSongMenu().getFilterMenu().hideMenu(); } if (GlobalManager.getInstance().getSongMenu().getScene().getChildScene() == ModMenu.getInstance().getScene()) { @@ -820,7 +810,7 @@ public boolean onKeyDown(final int keyCode, final KeyEvent event) { if (GlobalManager.getInstance().getSongMenu() != null && GlobalManager.getInstance().getEngine() != null && keyCode == KeyEvent.KEYCODE_MENU && GlobalManager.getInstance().getEngine().getScene() == GlobalManager.getInstance().getSongMenu().getScene() - && GlobalManager.getInstance().getSongMenu().getScene().hasChildScene() == false) { + && !GlobalManager.getInstance().getSongMenu().getScene().hasChildScene()) { GlobalManager.getInstance().getSongMenu().stopScroll(0); GlobalManager.getInstance().getSongMenu().showPropertiesMenu(null); return true; @@ -845,8 +835,7 @@ public boolean onKeyDown(final int keyCode, final KeyEvent event) { if (GlobalManager.getInstance().getEngine().getScene() == RoomScene.INSTANCE) { - if (RoomScene.INSTANCE.hasChildScene() && RoomScene.INSTANCE.getChildScene() == ModMenu.getInstance().getScene()) - { + if (RoomScene.INSTANCE.hasChildScene() && RoomScene.INSTANCE.getChildScene() == ModMenu.getInstance().getScene()) { ModMenu.getInstance().hide(); return true; } @@ -874,7 +863,7 @@ public boolean onKeyDown(final int keyCode, final KeyEvent event) { } public void forcedExit() { - if(GlobalManager.getInstance().getEngine().getScene() == GlobalManager.getInstance().getGameScene().getScene()) { + if (GlobalManager.getInstance().getEngine().getScene() == GlobalManager.getInstance().getGameScene().getScene()) { GlobalManager.getInstance().getGameScene().quit(); } GlobalManager.getInstance().getEngine().setScene(GlobalManager.getInstance().getMainScene().getScene()); @@ -885,10 +874,10 @@ public long getVersionCode() { long versionCode = 0; try { PackageInfo packageInfo = getPackageManager().getPackageInfo( - getPackageName(), 0); - if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { + getPackageName(), 0); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { versionCode = packageInfo.getLongVersionCode(); - }else { + } else { versionCode = packageInfo.versionCode; } } catch (PackageManager.NameNotFoundException e) { @@ -899,17 +888,17 @@ public long getVersionCode() { public float getRefreshRate() { return ((WindowManager) getSystemService(Context.WINDOW_SERVICE)) - .getDefaultDisplay() - .getRefreshRate(); + .getDefaultDisplay() + .getRefreshRate(); } private boolean checkPermissions() { - if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && Environment.isExternalStorageManager()) { return true; - }else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R && + } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R && PermissionChecker.checkCallingOrSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) - == PermissionChecker.PERMISSION_GRANTED) { + == PermissionChecker.PERMISSION_GRANTED) { return true; } else { Intent grantPermission = new Intent(this, PermissionActivity.class); diff --git a/src/ru/nsu/ccfit/zuev/osu/MainScene.java b/src/ru/nsu/ccfit/zuev/osu/MainScene.java index 3f5e8d699..b4ff1730b 100644 --- a/src/ru/nsu/ccfit/zuev/osu/MainScene.java +++ b/src/ru/nsu/ccfit/zuev/osu/MainScene.java @@ -8,9 +8,9 @@ import android.util.Log; import com.edlplan.ui.fragment.ConfirmDialogFragment; - import com.reco1l.legacy.ui.ChimuWebView; import com.reco1l.legacy.ui.MainMenu; + import org.anddev.andengine.engine.handler.IUpdateHandler; import org.anddev.andengine.entity.IEntity; import org.anddev.andengine.entity.modifier.IEntityModifier; @@ -84,14 +84,11 @@ public class MainScene implements IUpdateHandler { private Sprite music_nowplay; private Scene scene; private ChangeableText musicInfoText; - private Random random = new Random(); - private Rectangle[] spectrum = new Rectangle[120]; - private float[] peakLevel = new float[120]; - private float[] peakDownRate = new float[120]; - private float[] peakAlpha = new float[120]; - private Replay replay = null; - private TrackInfo selectedTrack; - private BeatmapData beatmapData; + private final Random random = new Random(); + private final Rectangle[] spectrum = new Rectangle[120]; + private final float[] peakLevel = new float[120]; + private final float[] peakDownRate = new float[120]; + private final float[] peakAlpha = new float[120]; private List timingPoints; private TimingPoint currentTimingPoint, lastTimingPoint, firstTimingPoint; @@ -99,7 +96,7 @@ public class MainScene implements IUpdateHandler { private boolean particleEnabled = false; private boolean isContinuousKiai = false; - private ParticleSystem[] particleSystem = new ParticleSystem[2]; + private final ParticleSystem[] particleSystem = new ParticleSystem[2]; //private BassAudioPlayer music; @@ -113,15 +110,13 @@ public class MainScene implements IUpdateHandler { private float lastBeatPassTime = 0; private boolean doChange = false; private boolean doStop = false; - // private int playIndex = 0; -// private int lastPlayIndex = -1; private long lastHit = 0; public boolean isOnExitAnim = false; private boolean isMenuShowed = false; private boolean doMenuShow = false; private float showPassTime = 0, syncPassedTime = 0; - private float menuBarX = 0, playY, optionsY, exitY; + private float menuBarX = 0, playY, exitY; private MainMenu menu; @@ -132,7 +127,7 @@ public void load(Context context) { scene = new Scene(); final TextureRegion tex = ResourceManager.getInstance().getTexture("menu-background"); - + if (tex != null) { float height = tex.getHeight(); height *= Config.getRES_WIDTH() @@ -149,7 +144,7 @@ public void load(Context context) { } lastBackground = new Sprite(0, 0, Config.getRES_WIDTH(), Config.getRES_HEIGHT(), ResourceManager.getInstance().getTexture("emptyavatar")); final TextureRegion logotex = ResourceManager.getInstance().getTexture("logo"); - logo = new Sprite(Config.getRES_WIDTH() / 2 - logotex.getWidth() / 2, Config.getRES_HEIGHT() / 2 - logotex.getHeight() / 2, logotex) { + logo = new Sprite((float) Config.getRES_WIDTH() / 2 - (float) logotex.getWidth() / 2, (float) Config.getRES_HEIGHT() / 2 - (float) logotex.getHeight() / 2, logotex) { @Override public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { @@ -163,10 +158,10 @@ public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, if (pSceneTouchEvent.isActionUp()) { Debug.i("logo up"); Debug.i("doMenuShow " + doMenuShow + " isMenuShowed " + isMenuShowed + " showPassTime " + showPassTime); - if (doMenuShow == true && isMenuShowed == true) { + if (doMenuShow && isMenuShowed) { showPassTime = 20000; } - if (doMenuShow == false && isMenuShowed == false && logo.getX() == (Config.getRES_WIDTH() - logo.getWidth()) / 2) { + if (!doMenuShow && !isMenuShowed && logo.getX() == (Config.getRES_WIDTH() - logo.getWidth()) / 2) { doMenuShow = true; showPassTime = 0; } @@ -178,7 +173,7 @@ public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, } }; - logoOverlay = new Sprite(Config.getRES_WIDTH() / 2 - logotex.getWidth() / 2, Config.getRES_HEIGHT() / 2 - logotex.getHeight() / 2, logotex); + logoOverlay = new Sprite((float) Config.getRES_WIDTH() / 2 - (float) logotex.getWidth() / 2, (float) Config.getRES_HEIGHT() / 2 - (float) logotex.getHeight() / 2, logotex); logoOverlay.setScale(1.07f); logoOverlay.setAlpha(0.2f); @@ -188,9 +183,9 @@ public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, .getInstance().getFont("font"), String.format( Locale.getDefault(), - "osu!droid %s\nby osu!droid Team\nosu! is \u00a9 peppy 2007-2023", + "osu!droid %s\nby osu!droid Team\nosu! is © peppy 2007-2023", BuildConfig.VERSION_NAME + " (" + BuildConfig.BUILD_TYPE + ")" - )) { + )) { @Override @@ -198,12 +193,12 @@ public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { if (pSceneTouchEvent.isActionDown()) { new ConfirmDialogFragment().setMessage(R.string.dialog_visit_osu_website_message).showForResult( - isAccepted -> { - if(isAccepted) { - Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://osu.ppy.sh")); - GlobalManager.getInstance().getMainActivity().startActivity(browserIntent); + isAccepted -> { + if (isAccepted) { + Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://osu.ppy.sh")); + GlobalManager.getInstance().getMainActivity().startActivity(browserIntent); + } } - } ); return true; } @@ -221,12 +216,12 @@ public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { if (pSceneTouchEvent.isActionDown()) { new ConfirmDialogFragment().setMessage(R.string.dialog_visit_osudroid_website_message).showForResult( - isAccepted -> { - if(isAccepted) { - Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://" + OnlineManager.hostname)); - GlobalManager.getInstance().getMainActivity().startActivity(browserIntent); + isAccepted -> { + if (isAccepted) { + Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://" + OnlineManager.hostname)); + GlobalManager.getInstance().getMainActivity().startActivity(browserIntent); + } } - } ); return true; } @@ -362,7 +357,7 @@ public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, musicInfoText = new ChangeableText(0, 0, ResourceManager.getInstance().getFont("font"), "", HorizontalAlign.RIGHT, 35); final TextureRegion nptex = ResourceManager.getInstance().getTexture("music_np"); - music_nowplay = new Sprite(Utils.toRes(Config.getRES_WIDTH() - 500), 0, 40 * nptex.getWidth() / nptex.getHeight(), 40, nptex); + music_nowplay = new Sprite(Utils.toRes(Config.getRES_WIDTH() - 500), 0, (float) (40 * nptex.getWidth()) / nptex.getHeight(), 40, nptex); final Rectangle bgTopRect = new Rectangle(0, 0, Config.getRES_WIDTH(), Utils.toRes(120)); bgTopRect.setColor(0, 0, 0, 0.3f); @@ -373,8 +368,8 @@ public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, bgbottomRect.setColor(0, 0, 0, 0.3f); for (int i = 0; i < 120; i++) { - final float pX = Config.getRES_WIDTH() / 2; - final float pY = Config.getRES_HEIGHT() / 2; + final float pX = (float) Config.getRES_WIDTH() / 2; + final float pY = (float) Config.getRES_HEIGHT() / 2; spectrum[i] = new Rectangle(pX, pY, 260, 10); spectrum[i].setRotationCenter(0, 5); @@ -390,7 +385,7 @@ public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, TextureRegion starRegion = ResourceManager.getInstance().getTexture("star"); { - particleSystem[0] = new ParticleSystem(new PointParticleEmitter(-40, Config.getRES_HEIGHT() * 3 / 4), 32, 48, 128, starRegion); + particleSystem[0] = new ParticleSystem(new PointParticleEmitter(-40, (float) (Config.getRES_HEIGHT() * 3) / 4), 32, 48, 128, starRegion); particleSystem[0].setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); particleSystem[0].addParticleInitializer(new VelocityInitializer(150, 430, -480, -520)); @@ -407,7 +402,7 @@ public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, } { - particleSystem[1] = new ParticleSystem(new PointParticleEmitter(Config.getRES_WIDTH(), Config.getRES_HEIGHT() * 3 / 4), 32, 48, 128, starRegion); + particleSystem[1] = new ParticleSystem(new PointParticleEmitter(Config.getRES_WIDTH(), (float) (Config.getRES_HEIGHT() * 3) / 4), 32, 48, 128, starRegion); particleSystem[1].setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); particleSystem[1].addParticleInitializer(new VelocityInitializer(-150, -430, -480, -520)); @@ -424,19 +419,15 @@ public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, } TextureRegion chimuTex = ResourceManager.getInstance().getTexture("chimu"); - Sprite chimu = new Sprite(Config.getRES_WIDTH() - chimuTex.getWidth(), (Config.getRES_HEIGHT() - chimuTex.getHeight()) / 2f, chimuTex) - { - public boolean onAreaTouched(TouchEvent pSceneTouchEvent, float pTouchAreaLocalX, float pTouchAreaLocalY) - { - if (pSceneTouchEvent.isActionDown()) - { + Sprite chimu = new Sprite(Config.getRES_WIDTH() - chimuTex.getWidth(), (Config.getRES_HEIGHT() - chimuTex.getHeight()) / 2f, chimuTex) { + public boolean onAreaTouched(TouchEvent pSceneTouchEvent, float pTouchAreaLocalX, float pTouchAreaLocalY) { + if (pSceneTouchEvent.isActionDown()) { setColor(0.7f, 0.7f, 0.7f); doStop = true; return true; } - if (pSceneTouchEvent.isActionUp()) - { + if (pSceneTouchEvent.isActionUp()) { setColor(1, 1, 1); musicControl(MusicOption.STOP); ChimuWebView.INSTANCE.show(); @@ -541,7 +532,7 @@ public void musicControl(MusicOption option) { firstTimingPoint = null; LibraryManager.INSTANCE.getPrevBeatmap(); loadBeatmapInfo(); - loadTimeingPoints(true); + loadTimingPoints(true); doChange = false; doStop = false; } @@ -549,7 +540,7 @@ public void musicControl(MusicOption option) { case PLAY: { if (GlobalManager.getInstance().getSongService().getStatus() == Status.PAUSED || GlobalManager.getInstance().getSongService().getStatus() == Status.STOPPED) { if (GlobalManager.getInstance().getSongService().getStatus() == Status.STOPPED) { - loadTimeingPoints(false); + loadTimingPoints(false); GlobalManager.getInstance().getSongService().preLoad(beatmapInfo.getMusic()); if (firstTimingPoint != null) { bpmLength = firstTimingPoint.getBeatLength() * 1000f; @@ -597,7 +588,7 @@ public void musicControl(MusicOption option) { LibraryManager.INSTANCE.getNextBeatmap(); firstTimingPoint = null; loadBeatmapInfo(); - loadTimeingPoints(true); + loadTimingPoints(true); doChange = false; doStop = false; } @@ -630,11 +621,11 @@ public void onUpdate(final float pSecondsElapsed) { offset = 0; } - if (doMenuShow == true && isMenuShowed == false) { - logo.registerEntityModifier(new MoveXModifier(0.3f, Config.getRES_WIDTH() / 2 - logo.getWidth() / 2, Config.getRES_WIDTH() / 3 - logo.getWidth() / 2, EaseExponentialOut.getInstance())); - logoOverlay.registerEntityModifier(new MoveXModifier(0.3f, Config.getRES_WIDTH() / 2 - logo.getWidth() / 2, Config.getRES_WIDTH() / 3 - logo.getWidth() / 2, EaseExponentialOut.getInstance())); - for (int i = 0; i < spectrum.length; i++) { - spectrum[i].registerEntityModifier(new MoveXModifier(0.3f, Config.getRES_WIDTH() / 2, Config.getRES_WIDTH() / 3, EaseExponentialOut.getInstance())); + if (doMenuShow && !isMenuShowed) { + logo.registerEntityModifier(new MoveXModifier(0.3f, (float) Config.getRES_WIDTH() / 2 - logo.getWidth() / 2, (float) Config.getRES_WIDTH() / 3 - logo.getWidth() / 2, EaseExponentialOut.getInstance())); + logoOverlay.registerEntityModifier(new MoveXModifier(0.3f, (float) Config.getRES_WIDTH() / 2 - logo.getWidth() / 2, (float) Config.getRES_WIDTH() / 3 - logo.getWidth() / 2, EaseExponentialOut.getInstance())); + for (Rectangle rectangle : spectrum) { + rectangle.registerEntityModifier(new MoveXModifier(0.3f, (float) Config.getRES_WIDTH() / 2, (float) Config.getRES_WIDTH() / 3, EaseExponentialOut.getInstance())); } menu.getFirst().registerEntityModifier(new ParallelEntityModifier( new MoveXModifier(0.5f, menuBarX - 100, menuBarX, EaseElasticOut.getInstance()), @@ -651,7 +642,7 @@ public void onUpdate(final float pSecondsElapsed) { isMenuShowed = true; } - if (doMenuShow == true && isMenuShowed == true) { + if (doMenuShow) { if (showPassTime > 10000f) { menu.showFirstMenu(); @@ -669,12 +660,12 @@ public void onUpdate(final float pSecondsElapsed) { new MoveXModifier(1f, menuBarX, menuBarX - 50, EaseExponentialOut.getInstance()), new org.anddev.andengine.entity.modifier.AlphaModifier(1f, 0.9f, 0, EaseExponentialOut.getInstance()))); - logo.registerEntityModifier(new MoveXModifier(1f, Config.getRES_WIDTH() / 3 - logo.getWidth() / 2, Config.getRES_WIDTH() / 2 - logo.getWidth() / 2, + logo.registerEntityModifier(new MoveXModifier(1f, (float) Config.getRES_WIDTH() / 3 - logo.getWidth() / 2, (float) Config.getRES_WIDTH() / 2 - logo.getWidth() / 2, EaseBounceOut.getInstance())); - logoOverlay.registerEntityModifier(new MoveXModifier(1f, Config.getRES_WIDTH() / 3 - logo.getWidth() / 2, Config.getRES_WIDTH() / 2 - logo.getWidth() / 2, EaseBounceOut.getInstance())); + logoOverlay.registerEntityModifier(new MoveXModifier(1f, (float) Config.getRES_WIDTH() / 3 - logo.getWidth() / 2, (float) Config.getRES_WIDTH() / 2 - logo.getWidth() / 2, EaseBounceOut.getInstance())); - for (int i = 0; i < spectrum.length; i++) { - spectrum[i].registerEntityModifier(new MoveXModifier(1f, Config.getRES_WIDTH() / 3, Config.getRES_WIDTH() / 2, EaseBounceOut.getInstance())); + for (Rectangle rectangle : spectrum) { + rectangle.registerEntityModifier(new MoveXModifier(1f, (float) Config.getRES_WIDTH() / 3, (float) Config.getRES_WIDTH() / 2, EaseBounceOut.getInstance())); } isMenuShowed = false; doMenuShow = false; @@ -806,7 +797,7 @@ public void reset() { public void loadBeatmap() { LibraryManager.INSTANCE.shuffleLibrary(); loadBeatmapInfo(); - loadTimeingPoints(true); + loadTimingPoints(true); } public void loadBeatmapInfo() { @@ -818,7 +809,7 @@ public void loadBeatmapInfo() { musicInfoText = new ChangeableText(Utils.toRes(Config.getRES_WIDTH() - 500), Utils.toRes(3), ResourceManager.getInstance().getFont("font"), "None...", HorizontalAlign.RIGHT, 35); } - if (beatmapInfo.getArtistUnicode() != null && beatmapInfo.getTitleUnicode() != null && Config.isForceRomanized() == false) { + if (beatmapInfo.getArtistUnicode() != null && beatmapInfo.getTitleUnicode() != null && !Config.isForceRomanized()) { musicInfoText.setText(beatmapInfo.getArtistUnicode() + " - " + beatmapInfo.getTitleUnicode(), true); } else if (beatmapInfo.getArtist() != null && beatmapInfo.getTitle() != null) { musicInfoText.setText(beatmapInfo.getArtist() + " - " + beatmapInfo.getTitle(), true); @@ -835,7 +826,7 @@ public void loadBeatmapInfo() { } } - public void loadTimeingPoints(boolean reloadMusic) { + public void loadTimingPoints(boolean reloadMusic) { if (beatmapInfo == null) { return; } @@ -848,14 +839,14 @@ public void loadTimeingPoints(boolean reloadMusic) { ArrayList trackInfos = beatmapInfo.getTracks(); if (trackInfos != null && trackInfos.size() > 0) { int trackIndex = random.nextInt(trackInfos.size()); - selectedTrack = trackInfos.get(trackIndex); + TrackInfo selectedTrack = trackInfos.get(trackIndex); GlobalManager.getInstance().setSelectedTrack(selectedTrack); if (selectedTrack.getBackground() != null) { try { final TextureRegion tex = Config.isSafeBeatmapBg() ? - ResourceManager.getInstance().getTexture("menu-background") : - ResourceManager.getInstance().loadBackground(selectedTrack.getBackground()); + ResourceManager.getInstance().getTexture("menu-background") : + ResourceManager.getInstance().loadBackground(selectedTrack.getBackground()); if (tex != null) { float height = tex.getHeight(); @@ -872,13 +863,7 @@ public void onModifierStarted(IModifier pModifier, IEntity pItem) { @Override public void onModifierFinished(IModifier pModifier, final IEntity pItem) { - GlobalManager.getInstance().getMainActivity().runOnUpdateThread(new Runnable() { - @Override - public void run() { - // TODO Auto-generated method stub - pItem.detachSelf(); - } - }); + GlobalManager.getInstance().getMainActivity().runOnUpdateThread(pItem::detachSelf); } })); lastBackground = background; @@ -905,11 +890,11 @@ public void run() { Arrays.fill(peakAlpha, 0f); BeatmapParser parser = new BeatmapParser(selectedTrack.getFilename()); - beatmapData = parser.parse(false); + BeatmapData beatmapData = parser.parse(false); if (beatmapData != null) { timingPoints = new LinkedList<>(); for (final String s : beatmapData.rawTimingPoints) { - final TimingPoint tp = new TimingPoint(s.split("[,]"), currentTimingPoint); + final TimingPoint tp = new TimingPoint(s.split(","), currentTimingPoint); timingPoints.add(tp); if (!tp.wasInderited() || currentTimingPoint == null) { currentTimingPoint = tp; @@ -924,17 +909,13 @@ public void run() { } public void showExitDialog() { - GlobalManager.getInstance().getMainActivity().runOnUiThread(new Runnable() { - public void run() { - new ConfirmDialogFragment().setMessage(R.string.dialog_exit_message).showForResult( - isAccepted -> { - if (isAccepted) { - exit(); - } + GlobalManager.getInstance().getMainActivity().runOnUiThread(() -> new ConfirmDialogFragment().setMessage(R.string.dialog_exit_message).showForResult( + isAccepted -> { + if (isAccepted) { + exit(); } - ); - } - }); + } + )); } public void exit() { @@ -962,7 +943,7 @@ public void exit() { if (exitsound != null) { exitsound.play(); } - + Rectangle bg = new Rectangle(0, 0, Config.getRES_WIDTH(), Config.getRES_HEIGHT()); bg.setColor(0, 0, 0, 1.0f); @@ -1016,12 +997,12 @@ public void setBeatmap(BeatmapInfo info) { int playIndex = LibraryManager.INSTANCE.findBeatmap(info); Debug.i("index " + playIndex); loadBeatmapInfo(); - loadTimeingPoints(false); + loadTimingPoints(false); musicControl(MusicOption.SYNC); } public void watchReplay(String replayFile) { - replay = new Replay(); + Replay replay = new Replay(); if (replay.loadInfo(replayFile)) { if (replay.replayVersion >= 3) { //replay @@ -1050,4 +1031,4 @@ public void show() { } public enum MusicOption {PREV, PLAY, PAUSE, STOP, NEXT, SYNC} -} +} \ No newline at end of file diff --git a/src/ru/nsu/ccfit/zuev/osu/PermissionActivity.java b/src/ru/nsu/ccfit/zuev/osu/PermissionActivity.java index 8eb2f91fa..17c3e7e6c 100644 --- a/src/ru/nsu/ccfit/zuev/osu/PermissionActivity.java +++ b/src/ru/nsu/ccfit/zuev/osu/PermissionActivity.java @@ -59,7 +59,7 @@ private void checkPermissions() { Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION, uri); startActivityForResult(intent, 2444); } - }else if(Build.VERSION.SDK_INT < Build.VERSION_CODES.R) { + } else { if (PermissionChecker.checkCallingOrSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PermissionChecker.PERMISSION_GRANTED) { startGameActivity(); diff --git a/src/ru/nsu/ccfit/zuev/osu/PropertiesLibrary.java b/src/ru/nsu/ccfit/zuev/osu/PropertiesLibrary.java index fe34baaba..8a7db233c 100644 --- a/src/ru/nsu/ccfit/zuev/osu/PropertiesLibrary.java +++ b/src/ru/nsu/ccfit/zuev/osu/PropertiesLibrary.java @@ -7,7 +7,6 @@ import java.io.File; import java.io.FileInputStream; -import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; @@ -15,14 +14,13 @@ import java.util.HashMap; import java.util.Map; -import ru.nsu.ccfit.zuev.osu.async.AsyncTask; import ru.nsu.ccfit.zuev.osu.helper.StringTable; import ru.nsu.ccfit.zuev.osuplus.R; public class PropertiesLibrary { private static final PropertiesLibrary instance = new PropertiesLibrary(); private final String version = "properties1"; - private Map props = new HashMap(); + private Map props = new HashMap<>(); private Context context = null; private PropertiesLibrary() { } @@ -35,7 +33,7 @@ public static PropertiesLibrary getInstance() { public void load(final Activity activity) { context = activity; final File lib = new File(activity.getFilesDir(), "properties"); - if (lib.exists() == false) { + if (!lib.exists()) { return; } @@ -44,7 +42,7 @@ public void load(final Activity activity) { new FileInputStream(lib)); Object obj = istream.readObject(); if (obj instanceof String) { - if (((String) obj).equals(version) == false) { + if (!obj.equals(version)) { istream.close(); return; } @@ -59,14 +57,9 @@ public void load(final Activity activity) { Debug.i("Properties loaded"); } istream.close(); - } catch (final FileNotFoundException e) { - Debug.e("PropertiesLibrary: " + e.getMessage(), e); - } catch (final IOException e) { - Debug.e("PropertiesLibrary: " + e.getMessage(), e); - } catch (final ClassNotFoundException e) { + } catch (final IOException | ClassNotFoundException e) { Debug.e("PropertiesLibrary: " + e.getMessage(), e); } - ToastLogger.addToLog("Cannot load properties!"); } public synchronized void save(final Context activity) { @@ -77,11 +70,6 @@ public synchronized void save(final Context activity) { ostream.writeObject(version); ostream.writeObject(props); ostream.close(); - } catch (final FileNotFoundException e) { - ToastLogger.showText( - StringTable.format(R.string.message_error, e.getMessage()), - false); - Debug.e("PropertiesLibrary: " + e.getMessage(), e); } catch (final IOException e) { ToastLogger.showText( StringTable.format(R.string.message_error, e.getMessage()), @@ -103,18 +91,6 @@ public void save() { save(context); } - public void saveAsync() { - if (context == null) { - return; - } - new AsyncTask() { - @Override - public void run() { - save(context); - } - }.execute(); - } - public BeatmapProperties getProperties(final String path) { if (props.containsKey(path)) { return props.get(path); @@ -126,7 +102,7 @@ public void setProperties(final String path, final BeatmapProperties properties) { this.load((Activity) context); props.put(path, properties); - if (properties.favorite == false && properties.getOffset() == 0) { + if (!properties.favorite && properties.getOffset() == 0) { props.remove(path); } } diff --git a/src/ru/nsu/ccfit/zuev/osu/ResourceManager.java b/src/ru/nsu/ccfit/zuev/osu/ResourceManager.java index 19ca08d56..6fc3f0db0 100644 --- a/src/ru/nsu/ccfit/zuev/osu/ResourceManager.java +++ b/src/ru/nsu/ccfit/zuev/osu/ResourceManager.java @@ -25,15 +25,18 @@ import java.io.File; import java.io.IOException; +import java.util.ArrayList; import java.util.HashMap; +import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import ru.nsu.ccfit.zuev.audio.BassSoundProvider; import ru.nsu.ccfit.zuev.osu.helper.FileUtils; -import ru.nsu.ccfit.zuev.osu.helper.MD5Calcuator; +import ru.nsu.ccfit.zuev.osu.helper.MD5Calculator; import ru.nsu.ccfit.zuev.osu.helper.QualityAssetBitmapSource; import ru.nsu.ccfit.zuev.osu.helper.QualityFileBitmapSource; import ru.nsu.ccfit.zuev.osu.helper.ScaledBitmapSource; @@ -103,7 +106,7 @@ public void loadSkin(String folder) { loadTexture("ranking_disabled", "ranking_disabled.png", false); loadTexture("flashlight_cursor", "flashlight_cursor.png", false, TextureOptions.BILINEAR_PREMULTIPLYALPHA); - if (textures.containsKey("lighting") == false) + if (!textures.containsKey("lighting")) textures.put("lighting", null); // textures.put("fail-background", null); // textures.put("pause-overlay", null); @@ -114,14 +117,11 @@ public void loadCustomSkin(String folder) { if (!folder.endsWith("/")) folder += "/"; File[] skinFiles = null; - File skinFolder = null; - if (folder != null) { - skinFolder = new File(folder); - if (!skinFolder.exists()) { - skinFolder = null; - } else { - skinFiles = FileUtils.listFiles(skinFolder); - } + File skinFolder = new File(folder); + if (!skinFolder.exists()) { + skinFolder = null; + } else { + skinFiles = FileUtils.listFiles(skinFolder); } if (skinFiles != null) { JSONObject skinjson = null; @@ -131,7 +131,6 @@ public void loadCustomSkin(String folder) { skinjson = new JSONObject(OsuSkin.readFull(jsonFile)); } catch (Exception e) { e.printStackTrace(); - skinjson = null; } } else { var iniFile = new File(folder, "skin.ini"); @@ -158,7 +157,7 @@ public void loadCustomSkin(String folder) { if (skinjson == null) skinjson = new JSONObject(); SkinJsonReader.getReader().supplyJson(skinjson); } - final Map availableFiles = new HashMap(); + final Map availableFiles = new HashMap<>(); if (skinFiles != null) { for (final File f : skinFiles) { if (f.isFile()) { @@ -201,9 +200,9 @@ public void loadCustomSkin(String folder) { customFrameCount.clear(); try { - for (final String s : context.getAssets().list("gfx")) { + for (final String s : Objects.requireNonNull(context.getAssets().list("gfx"))) { final String name = s.substring(0, s.length() - 4); - if (Config.isCorovans() == false) { + if (!Config.isCorovans()) { if (name.equals("count1") || name.equals("count2") || name.equals("count3") || name.equals("go") || name.equals("ready")) { @@ -211,7 +210,7 @@ public void loadCustomSkin(String folder) { } } if (availableFiles.containsKey(name)) { - loadTexture(name, availableFiles.get(name).getPath(), true); + loadTexture(name, Objects.requireNonNull(availableFiles.get(name)).getPath(), true); if (Character.isDigit(name.charAt(name.length() - 1))) { noticeFrameCount(name); } @@ -220,83 +219,42 @@ public void loadCustomSkin(String folder) { } } if (availableFiles.containsKey("scorebar-kidanger")) { - loadTexture("scorebar-kidanger", availableFiles.get("scorebar-kidanger").getPath(), true); + loadTexture("scorebar-kidanger", Objects.requireNonNull(availableFiles.get("scorebar-kidanger")).getPath(), true); loadTexture("scorebar-kidanger2", - availableFiles.get( + Objects.requireNonNull(availableFiles.get( availableFiles.containsKey("scorebar-kidanger2") ? "scorebar-kidanger2" : "scorebar-kidanger" - ).getPath(), true); + )).getPath(), true); } if (availableFiles.containsKey("comboburst")) - loadTexture("comboburst", availableFiles.get("comboburst").getPath(), true); + loadTexture("comboburst", Objects.requireNonNull(availableFiles.get("comboburst")).getPath(), true); else unloadTexture("comboburst"); + for (int i = 0; i < 10; i++) { String textureName = "comboburst-" + i; - if (availableFiles.containsKey(textureName)) - loadTexture(textureName, availableFiles.get(textureName).getPath(), true); - else unloadTexture(textureName); - } - for (int i = 0; i < 60; i++) { - String textureName = "play-skip-" + i; - if (availableFiles.containsKey(textureName)) - loadTexture(textureName, availableFiles.get(textureName).getPath(), true); - else unloadTexture(textureName); - } - for (int i = 0; i < 60; i++) { - String textureName = "menu-back-" + i; - if (availableFiles.containsKey(textureName)) - loadTexture(textureName, availableFiles.get(textureName).getPath(), true); - else unloadTexture(textureName); - } - for (int i = 0; i < 60; i++) { - String textureName = "scorebar-colour-" + i; - if (availableFiles.containsKey(textureName)) - loadTexture(textureName, availableFiles.get(textureName).getPath(), true); - else unloadTexture(textureName); - } - // - for (int i = 0; i < 60; i++) { - String textureName = "hit0-" + i; - if (availableFiles.containsKey(textureName)) - loadTexture(textureName, availableFiles.get(textureName).getPath(), true); - else unloadTexture(textureName); - } - for (int i = 0; i < 60; i++) { - String textureName = "hit50-" + i; - if (availableFiles.containsKey(textureName)) - loadTexture(textureName, availableFiles.get(textureName).getPath(), true); - else unloadTexture(textureName); - } - for (int i = 0; i < 60; i++) { - String textureName = "hit100-" + i; - if (availableFiles.containsKey(textureName)) - loadTexture(textureName, availableFiles.get(textureName).getPath(), true); - else unloadTexture(textureName); - } - for (int i = 0; i < 60; i++) { - String textureName = "hit100k-" + i; - if (availableFiles.containsKey(textureName)) - loadTexture(textureName, availableFiles.get(textureName).getPath(), true); - else unloadTexture(textureName); - } - for (int i = 0; i < 60; i++) { - String textureName = "hit300-" + i; - if (availableFiles.containsKey(textureName)) - loadTexture(textureName, availableFiles.get(textureName).getPath(), true); - else unloadTexture(textureName); - } - for (int i = 0; i < 60; i++) { - String textureName = "hit300k-" + i; - if (availableFiles.containsKey(textureName)) - loadTexture(textureName, availableFiles.get(textureName).getPath(), true); - else unloadTexture(textureName); - } - for (int i = 0; i < 60; i++) { - String textureName = "hit300g-" + i; - if (availableFiles.containsKey(textureName)) - loadTexture(textureName, availableFiles.get(textureName).getPath(), true); - else unloadTexture(textureName); - } - // + if (availableFiles.containsKey(textureName)) { // No idea if this is still needed + File file = availableFiles.get(textureName); + if (file != null) { + loadTexture(textureName, file.getPath(), true); + } else { + unloadTexture(textureName); + } + } + } + + String[] names = {"play-skip-", "menu-back-", "scorebar-colour-", "hit0-", "hit50-", "hit100-", "hit100k-", "hit300-", "hit300k-", "hit300g-"}; + for (String name : names) { + for (int i = 0; i < 60; i++) { + String textureName = name + i; + if (availableFiles.containsKey(textureName)) { + File file = availableFiles.get(textureName); + if (file != null) { + loadTexture(textureName, file.getPath(), true); + } else { + unloadTexture(textureName); + } + } + } + } } catch (final IOException e) { Debug.e("Resources: " + e.getMessage(), e); } @@ -305,10 +263,10 @@ public void loadCustomSkin(String folder) { try { // TODO: buggy? - for (final String s : context.getAssets().list("sfx")) { + for (final String s : Objects.requireNonNull(context.getAssets().list("sfx"))) { final String name = s.substring(0, s.length() - 4); if (availableFiles.containsKey(name)) { - loadSound(name, availableFiles.get(name).getPath(), true); + loadSound(name, Objects.requireNonNull(availableFiles.get(name)).getPath(), true); } else { loadSound(name, "sfx/" + s, false); } @@ -331,7 +289,7 @@ public void loadCustomSkin(String folder) { loadTexture("ranking_button", "ranking_button.png", false); loadTexture("ranking_enabled", "ranking_enabled.png", false); loadTexture("ranking_disabled", "ranking_disabled.png", false); - if (textures.containsKey("lighting") == false) + if (!textures.containsKey("lighting")) textures.put("lighting", null); // textures.put("fail-background", null); // textures.put("pause-overlay", null); @@ -339,7 +297,7 @@ public void loadCustomSkin(String folder) { private void noticeFrameCount(final String name) { String resnameWN; - if (name.contains("-") == false) { + if (!name.contains("-")) { resnameWN = name.substring(0, name.length() - 1); } else { resnameWN = name.substring(0, name.lastIndexOf('-')); @@ -353,8 +311,8 @@ private void noticeFrameCount(final String name) { if (frameNum < 0) { frameNum *= -1; } - if (customFrameCount.containsKey(resnameWN) == false - || customFrameCount.get(resnameWN) < frameNum) { + if (!customFrameCount.containsKey(resnameWN) + || Objects.requireNonNull(customFrameCount.get(resnameWN)) < frameNum) { customFrameCount.put(resnameWN, frameNum); } } @@ -390,7 +348,7 @@ public StrokeFont loadStrokeFont(final String resname, final String file, Config.getTextureQuality() == 1 ? 2 : 0.75f, color2); } else { font = FontFactory.createStrokeFromAsset(texture, context, "fonts/" - + file, size, true, color1, 2 / Config.getTextureQuality(), + + file, size, true, color1, (float) 2 / Config.getTextureQuality(), color2); } engine.getTextureManager().loadTexture(texture); @@ -400,7 +358,7 @@ public StrokeFont loadStrokeFont(final String resname, final String file, } public Font getFont(final String resname) { - if (fonts.containsKey(resname) == false) { + if (!fonts.containsKey(resname)) { loadFont(resname, null, 35, Color.WHITE); } return fonts.get(resname); @@ -428,7 +386,7 @@ public TextureRegion loadBackground(final String file) { public TextureRegion loadBackground(final String file, Engine engine) { if (textures.containsKey("::background")) { engine.getTextureManager().unloadTexture( - textures.get("::background").getTexture()); + Objects.requireNonNull(textures.get("::background")).getTexture()); } if (file == null) { return textures.get("menu-background"); @@ -445,7 +403,7 @@ public TextureRegion loadBackground(final String file, Engine engine) { while (th < source.getHeight()) { th *= 2; } - if (source.preload() == false) { + if (!source.preload()) { textures.put("::background", textures.get("menu-background")); return textures.get("::background"); } @@ -641,10 +599,10 @@ public TextureRegion getTexture(final String resname) { } public TextureRegion getAvatarTextureIfLoaded(final String avatarURL) { - var region = getTextureIfLoaded(MD5Calcuator.getStringMD5(avatarURL)); + var region = getTextureIfLoaded(MD5Calculator.getStringMD5(avatarURL)); if (region == null) { - region = getTextureIfLoaded(MD5Calcuator.getStringMD5(OnlineManager.defaultAvatarURL)); + region = getTextureIfLoaded(MD5Calculator.getStringMD5(OnlineManager.defaultAvatarURL)); } return region; @@ -712,7 +670,7 @@ public void loadCustomSound(final File file) { if (resName.length() == 0) { return; } - Pattern pattern = Pattern.compile("([^\\d\\.]+)"); + Pattern pattern = Pattern.compile("([^\\d.]+)"); Matcher matcher = pattern.matcher(resName); if (matcher.find()) { String setName = matcher.group(1); @@ -738,7 +696,7 @@ public BassSoundProvider getCustomSound(final String resname, final int set) { return getSound(resname); } if (set >= 2) { - String fullName = resname + String.valueOf(set); + String fullName = resname + set; if (customSounds.containsKey(fullName)) { return customSounds.get(fullName); } else { @@ -762,13 +720,13 @@ public void loadCustomTexture(final File file) { if (Character.isDigit(resname.charAt(resname.length() - 1))) { String resnameWN; - if (resname.contains("-") == false) { + if (!resname.contains("-")) { resnameWN = resname.substring(0, resname.length() - 1); } else { resnameWN = resname.substring(0, resname.lastIndexOf('-')); } - if (textures.containsKey(resname) == false + if (!textures.containsKey(resname) && SkinManager.getFrames(resnameWN) == 0) { return; } @@ -781,12 +739,12 @@ public void loadCustomTexture(final File file) { if (frameNum < 0) { frameNum *= -1; } - if (customFrameCount.containsKey(resnameWN) == false - || customFrameCount.get(resnameWN) < frameNum) { + if (!customFrameCount.containsKey(resnameWN) + || Objects.requireNonNull(customFrameCount.get(resnameWN)) < frameNum) { customFrameCount.put(resnameWN, frameNum); } } - } else if (textures.containsKey(resname) == false) { + } else if (!textures.containsKey(resname)) { if (textures.containsKey(resname + "-0") || textures.containsKey(resname + "0")) { if (textures.containsKey(resname + "0")) @@ -807,7 +765,7 @@ public void loadCustomTexture(final File file) { while (th < source.getHeight()) { th *= 2; } - if (source.preload() == false) { + if (!source.preload()) { return; } final BitmapTextureAtlas tex = new BitmapTextureAtlas(tw, th, @@ -856,7 +814,7 @@ public void loadCustomTexture(final File file) { public void unloadTexture(final String name) { if (textures.get(name) != null) { engine.getTextureManager().unloadTexture( - textures.get(name).getTexture()); + Objects.requireNonNull(textures.get(name)).getTexture()); textures.remove(name); Debug.i("Texture \"" + name + "\"unloaded"); } @@ -864,7 +822,18 @@ public void unloadTexture(final String name) { public void unloadTexture(TextureRegion texture) { engine.getTextureManager().unloadTexture(texture.getTexture()); - textures.remove(texture); + + List toRemove = new ArrayList<>(); + + for (var entry : textures.entrySet()) { + if (entry.getValue() == texture) { + toRemove.add(entry.getKey()); + } + } + + for (var key : toRemove) { + textures.remove(key); + } } public void initSecurityUtils() { @@ -877,9 +846,9 @@ public void clearCustomResources() { } final Set texnames = customTextures.keySet(); for (final String s : texnames) { - if (customTextures.get(s).getTexture().isLoadedToHardware()) { - engine.getTextureManager().unloadTexture( - customTextures.get(s).getTexture()); + TextureRegion tex = customTextures.get(s); + if (tex != null && tex.getTexture() != null && tex.getTexture().isLoadedToHardware()) { + engine.getTextureManager().unloadTexture(tex.getTexture()); // engine.getTextureManager().loadTexture(textures.get(s).getTexture()); } } @@ -889,10 +858,10 @@ public void clearCustomResources() { } public int getFrameCount(final String texname) { - if (customFrameCount.containsKey(texname) == false) { + if (!customFrameCount.containsKey(texname)) { return -1; } else { - return customFrameCount.get(texname); + return Objects.requireNonNull(customFrameCount.get(texname)); } } @@ -900,10 +869,8 @@ public void checkSpinnerTextures() { final String[] names = {"spinner-background", "spinner-circle", "spinner-metre", "spinner-approachcircle", "spinner-spin"}; for (final String s : names) { - if (textures != null - && textures.get(s) != null - && textures.get(s).getTexture() != null - && !textures.get(s).getTexture().isLoadedToHardware()) { + TextureRegion tex = textures.get(s); + if (tex != null && tex.getTexture() != null && !tex.getTexture().isLoadedToHardware()) { engine.getTextureManager().reloadTextures(); break; } @@ -921,10 +888,8 @@ public void checkEvoSpinnerTextures() { "spinner-clear" }; for (final String s : names) { - if (textures != null - && textures.get(s) != null - && textures.get(s).getTexture() != null - && !textures.get(s).getTexture().isLoadedToHardware()) { + TextureRegion tex = textures.get(s); + if (tex != null && tex.getTexture() != null && !tex.getTexture().isLoadedToHardware()) { engine.getTextureManager().reloadTextures(); break; } diff --git a/src/ru/nsu/ccfit/zuev/osu/StartingMapManager.java b/src/ru/nsu/ccfit/zuev/osu/StartingMapManager.java deleted file mode 100644 index 857a618d1..000000000 --- a/src/ru/nsu/ccfit/zuev/osu/StartingMapManager.java +++ /dev/null @@ -1,113 +0,0 @@ -package ru.nsu.ccfit.zuev.osu; - -import android.app.Activity; -import android.content.SharedPreferences; -import android.content.res.AssetManager; - -import androidx.preference.PreferenceManager; - -import org.anddev.andengine.util.Debug; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import ru.nsu.ccfit.zuev.osu.helper.StringTable; -import ru.nsu.ccfit.zuev.osuplus.R; - -public class StartingMapManager { - private final Activity activity; - - public StartingMapManager(final Activity activity) { - this.activity = activity; - } - - public boolean checkStartingMaps() { - final SharedPreferences prefs = PreferenceManager - .getDefaultSharedPreferences(activity); - return prefs.getBoolean("initialized", false); - } - - public void copyStartingMaps() { - if (checkStartingMaps()) { - return; - } - ToastLogger.showText("Preparing for the first launch", false); - String dirList[]; - try { - dirList = activity.getAssets().list("Songs"); - } catch (final IOException e) { - Debug.e("StartingMapManager: " + e.getMessage(), e); - return; - } - - for (final String dir : dirList) { - copyAllFiles(dir); - } - - final SharedPreferences prefs = PreferenceManager - .getDefaultSharedPreferences(activity); - final SharedPreferences.Editor editor = prefs.edit(); - editor.putBoolean("initialized", true); - editor.commit(); - } - - private void copyAllFiles(final String dirname) { - final File dir = new File(Config.getBeatmapPath() + "/" + dirname); - if (dir.exists() == false && dir.mkdirs() == false) { - ToastLogger.showText("Cannot create " + dir.getPath(), false); - return; - } - String fileList[]; - try { - fileList = activity.getAssets().list("Songs/" + dirname); - } catch (final IOException e) { - Debug.e("StartingMapManager: " + e.getMessage(), e); - return; - } - - final AssetManager mgr = activity.getAssets(); - for (final String file : fileList) { - final String fullname = "Songs/" + dirname + "/" + file; - try { - final InputStream istream = mgr.open(fullname); - copyFile(dirname + "/" + file, istream); - } catch (final IOException e) { - Debug.e("StartingMapManager: " + e.getMessage(), e); - } - } - } - - private void copyFile(final String filename, final InputStream istream) { - OutputStream out; - - try { - out = new FileOutputStream(Config.getBeatmapPath() + "/" + filename); - } catch (final FileNotFoundException e) { - ToastLogger.showText( - StringTable.format(R.string.message_error, e.getMessage()), - false); - Debug.e("StartingMapManager: " + e.getMessage(), e); - return; - } - - try { - final byte[] buffer = new byte[4096]; - int read; - while ((read = istream.read(buffer)) != -1) { - out.write(buffer, 0, read); - } - - istream.close(); - out.flush(); - out.close(); - } catch (final IOException e) { - ToastLogger.showText(e.getMessage(), false); - Debug.e("StartingMapManager: " + e.getMessage(), e); - return; - } - } -} diff --git a/src/ru/nsu/ccfit/zuev/osu/ToastLogger.java b/src/ru/nsu/ccfit/zuev/osu/ToastLogger.java index 7918e9c63..eae8680c6 100644 --- a/src/ru/nsu/ccfit/zuev/osu/ToastLogger.java +++ b/src/ru/nsu/ccfit/zuev/osu/ToastLogger.java @@ -12,9 +12,7 @@ public class ToastLogger { private static ToastLogger instance = null; Activity activity; - String message = ""; - boolean showlong = false; - ArrayList debugLog = new ArrayList(); + ArrayList debugLog = new ArrayList<>(); float percentage; private ToastLogger(final Activity activity) { @@ -39,16 +37,6 @@ public static void showTextId(@StringRes final int resID, final boolean showlong showText(StringTable.get(resID), showlong); } - public static void addToLog(final String str) { - if (instance == null) { - return; - /* - * if (instance.debugLog.size() >= 20) instance.debugLog.remove(0); - * instance.debugLog.add(str); - */ - } - } - public static ArrayList getLog() { if (instance == null) { return null; diff --git a/src/ru/nsu/ccfit/zuev/osu/Utils.java b/src/ru/nsu/ccfit/zuev/osu/Utils.java index ca6ac3992..3ed1c92bb 100644 --- a/src/ru/nsu/ccfit/zuev/osu/Utils.java +++ b/src/ru/nsu/ccfit/zuev/osu/Utils.java @@ -9,6 +9,8 @@ import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.util.MathUtils; +import java.util.Arrays; + import ru.nsu.ccfit.zuev.osu.game.GameHelper; import ru.nsu.ccfit.zuev.osu.game.GameObjectListener; @@ -18,9 +20,7 @@ public class Utils { private static int soundMask = 0; public static T[] oneObjectArray(T object, T[] ary) { - for (int i = 0; i < ary.length; i++) { - ary[i] = object; - } + Arrays.fill(ary, object); return ary; } @@ -57,9 +57,9 @@ public static PointF trackToRealCoords(final PointF coords) { pos.y += (Config.getRES_HEIGHT() - toRes(Constants.MAP_ACTUAL_HEIGHT)) / 2f; pos.x += (Config.getRES_WIDTH() - toRes(Constants.MAP_ACTUAL_WIDTH)) / 2f; if (GameHelper.isHardrock()) { - pos.y -= Config.getRES_HEIGHT() / 2; + pos.y -= (float) Config.getRES_HEIGHT() / 2; pos.y *= -1; - pos.y += Config.getRES_HEIGHT() / 2; + pos.y += (float) Config.getRES_HEIGHT() / 2; } /*if (pos.y < 18) { pos.y = 18; @@ -75,9 +75,9 @@ public static void changeTrackToRealCoords(final PointF coords) { pos.y += (Config.getRES_HEIGHT() - toRes(Constants.MAP_ACTUAL_HEIGHT)) / 2f; pos.x += (Config.getRES_WIDTH() - toRes(Constants.MAP_ACTUAL_WIDTH)) / 2f; if (GameHelper.isHardrock()) { - pos.y -= Config.getRES_HEIGHT() / 2; + pos.y -= (float) Config.getRES_HEIGHT() / 2; pos.y *= -1; - pos.y += Config.getRES_HEIGHT() / 2; + pos.y += (float) Config.getRES_HEIGHT() / 2; } } diff --git a/src/ru/nsu/ccfit/zuev/osu/async/AsyncTask.java b/src/ru/nsu/ccfit/zuev/osu/async/AsyncTask.java deleted file mode 100644 index e1ad21e46..000000000 --- a/src/ru/nsu/ccfit/zuev/osu/async/AsyncTask.java +++ /dev/null @@ -1,62 +0,0 @@ -package ru.nsu.ccfit.zuev.osu.async; - -import android.os.Handler; -import android.os.Looper; - -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -public abstract class AsyncTask { - private final ExecutorService executor; - private final Handler handler; - - private boolean isCompleted; - - private final Runnable mOnComplete = () -> { - onComplete(); - isCompleted = true; - }; - - public AsyncTask() { - executor = Executors.newSingleThreadExecutor(); - handler = new Handler(Looper.getMainLooper()); - } - - public abstract void run(); - public void onComplete() {} - - public void onCancel(boolean wasForced) {} - - public final void execute() { - executor.execute(() -> { - isCompleted = false; - Thread t = Thread.currentThread(); - t.setName("async::" + t.getName()); - run(); - handler.post(mOnComplete); - executor.shutdown(); - }); - } - - public final void cancel(boolean force) { - if (force) { - executor.shutdownNow(); - } else { - executor.shutdown(); - } - handler.removeCallbacks(mOnComplete); - onCancel(force); - } - - public final boolean isCompleted() { - return isCompleted; - } - - public final boolean isTerminated() { - return executor.isTerminated(); - } - - public final boolean isShutdown() { - return executor.isShutdown(); - } -} \ No newline at end of file diff --git a/src/ru/nsu/ccfit/zuev/osu/beatmap/parser/sections/BeatmapColorParser.java b/src/ru/nsu/ccfit/zuev/osu/beatmap/parser/sections/BeatmapColorParser.java index 35a69f5ac..35bbdcfa1 100644 --- a/src/ru/nsu/ccfit/zuev/osu/beatmap/parser/sections/BeatmapColorParser.java +++ b/src/ru/nsu/ccfit/zuev/osu/beatmap/parser/sections/BeatmapColorParser.java @@ -1,6 +1,7 @@ package ru.nsu.ccfit.zuev.osu.beatmap.parser.sections; import java.util.Collections; +import java.util.Comparator; import ru.nsu.ccfit.zuev.osu.RGBColor; import ru.nsu.ccfit.zuev.osu.Utils; diff --git a/src/ru/nsu/ccfit/zuev/osu/game/BreakAnimator.java b/src/ru/nsu/ccfit/zuev/osu/game/BreakAnimator.java index 1b68528f3..e5c386049 100644 --- a/src/ru/nsu/ccfit/zuev/osu/game/BreakAnimator.java +++ b/src/ru/nsu/ccfit/zuev/osu/game/BreakAnimator.java @@ -82,8 +82,8 @@ public void init(final float length) { this.length = length; time = 0; ending = stat.getHp() > 0.5f ? "pass" : "fail"; - final PointF center = new PointF(Config.getRES_WIDTH() / 2, - Config.getRES_HEIGHT() / 2); + final PointF center = new PointF((float) Config.getRES_WIDTH() / 2, + (float) Config.getRES_HEIGHT() / 2); passfail = SpritePool.getInstance().getCenteredSprite( "section-" + ending, center); scene.attachChild(passfail, 0); @@ -103,8 +103,6 @@ public void init(final float length) { mark.setScale(1.2f); scene.attachChild(mark, 0); } - - System.gc(); } private void setBgFade(float percent) { diff --git a/src/ru/nsu/ccfit/zuev/osu/game/ComboBurst.java b/src/ru/nsu/ccfit/zuev/osu/game/ComboBurst.java index e95d69557..0a85eec68 100644 --- a/src/ru/nsu/ccfit/zuev/osu/game/ComboBurst.java +++ b/src/ru/nsu/ccfit/zuev/osu/game/ComboBurst.java @@ -26,8 +26,8 @@ */ public class ComboBurst { - private final List comboBursts = new ArrayList(); - private final List comboBurstVocals = new ArrayList(); + private final List comboBursts = new ArrayList<>(); + private final List comboBurstVocals = new ArrayList<>(); private final float rightX; private final float bottomY; diff --git a/src/ru/nsu/ccfit/zuev/osu/game/Countdown.java b/src/ru/nsu/ccfit/zuev/osu/game/Countdown.java index 01b6e7286..867ea26b0 100644 --- a/src/ru/nsu/ccfit/zuev/osu/game/Countdown.java +++ b/src/ru/nsu/ccfit/zuev/osu/game/Countdown.java @@ -35,7 +35,7 @@ public Countdown(final GameObjectListener listener, final Scene scene, this.scene = scene; timepassed = -time + COUNTDOWN_LENGTH * speed; final PointF center = Utils.trackToRealCoords(new PointF( - Constants.MAP_WIDTH / 2, Constants.MAP_HEIGHT / 2)); + (float) Constants.MAP_WIDTH / 2, (float) Constants.MAP_HEIGHT / 2)); ready = new CentredSprite(center.x, center.y, ResourceManager .getInstance().getTexture("ready")); ready.registerEntityModifier(new SequenceEntityModifier( diff --git a/src/ru/nsu/ccfit/zuev/osu/game/FollowTrack.java b/src/ru/nsu/ccfit/zuev/osu/game/FollowTrack.java index f8d5b6eda..c5376131a 100644 --- a/src/ru/nsu/ccfit/zuev/osu/game/FollowTrack.java +++ b/src/ru/nsu/ccfit/zuev/osu/game/FollowTrack.java @@ -15,7 +15,7 @@ import ru.nsu.ccfit.zuev.osu.helper.AnimSprite; public class FollowTrack extends GameObject { - private final ArrayList points = new ArrayList(); + private final ArrayList points = new ArrayList<>(); private final int frameCount; private GameObjectListener listener; private float timeLeft; @@ -120,7 +120,7 @@ public void update(final float dt) { } if (percent >= 0 && percent < 1) { points.get((int) (percent * points.size())).setAlpha( - 1 - percent + (int) percent); + 1 - percent); } } diff --git a/src/ru/nsu/ccfit/zuev/osu/game/GameObjectData.java b/src/ru/nsu/ccfit/zuev/osu/game/GameObjectData.java index 3ed51b96b..b931313df 100644 --- a/src/ru/nsu/ccfit/zuev/osu/game/GameObjectData.java +++ b/src/ru/nsu/ccfit/zuev/osu/game/GameObjectData.java @@ -22,9 +22,7 @@ public GameObjectData(final String line) { } if (dataSize < data.length) { rawdata = new String[dataSize]; - for (int i = 0; i < rawdata.length; i++) { - rawdata[i] = data[i]; - } + System.arraycopy(data, 0, rawdata, 0, rawdata.length); } else rawdata = data; diff --git a/src/ru/nsu/ccfit/zuev/osu/game/GameObjectPool.java b/src/ru/nsu/ccfit/zuev/osu/game/GameObjectPool.java index 87ff1eebb..8364cf5c8 100644 --- a/src/ru/nsu/ccfit/zuev/osu/game/GameObjectPool.java +++ b/src/ru/nsu/ccfit/zuev/osu/game/GameObjectPool.java @@ -8,12 +8,12 @@ public class GameObjectPool { public static GameObjectPool instance = new GameObjectPool(); - public LinkedList circles = new LinkedList(); - public Map> numbers = new HashMap>(); - public Map> effects = new HashMap>(); - public LinkedList sliders = new LinkedList(); - public LinkedList tracks = new LinkedList(); - public LinkedList spinners = new LinkedList(); + public LinkedList circles = new LinkedList<>(); + public Map> numbers = new HashMap<>(); + public Map> effects = new HashMap<>(); + public LinkedList sliders = new LinkedList<>(); + public LinkedList tracks = new LinkedList<>(); + public LinkedList spinners = new LinkedList<>(); private int objectsCreated = 0; private GameObjectPool() { } @@ -63,7 +63,7 @@ public CircleNumber getNumber(final int num) { public void putNumber(final CircleNumber number) { if (numbers.containsKey(number.getNum()) == false) { - numbers.put(number.getNum(), new LinkedList()); + numbers.put(number.getNum(), new LinkedList<>()); } numbers.get(number.getNum()).add(number); } @@ -80,7 +80,7 @@ public GameEffect getEffect(final String texname) { public void putEffect(final GameEffect effect) { if (effects.containsKey(effect.getTexname()) == false) { - effects.put(effect.getTexname(), new LinkedList()); + effects.put(effect.getTexname(), new LinkedList<>()); } effects.get(effect.getTexname()).add(effect); } diff --git a/src/ru/nsu/ccfit/zuev/osu/game/GameScene.java b/src/ru/nsu/ccfit/zuev/osu/game/GameScene.java index f7559b090..89ee0c553 100644 --- a/src/ru/nsu/ccfit/zuev/osu/game/GameScene.java +++ b/src/ru/nsu/ccfit/zuev/osu/game/GameScene.java @@ -80,7 +80,7 @@ import ru.nsu.ccfit.zuev.osu.helper.AnimSprite; import ru.nsu.ccfit.zuev.osu.helper.BeatmapDifficultyCalculator; import ru.nsu.ccfit.zuev.osu.helper.DifficultyHelper; -import ru.nsu.ccfit.zuev.osu.helper.MD5Calcuator; +import ru.nsu.ccfit.zuev.osu.helper.MD5Calculator; import ru.nsu.ccfit.zuev.osu.helper.ModifierFactory; import ru.nsu.ccfit.zuev.osu.helper.StringTable; import ru.nsu.ccfit.zuev.osu.menu.LoadingScreen; @@ -135,7 +135,7 @@ public class GameScene implements IUpdateHandler, GameObjectListener, private LinkedList expiredObjects; private GameScoreText comboText, accText, scoreText; //显示的文字 连击数 ACC 分数 private GameScoreTextShadow scoreShadow; - private Queue breakPeriods = new LinkedList(); + private Queue breakPeriods = new LinkedList<>(); private BreakAnimator breakAnimator; private ScoreBar scorebar; private SongProgressBar progressBar; @@ -321,10 +321,9 @@ private void setBackground() { } private boolean loadGame(final TrackInfo track, final String rFile) { - InGameSettingMenu.getInstance().dismiss(); if (rFile != null && rFile.startsWith("https://")) { this.replayFile = Config.getCachePath() + "/" + - MD5Calcuator.getStringMD5(rFile) + ".odr"; + MD5Calculator.getStringMD5(rFile) + ".odr"; Debug.i("ReplayFile = " + replayFile); if (!OnlineFileOperator.downloadFile(rFile, this.replayFile)) { ToastLogger.showTextId(R.string.replay_cantdownload, true); @@ -500,7 +499,7 @@ private boolean loadGame(final TrackInfo track, final String rFile) { objects.add(new GameObjectData(s)); } - if (objects.size() <= 0) { + if (objects.size() == 0) { ToastLogger.showText("Empty Beatmap", true); return false; } @@ -619,7 +618,6 @@ private boolean loadGame(final TrackInfo track, final String rFile) { if (!replaying) OnlineScoring.getInstance().startPlay(track, trackMD5); - System.gc(); GameObjectPool.getInstance().preload(); ppText = null; @@ -732,7 +730,7 @@ private void prepareScene() { SmoothCamera camera = (SmoothCamera) (GlobalManager.getInstance().getCamera()); camera.setZoomFactorDirect(Config.getPlayfieldSize()); if (Config.isShrinkPlayfieldDownwards()) { - camera.setCenterDirect(Config.getRES_WIDTH() / 2, Config.getRES_HEIGHT() / 2 * Config.getPlayfieldSize()); + camera.setCenterDirect((float) Config.getRES_WIDTH() / 2, (float) Config.getRES_HEIGHT() / 2 * Config.getPlayfieldSize()); } } setBackground(); @@ -855,9 +853,7 @@ public void onUpdate(final float pSecondsElapsed) { cursors[i].mouseOldDown = false; } - for (int i = 0; i < CursorCount; i++) { - cursorIIsDown[i] = false; - } + Arrays.fill(cursorIIsDown, false); comboWas100 = false; comboWasMissed = false; @@ -930,7 +926,7 @@ public void onUpdate(final float pSecondsElapsed) { || (Config.getErrorMeter() == 2 && replaying)) { hitErrorMeter = new HitErrorMeter( fgScene, - new PointF(Config.getRES_WIDTH() / 2, Config.getRES_HEIGHT() - 20), + new PointF((float) Config.getRES_WIDTH() / 2, Config.getRES_HEIGHT() - 20), overallDifficulty, 12, difficultyHelper); @@ -948,7 +944,7 @@ public void onUpdate(final float pSecondsElapsed) { tex = ResourceManager.getInstance().getTexture("play-skip-0"); skipBtn = new AnimSprite(Config.getRES_WIDTH() - tex.getWidth(), Config.getRES_HEIGHT() - tex.getHeight(), loadedSkipTextures.size(), - loadedSkipTextures.toArray(new String[loadedSkipTextures.size()])); + loadedSkipTextures.toArray(new String[0])); } else { tex = ResourceManager.getInstance().getTexture("play-skip"); skipBtn = new Sprite(Config.getRES_WIDTH() - tex.getWidth(), @@ -1236,7 +1232,7 @@ else if (stat.getMod().contains(GameMod.MOD_PERFECT)) { bgScene.attachChild(kiaiRect, 0); unranked = new Sprite(0, 0, ResourceManager.getInstance().getTexture("play-unranked")); - unranked.setPosition(Config.getRES_WIDTH() / 2 - unranked.getWidth() / 2, 80); + unranked.setPosition((float) Config.getRES_WIDTH() / 2 - unranked.getWidth() / 2, 80); unranked.setVisible(false); fgScene.attachChild(unranked); @@ -1897,7 +1893,7 @@ public void onUpdate(final float pSecondsElapsed) { if (replay != null && replaying == false) { String ctime = String.valueOf(System.currentTimeMillis()); replayFile = Config.getCorePath() + "Scores/" - + MD5Calcuator.getStringMD5(lastTrack.getFilename() + ctime) + + MD5Calculator.getStringMD5(lastTrack.getFilename() + ctime) + ctime.substring(0, Math.min(3, ctime.length())) + ".odr"; replay.setStat(stat); replay.save(replayFile); @@ -1906,7 +1902,7 @@ public void onUpdate(final float pSecondsElapsed) { SmoothCamera camera = (SmoothCamera) (GlobalManager.getInstance().getCamera()); camera.setZoomFactorDirect(1f); if (Config.isShrinkPlayfieldDownwards()) { - camera.setCenterDirect(Config.getRES_WIDTH() / 2, Config.getRES_HEIGHT() / 2); + camera.setCenterDirect((float) Config.getRES_WIDTH() / 2, (float) Config.getRES_HEIGHT() / 2); } } if (scoringScene != null) { @@ -2132,7 +2128,7 @@ public void quit() { SmoothCamera camera = (SmoothCamera) (GlobalManager.getInstance().getCamera()); camera.setZoomFactorDirect(1f); if (Config.isShrinkPlayfieldDownwards()) { - camera.setCenterDirect(Config.getRES_WIDTH() / 2, Config.getRES_HEIGHT() / 2); + camera.setCenterDirect((float) Config.getRES_WIDTH() / 2, (float) Config.getRES_HEIGHT() / 2); } } scene = new Scene(); @@ -2381,8 +2377,8 @@ public void onSpinnerHit(int id, final int score, final boolean endCombo, int to replay.addObjectResult(id, acc, null); } - final PointF pos = new PointF(Config.getRES_WIDTH() / 2, - Config.getRES_HEIGHT() / 2); + final PointF pos = new PointF((float) Config.getRES_WIDTH() / 2, + (float) Config.getRES_HEIGHT() / 2); if (score == 0) { final GameEffect effect = GameObjectPool.getInstance().getEffect( "hit0"); @@ -2432,8 +2428,8 @@ public void onSpinnerHit(int id, final int score, final boolean endCombo, int to pos, scale, new SequenceEntityModifier(ModifierFactory.newScaleModifier( - 0.15f, 1.0f * scale, 1.2f * scale), ModifierFactory - .newScaleModifier(0.05f, 1.2f * scale, 1.0f * scale), + 0.15f, scale, 1.2f * scale), ModifierFactory + .newScaleModifier(0.05f, 1.2f * scale, scale), ModifierFactory.newAlphaModifier(1f, 1, 0))); pos.y /= 2f; @@ -2807,8 +2803,8 @@ private void createHitEffect(final PointF pos, final String name, RGBColor color pos, scale, new SequenceEntityModifier(ModifierFactory.newScaleModifier( - 0.15f, 1.0f * scale, 1.2f * scale), ModifierFactory - .newScaleModifier(0.05f, 1.2f * scale, 1.0f * scale), + 0.15f, scale, 1.2f * scale), ModifierFactory + .newScaleModifier(0.05f, 1.2f * scale, scale), ModifierFactory.newAlphaModifier(0.5f, 1, 0))); } @@ -2967,10 +2963,7 @@ private void stackNotes(){ } private void calculateAllSliderPaths(){ - if (objects.isEmpty()){ - return; - } - else { + if (!objects.isEmpty()){ if (lastTrack.getSliderCount() <= 0){ return; } @@ -2992,11 +2985,11 @@ private void calculateAllSliderPaths(){ pos.y += data.getPosOffset(); if (length < 0){ sliderPaths[sliderIndex] = GameHelper.calculatePath(Utils.realToTrackCoords(pos), - params[5].split("[|]"), 0, offset); + params[5].split("[|]"), 0, offset); } else{ sliderPaths[sliderIndex] = GameHelper.calculatePath(Utils.realToTrackCoords(pos), - params[5].split("[|]"), length, offset); + params[5].split("[|]"), length, offset); } sliderIndex++; } @@ -3035,7 +3028,7 @@ public boolean saveFailedReplay() { //save replay String ctime = String.valueOf(System.currentTimeMillis()); replayFile = Config.getCorePath() + "Scores/" - + MD5Calcuator.getStringMD5(lastTrack.getFilename() + ctime) + + MD5Calculator.getStringMD5(lastTrack.getFilename() + ctime) + ctime.substring(0, Math.min(3, ctime.length())) + ".odr"; replay.setStat(stat); replay.save(replayFile); diff --git a/src/ru/nsu/ccfit/zuev/osu/game/GameScoreText.java b/src/ru/nsu/ccfit/zuev/osu/game/GameScoreText.java index 845ada0ee..cc9e4b321 100644 --- a/src/ru/nsu/ccfit/zuev/osu/game/GameScoreText.java +++ b/src/ru/nsu/ccfit/zuev/osu/game/GameScoreText.java @@ -14,7 +14,7 @@ public class GameScoreText { private final AnimSprite[] letters; private final Map characters; - private final ArrayList digits = new ArrayList(); + private final ArrayList digits = new ArrayList<>(); private float scale = 0; private boolean hasX = false; private final float digitWidth; @@ -47,7 +47,7 @@ public GameScoreText(StringSkinData prefix, final float x, final float y, final width += letters[i].getWidth(); } this.scale = scale; - this.characters = new HashMap(); + this.characters = new HashMap<>(); this.characters.put('.', scoreComma); this.characters.put('%', scorePercent); this.characters.put('x', scoreX); @@ -55,7 +55,7 @@ public GameScoreText(StringSkinData prefix, final float x, final float y, final public void changeText(final String text) { int j = 0; - var totalWidth = 0; + var totalWidth = 0f; var digitsSize = digits.size(); for (int i = 0, length = text.length(); i < length; i++) { diff --git a/src/ru/nsu/ccfit/zuev/osu/game/GameScoreTextShadow.java b/src/ru/nsu/ccfit/zuev/osu/game/GameScoreTextShadow.java index 01fd33849..ff2893943 100644 --- a/src/ru/nsu/ccfit/zuev/osu/game/GameScoreTextShadow.java +++ b/src/ru/nsu/ccfit/zuev/osu/game/GameScoreTextShadow.java @@ -12,7 +12,7 @@ public class GameScoreTextShadow extends GameObject { private final GameScoreText comboText; private final AnimSprite[] letters; - private final ArrayList digits = new ArrayList(); + private final ArrayList digits = new ArrayList<>(); private boolean hasX = false; private String text = ""; diff --git a/src/ru/nsu/ccfit/zuev/osu/game/HitErrorMeter.java b/src/ru/nsu/ccfit/zuev/osu/game/HitErrorMeter.java index 361b56b0c..0c4eb8eda 100644 --- a/src/ru/nsu/ccfit/zuev/osu/game/HitErrorMeter.java +++ b/src/ru/nsu/ccfit/zuev/osu/game/HitErrorMeter.java @@ -28,8 +28,8 @@ public HitErrorMeter(Scene scene, PointF anchor, float difficulty, float height, barHeight = height; bgScene = scene; - onDisplayIndicators = new LinkedList(); - recycledIndicators = new LinkedList(); + onDisplayIndicators = new LinkedList<>(); + recycledIndicators = new LinkedList<>(); this.difficultyHelper = difficultyHelper; diff --git a/src/ru/nsu/ccfit/zuev/osu/game/ModernSpinner.java b/src/ru/nsu/ccfit/zuev/osu/game/ModernSpinner.java index eeea7a351..db4a5db78 100644 --- a/src/ru/nsu/ccfit/zuev/osu/game/ModernSpinner.java +++ b/src/ru/nsu/ccfit/zuev/osu/game/ModernSpinner.java @@ -52,8 +52,8 @@ public class ModernSpinner extends Spinner { public ModernSpinner() { ResourceManager.getInstance().checkEvoSpinnerTextures(); - center = Utils.trackToRealCoords(new PointF(Constants.MAP_WIDTH / 2, - Constants.MAP_HEIGHT / 2)); + center = Utils.trackToRealCoords(new PointF((float) Constants.MAP_WIDTH / 2, + (float) Constants.MAP_HEIGHT / 2)); middle = SpritePool.getInstance().getCenteredSprite( "spinner-middle", center); middle2 = SpritePool.getInstance().getCenteredSprite( diff --git a/src/ru/nsu/ccfit/zuev/osu/game/ScoreBar.java b/src/ru/nsu/ccfit/zuev/osu/game/ScoreBar.java index b85794489..72d7978f2 100644 --- a/src/ru/nsu/ccfit/zuev/osu/game/ScoreBar.java +++ b/src/ru/nsu/ccfit/zuev/osu/game/ScoreBar.java @@ -36,7 +36,7 @@ public ScoreBar(final GameObjectListener listener, final Scene scene, loadedScoreBarTextures.add("scorebar-colour-" + i); } colour = new AnimSprite(Utils.toRes(5), Utils.toRes(16), loadedScoreBarTextures.size(), - loadedScoreBarTextures.toArray(new String[loadedScoreBarTextures.size()])); + loadedScoreBarTextures.toArray(new String[0])); } else { colour = new Sprite(Utils.toRes(5), Utils.toRes(16), ResourceManager.getInstance().getTexture("scorebar-colour")); diff --git a/src/ru/nsu/ccfit/zuev/osu/game/Spinner.java b/src/ru/nsu/ccfit/zuev/osu/game/Spinner.java index 142f0acb7..9dc923d54 100644 --- a/src/ru/nsu/ccfit/zuev/osu/game/Spinner.java +++ b/src/ru/nsu/ccfit/zuev/osu/game/Spinner.java @@ -58,7 +58,7 @@ public class Spinner extends GameObject { public Spinner() { ResourceManager.getInstance().checkSpinnerTextures(); - this.pos = new PointF(Constants.MAP_WIDTH / 2,Constants.MAP_HEIGHT / 2); + this.pos = new PointF((float) Constants.MAP_WIDTH / 2, (float) Constants.MAP_HEIGHT / 2); center = Utils.trackToRealCoords(pos); background = SpritePool.getInstance().getCenteredSprite( "spinner-background", center); @@ -69,7 +69,7 @@ public Spinner() { center); mregion = ResourceManager.getInstance().getTexture("spinner-metre") .deepCopy(); - metre = new Sprite(center.x - Config.getRES_WIDTH() / 2, + metre = new Sprite(center.x - (float) Config.getRES_WIDTH() / 2, Config.getRES_HEIGHT(), mregion); metre.setWidth(Config.getRES_WIDTH()); metre.setHeight(background.getHeightScaled()); diff --git a/src/ru/nsu/ccfit/zuev/osu/game/SpritePool.java b/src/ru/nsu/ccfit/zuev/osu/game/SpritePool.java index fd29b85e7..13e532434 100644 --- a/src/ru/nsu/ccfit/zuev/osu/game/SpritePool.java +++ b/src/ru/nsu/ccfit/zuev/osu/game/SpritePool.java @@ -15,8 +15,8 @@ public class SpritePool { private static SpritePool instance = new SpritePool(); private static int CAPACITY = 250; - private final Map> sprites = new HashMap>(); - private final Map> animsprites = new HashMap>(); + private final Map> sprites = new HashMap<>(); + private final Map> animsprites = new HashMap<>(); int count = 0; private int spritesCreated = 0; private SpritePool() { @@ -47,7 +47,7 @@ synchronized public void putSprite(final String name, final Sprite sprite) { if (sprites.containsKey(name)) { sprites.get(name).add(sprite); } else { - final LinkedList list = new LinkedList(); + final LinkedList list = new LinkedList<>(); list.add(sprite); sprites.put(name, list); } @@ -124,7 +124,7 @@ synchronized public void putAnimSprite(final String name, if (animsprites.containsKey(name)) { animsprites.get(name).add(sprite); } else { - final LinkedList list = new LinkedList(); + final LinkedList list = new LinkedList<>(); list.add(sprite); animsprites.put(name, list); } diff --git a/src/ru/nsu/ccfit/zuev/osu/helper/CentredSprite.java b/src/ru/nsu/ccfit/zuev/osu/helper/CentredSprite.java index 89a43c493..d122f33c2 100644 --- a/src/ru/nsu/ccfit/zuev/osu/helper/CentredSprite.java +++ b/src/ru/nsu/ccfit/zuev/osu/helper/CentredSprite.java @@ -7,8 +7,8 @@ public class CentredSprite extends Sprite { public CentredSprite(final float pX, final float pY, final TextureRegion pTextureRegion) { - super(pX - pTextureRegion.getWidth() / 2, pY - - pTextureRegion.getHeight() / 2, pTextureRegion); + super(pX - (float) pTextureRegion.getWidth() / 2, pY + - (float) pTextureRegion.getHeight() / 2, pTextureRegion); } } diff --git a/src/ru/nsu/ccfit/zuev/osu/helper/FileUtils.java b/src/ru/nsu/ccfit/zuev/osu/helper/FileUtils.java index 2a6b6ed8c..77671986c 100644 --- a/src/ru/nsu/ccfit/zuev/osu/helper/FileUtils.java +++ b/src/ru/nsu/ccfit/zuev/osu/helper/FileUtils.java @@ -3,34 +3,27 @@ import android.os.Build; import android.os.Environment; +import net.lingala.zip4j.ZipFile; + +import org.anddev.andengine.util.Debug; + import java.io.BufferedInputStream; -import java.io.FileInputStream; import java.io.File; import java.io.FileFilter; -import java.io.FileNotFoundException; +import java.io.FileInputStream; import java.io.IOException; - -// TODO: Implement zhanghai/AndroidRetroFile import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; - import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; - import java.util.Arrays; import java.util.LinkedList; -import net.lingala.zip4j.ZipFile; -import net.lingala.zip4j.exception.ZipException; - import okio.BufferedSink; import okio.Okio; import okio.Source; - -import org.anddev.andengine.util.Debug; - import ru.nsu.ccfit.zuev.osu.Config; import ru.nsu.ccfit.zuev.osu.LibraryManager; import ru.nsu.ccfit.zuev.osu.ToastLogger; @@ -40,14 +33,14 @@ public class FileUtils { private FileUtils() {} - public static void copy(File from, File to) throws FileNotFoundException, IOException { + public static void copy(File from, File to) throws IOException { try (Source source = Okio.source(from); BufferedSink bufferedSink = Okio.buffer(Okio.sink(to))) { bufferedSink.writeAll(source); } } - public static void move(File from, File to) throws FileNotFoundException, IOException { + public static void move(File from, File to) throws IOException { copy(from, to); from.delete(); } @@ -60,8 +53,6 @@ public static boolean extractZip(final String sourcePath, final String targetPat return false; } - ToastLogger.addToLog("Importing " + sourcePath); - String sourceFileName = file.getName(); final String folderName = sourceFileName.substring(0, sourceFileName.length() - 4); @@ -70,8 +61,7 @@ public static boolean extractZip(final String sourcePath, final String targetPat folderFile.mkdirs(); } - try { - ZipFile zip = new ZipFile(file); + try (ZipFile zip = new ZipFile(file)) { if(!zip.isValidZipFile()) { ToastLogger.showText( StringTable.format(R.string.message_error, "Invalid file"), @@ -87,7 +77,7 @@ public static boolean extractZip(final String sourcePath, final String targetPat || sourceFileName.toLowerCase().endsWith(".osk")) { file.delete(); } - } catch (final ZipException e) { + } catch (final IOException e) { Debug.e("FileUtils.extractZip: " + e.getMessage(), e); int extensionIndex = sourceFileName.lastIndexOf('.'); @@ -119,8 +109,8 @@ public static String getFileChecksum(String algorithm, File file) { in.close(); byte[] bytes = digest.digest(); - for(int i = 0; i < bytes.length; i++) { - sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1)); + for (byte aByte : bytes) { + sb.append(Integer.toString((aByte & 0xff) + 0x100, 16).substring(1)); } }catch(IOException e) { Debug.e("getFileChecksum " + e.getMessage(), e); @@ -177,25 +167,19 @@ public static File[] listFiles(File directory, String[] endsWithExtensions) { } return false; }); - }else if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { + }else { return listFiles(directory, file -> { String filename = file.getName().toLowerCase(); return Arrays.stream(endsWithExtensions).anyMatch(filename::endsWith); }); } - return null; } public static File[] listFiles(File directory, FileFilter filter) { - File[] filelist = null; + File[] filelist; if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { - LinkedList cachedFiles = new LinkedList(); - DirectoryStream.Filter directoryFilter = new DirectoryStream.Filter() { - @Override - public boolean accept(Path entry) { - return filter.accept(entry.toFile()); - } - }; + LinkedList cachedFiles = new LinkedList<>(); + DirectoryStream.Filter directoryFilter = entry -> filter.accept(entry.toFile()); try(DirectoryStream stream = Files.newDirectoryStream(Paths.get(directory.getAbsolutePath()), directoryFilter)) { for(Path path : stream) { cachedFiles.add(path.toFile()); @@ -203,7 +187,7 @@ public boolean accept(Path entry) { }catch(Exception err) { Debug.e("FileUtils.listFiles: " + err.getMessage(), err); } - filelist = cachedFiles.toArray(new File[cachedFiles.size()]); + filelist = cachedFiles.toArray(new File[0]); }else { filelist = directory.listFiles(filter); } diff --git a/src/ru/nsu/ccfit/zuev/osu/helper/MD5Calcuator.java b/src/ru/nsu/ccfit/zuev/osu/helper/MD5Calculator.java similarity index 74% rename from src/ru/nsu/ccfit/zuev/osu/helper/MD5Calcuator.java rename to src/ru/nsu/ccfit/zuev/osu/helper/MD5Calculator.java index b7f75546a..f65c39a0a 100644 --- a/src/ru/nsu/ccfit/zuev/osu/helper/MD5Calcuator.java +++ b/src/ru/nsu/ccfit/zuev/osu/helper/MD5Calculator.java @@ -7,11 +7,9 @@ import java.math.BigInteger; import java.security.MessageDigest; -public class MD5Calcuator { +public class MD5Calculator { public static String getFileMD5(final File file) { - String md5 = ""; - try { - FileInputStream in = new FileInputStream(file); + try (FileInputStream in = new FileInputStream(file)) { MessageDigest digester = MessageDigest.getInstance("MD5"); byte[] bytes = new byte[8192]; int byteCount; @@ -20,34 +18,34 @@ public static String getFileMD5(final File file) { } final BigInteger hash = new BigInteger(1, digester.digest()); - md5 = hash.toString(16); + StringBuilder md5 = new StringBuilder(hash.toString(16)); while (md5.length() < 32) { - md5 = "0" + md5; + md5.insert(0, "0"); } - in.close(); + return md5.toString(); } catch (Exception e) { Debug.e("MD5Calculator: " + e.getMessage()); } - return md5; + return ""; } public static String getStringMD5(final String str) { - String md5 = ""; try { MessageDigest digester = MessageDigest.getInstance("MD5"); digester.update(str.getBytes()); final BigInteger hash = new BigInteger(1, digester.digest()); - md5 = hash.toString(16); + StringBuilder md5 = new StringBuilder(hash.toString(16)); while (md5.length() < 32) { - md5 = "0" + md5; + md5.insert(0, "0"); } + return md5.toString(); } catch (Exception e) { Debug.e("MD5Calculator: " + e.getMessage()); } - return md5; + return ""; } } diff --git a/src/ru/nsu/ccfit/zuev/osu/helper/ModifierFactory.java b/src/ru/nsu/ccfit/zuev/osu/helper/ModifierFactory.java index edfb25538..769935082 100644 --- a/src/ru/nsu/ccfit/zuev/osu/helper/ModifierFactory.java +++ b/src/ru/nsu/ccfit/zuev/osu/helper/ModifierFactory.java @@ -9,7 +9,7 @@ public class ModifierFactory { private static ModifierFactory instance = new ModifierFactory(); - private final Queue pool = new LinkedList(); + private final Queue pool = new LinkedList<>(); private ModifierFactory() { } diff --git a/src/ru/nsu/ccfit/zuev/osu/menu/FilterMenu.java b/src/ru/nsu/ccfit/zuev/osu/menu/FilterMenu.java deleted file mode 100644 index 91188f54c..000000000 --- a/src/ru/nsu/ccfit/zuev/osu/menu/FilterMenu.java +++ /dev/null @@ -1,405 +0,0 @@ -package ru.nsu.ccfit.zuev.osu.menu; - -import android.app.Activity; -import android.content.Context; -import android.content.SharedPreferences; - -import androidx.preference.PreferenceManager; - -import com.edlplan.ui.fragment.FavoriteManagerFragment; -import com.edlplan.ui.fragment.FilterMenuFragment; - -import org.anddev.andengine.engine.handler.IUpdateHandler; -import org.anddev.andengine.entity.primitive.Rectangle; -import org.anddev.andengine.entity.scene.Scene; -import org.anddev.andengine.entity.text.ChangeableText; -import org.anddev.andengine.entity.text.Text; -import org.anddev.andengine.input.touch.TouchEvent; -import org.anddev.andengine.opengl.font.Font; - -import ru.nsu.ccfit.zuev.osu.Config; -import ru.nsu.ccfit.zuev.osu.GlobalManager; -import ru.nsu.ccfit.zuev.osu.ResourceManager; -import ru.nsu.ccfit.zuev.osu.Utils; -import ru.nsu.ccfit.zuev.osu.helper.InputManager; -import ru.nsu.ccfit.zuev.osu.helper.StringTable; -import ru.nsu.ccfit.zuev.osu.helper.TextButton; -import ru.nsu.ccfit.zuev.osu.menu.SongMenu.SortOrder; -import ru.nsu.ccfit.zuev.osuplus.R; - -public class FilterMenu implements IUpdateHandler, IFilterMenu { - private Context configContext = null; - private static IFilterMenu instance; - private Scene scene = null; - private ChangeableText filterText; - private String filter = ""; - private ChangeableText sortText; - private SongMenu menu; - private SortOrder order = SortOrder.Title; - private boolean favoritesOnly = false; - private String favoriteFolder = null; - - private FilterMenu() { - } - - public static IFilterMenu getInstance() { - if (instance == null) { - instance = new FilterMenuFragment(); - } - return instance; - } - - @Override - public String getFavoriteFolder() { - return favoriteFolder; - } - - public void loadConfig(final Context context) { - final SharedPreferences prefs = PreferenceManager - .getDefaultSharedPreferences(context); - - final int sortOrder = prefs.getInt("sortorder", 0); - switch (sortOrder) { - case 1: - order = SortOrder.Artist; - break; - case 2: - order = SortOrder.Creator; - break; - case 3: - order = SortOrder.Date; - break; - case 4: - order = SortOrder.Bpm; - break; - case 5: - order = SortOrder.Stars; - break; - case 6: - order = SortOrder.Length; - break; - default: - order = SortOrder.Title; - break; - } - configContext = context; - setSortText(); - } - - public void saveConfig() { - if (configContext == null) { - return; - } - - final SharedPreferences prefs = PreferenceManager - .getDefaultSharedPreferences(configContext); - final SharedPreferences.Editor editor = prefs.edit(); - - switch (order) { - case Artist: - editor.putInt("sortorder", 1); - break; - case Creator: - editor.putInt("sortorder", 2); - break; - case Date: - editor.putInt("sortorder", 3); - break; - case Bpm: - editor.putInt("sortorder", 4); - break; - case Stars: - editor.putInt("sortorder", 5); - break; - case Length: - editor.putInt("sortorder", 6); - break; - default: - editor.putInt("sortorder", 0); - break; - } - - editor.apply(); - } - - public void setSongMenu(final SongMenu menu) { - this.menu = menu; - } - - public void reload() { - init(); - } - - public void init() { - scene = new Scene(); - scene.setBackgroundEnabled(false); - final Rectangle bg = new Rectangle(0, 0, Config.getRES_WIDTH(), - Config.getRES_HEIGHT()); - bg.setColor(0, 0, 0, 0.7f); - scene.attachChild(bg); - - final Text caption = new Text(0, Utils.toRes(60), ResourceManager - .getInstance().getFont("CaptionFont"), - StringTable.get(R.string.menu_search_title)); - caption.setPosition(Config.getRES_WIDTH() / 2f - caption.getWidth() / 2, - caption.getY()); - scene.attachChild(caption); - - final Font font = ResourceManager.getInstance().getFont("font"); - - final Text capt1 = new Text(Utils.toRes(100), Utils.toRes(160), font, - StringTable.get(R.string.menu_search_filter)); - capt1.setPosition(Config.getRES_WIDTH() / 4f - capt1.getWidth(), capt1.getY()); - scene.attachChild(capt1); - - final Rectangle filterBorder = new Rectangle(capt1.getX(), - Utils.toRes(195), Utils.toRes(330), capt1.getHeight() - + Utils.toRes(30)); - scene.attachChild(filterBorder); - filterBorder.setColor(1, 150f / 255, 0); - filterBorder.setVisible(false); - final Rectangle filterBg = new Rectangle(filterBorder.getX() + 5, - Utils.toRes(200), Utils.toRes(320), capt1.getHeight() - + Utils.toRes(20)) { - - @Override - public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, - final float pTouchAreaLocalX, final float pTouchAreaLocalY) { - if (pSceneTouchEvent.isActionDown()) { - filterBorder.setVisible(true); - InputManager.getInstance().startInput( - FilterMenu.getInstance().getFilter(), 20); - return true; - } - return false; - } - }; - scene.registerTouchArea(filterBg); - scene.attachChild(filterBg); - - filterText = new ChangeableText(capt1.getX(), Utils.toRes(210), font, - filter, 21); - filterText.setColor(0, 0, 0); - scene.attachChild(filterText); - - final Text capt2 = new Text(Utils.toRes(700), Utils.toRes(160), font, - StringTable.get(R.string.menu_search_sort)); - capt2.setPosition(Config.getRES_WIDTH() * 2f / 3 - capt2.getWidth(), capt2.getY()); - scene.attachChild(capt2); - - final Rectangle sortBg = new Rectangle(capt2.getX(), Utils.toRes(200), - Utils.toRes(200), capt2.getHeight() + Utils.toRes(20)) { - - @Override - public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, - final float pTouchAreaLocalX, final float pTouchAreaLocalY) { - if (pSceneTouchEvent.isActionDown()) { - SortOrder newOrder; - switch (order) { - case Title: - newOrder = SortOrder.Artist; - break; - case Artist: - newOrder = SortOrder.Creator; - break; - case Creator: - newOrder = SortOrder.Date; - break; - case Date: - newOrder = SortOrder.Bpm; - break; - case Bpm: - newOrder = SortOrder.Stars; - break; - case Stars: - newOrder = SortOrder.Length; - break; - default: - newOrder = SortOrder.Title; - break; - } - order = newOrder; - setSortText(); - saveConfig(); - return true; - } - return false; - } - }; - scene.registerTouchArea(sortBg); - scene.attachChild(sortBg); - sortText = new ChangeableText(capt2.getX() + 5, - Utils.toRes(210), font, - StringTable.get(R.string.menu_search_sort_title), 10); - sortText.setColor(0, 0, 0); - setSortText(); - sortText.detachSelf(); - scene.attachChild(sortText); - - final TextButton back = new TextButton(ResourceManager - .getInstance().getFont("CaptionFont"), - StringTable.get(R.string.menu_mod_back)) { - - @Override - public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, - final float pTouchAreaLocalX, final float pTouchAreaLocalY) { - if (pSceneTouchEvent.isActionUp()) { - hideMenu(); - return true; - } - return false; - } - }; - back.setWidth(Utils.toRes(400)); - back.setScale(1.2f); - back.setPosition(Config.getRES_WIDTH() / 2f - back.getWidth() / 2, Config.getRES_HEIGHT() * 3f / 4 - back.getHeight() / 2); - back.setColor(66 / 255f, 76 / 255f, 80 / 255f); - scene.attachChild(back); - scene.registerTouchArea(back); - - final ChangeableText favs = new ChangeableText(capt1.getX(), - Utils.toRes(300), ResourceManager.getInstance().getFont( - "CaptionFont"), - StringTable.get(R.string.menu_search_favsdisabled)) { - - @Override - public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, - final float pTouchAreaLocalX, final float pTouchAreaLocalY) { - if (pSceneTouchEvent.isActionUp()) { - if (favoritesOnly) { - setText(StringTable - .get(R.string.menu_search_favsdisabled)); - setColor(1, 1, 1); - } else { - setText(StringTable - .get(R.string.menu_search_favsenabled)); - setColor(0, 1, 0); - } - favoritesOnly = !favoritesOnly; - return true; - } - return false; - } - }; - if (favoritesOnly) { - favs.setText(StringTable.get(R.string.menu_search_favsenabled)); - favs.setColor(0, 1, 0); - } - favs.setPosition(capt1.getX(), - favs.getY()); - scene.attachChild(favs); - scene.registerTouchArea(favs); - - - final ChangeableText folder = new ChangeableText(favs.getX(), - favs.getY() + favs.getHeight() + Utils.toRes(20), ResourceManager.getInstance().getFont( - "CaptionFont"), - StringTable.get(R.string.favorite_folder) + " " + (favoriteFolder == null ? StringTable.get(R.string.favorite_default) : favoriteFolder), 40) { - @Override - public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, - final float pTouchAreaLocalX, final float pTouchAreaLocalY) { - if (pSceneTouchEvent.isActionUp()) { - //显示选择收藏夹的dialog - GlobalManager.getInstance().getMainActivity().runOnUiThread(() -> { - FavoriteManagerFragment dialog = new FavoriteManagerFragment(); - dialog.showToSelectFloder(folder1 -> { - favoriteFolder = folder1; - this.setText(StringTable.get(R.string.favorite_folder) + " " + (favoriteFolder == null ? StringTable.get(R.string.favorite_default) : favoriteFolder)); - }); - }); - return true; - } - return false; - } - }; - - folder.setPosition(favs.getX(), - favs.getY() + favs.getHeight() + Utils.toRes(20)); - scene.attachChild(folder); - scene.registerTouchArea(folder); - - scene.registerUpdateHandler(this); - scene.setTouchAreaBindingEnabled(true); - } - - public void hideMenu() { - if (menu != null) { - menu.getScene().clearChildScene(); - menu.loadFilter(this); - scene = null; - } - } - - @Override - public void showMenu(SongMenu parent) { - reload(); - setSongMenu(parent); - parent.scene.setChildScene( - scene, false, - true, true); - } - - private void setSortText() { - if (sortText == null) { - return; - } - String s; - switch (order) { - case Title: - s = StringTable.get(R.string.menu_search_sort_title); - break; - case Artist: - s = StringTable.get(R.string.menu_search_sort_artist); - break; - case Date: - s = StringTable.get(R.string.menu_search_sort_date); - break; - case Bpm: - s = StringTable.get(R.string.menu_search_sort_bpm); - break; - case Stars: - s = StringTable.get(R.string.menu_search_sort_stars); - break; - case Length: - s = StringTable.get(R.string.menu_search_sort_length); - break; - default: - s = StringTable.get(R.string.menu_search_sort_creator); - break; - } - ((Activity) configContext).runOnUiThread(() -> sortText.setText(s)); - } - - public Scene getScene() { - if (scene == null) { - init(); - } - return scene; - } - - public void onUpdate(final float pSecondsElapsed) { - if (InputManager.getInstance().isChanged()) { - filter = InputManager.getInstance().getText(); - filterText.setText(filter); - } - } - - - public void reset() { - // TODO Auto-generated method stub - - } - - public SortOrder getOrder() { - return order; - } - - public String getFilter() { - return filter; - } - - public boolean isFavoritesOnly() { - return favoritesOnly; - } - -} diff --git a/src/ru/nsu/ccfit/zuev/osu/menu/MenuItem.java b/src/ru/nsu/ccfit/zuev/osu/menu/MenuItem.java index e58e58f6a..5bdbe8bc1 100644 --- a/src/ru/nsu/ccfit/zuev/osu/menu/MenuItem.java +++ b/src/ru/nsu/ccfit/zuev/osu/menu/MenuItem.java @@ -251,7 +251,7 @@ public void applyFilter(final String filter, final boolean favs, Set lim } } - if (filter.equals("")) { + if (filter.isEmpty()) { canVisible = true; } diff --git a/src/ru/nsu/ccfit/zuev/osu/menu/ModMenu.java b/src/ru/nsu/ccfit/zuev/osu/menu/ModMenu.java index 8a8d4434c..3ff0798cb 100644 --- a/src/ru/nsu/ccfit/zuev/osu/menu/ModMenu.java +++ b/src/ru/nsu/ccfit/zuev/osu/menu/ModMenu.java @@ -55,6 +55,7 @@ public class ModMenu implements IModSwitcher { private Float customOD = null; private Float customHP = null; private Float customCS = null; + private InGameSettingMenu menu; private ModMenu() { mod = EnumSet.noneOf(GameMod.class); @@ -81,7 +82,11 @@ public void show(Scene scene, TrackInfo selectedTrack) { parent = scene; setSelectedTrack(selectedTrack); scene.setChildScene(getScene(), false, true, true); - Execution.uiThread(InGameSettingMenu.getInstance()::show); + if (menu == null) { + menu = new InGameSettingMenu(); + } + + Execution.uiThread(menu::show); update(); } @@ -156,7 +161,8 @@ public void hide(boolean updatePlayerMods) { parent.clearChildScene(); parent = null; } - InGameSettingMenu.getInstance().dismiss(); +// InGameSettingMenu.Companion.getInstance().dismiss(); + menu.dismiss(); if (Multiplayer.isConnected()) { @@ -196,6 +202,8 @@ public void hideByFrag() { parent.clearChildScene(); parent = null; } + + menu = null; } private void addButton(int x, int y, String texture, GameMod mod) { @@ -225,6 +233,8 @@ public void init() { multiplierText.setScale(1.2f); scene.attachChild(multiplierText); + menu = new InGameSettingMenu(); + changeMultiplierText(); final int offset = 100; @@ -581,4 +591,8 @@ public Float getCustomCS() { public void setCustomCS(@Nullable Float customCS) { this.customCS = customCS; } + + public InGameSettingMenu getMenu() { + return menu; + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/menu/SettingsMenu.java b/src/ru/nsu/ccfit/zuev/osu/menu/SettingsMenu.java index 696859c6a..0b811f8e3 100644 --- a/src/ru/nsu/ccfit/zuev/osu/menu/SettingsMenu.java +++ b/src/ru/nsu/ccfit/zuev/osu/menu/SettingsMenu.java @@ -29,6 +29,7 @@ import com.google.android.material.snackbar.Snackbar; import java.io.File; +import java.util.Objects; import com.reco1l.framework.lang.execution.Async; import com.reco1l.legacy.UpdateManager; @@ -48,6 +49,8 @@ import static android.content.Intent.ACTION_VIEW; +import org.anddev.andengine.util.Debug; + public class SettingsMenu extends SettingsFragment { public static final String REGISTER_URL = "https://" + OnlineManager.hostname + "/user/?action=register"; @@ -65,10 +68,15 @@ public void onCreate(Bundle savedInstanceState) { public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { setPreferencesFromResource(R.xml.options, rootKey); - SkinPathPreference skinPath = (SkinPathPreference) findPreference("skinPath"); + SkinPathPreference skinPath = findPreference("skinPath"); + if (skinPath == null) { + Debug.w("skinPath is null"); + return; + } + skinPath.reloadSkinList(); skinPath.setOnPreferenceChangeListener((preference, newValue) -> { - if(GlobalManager.getInstance().getSkinNow() != newValue.toString()) { + if(!Objects.equals(GlobalManager.getInstance().getSkinNow(), newValue.toString())) { var loading = new LoadingFragment(); loading.show(); @@ -91,44 +99,42 @@ public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { // screens mParentScreen = parentScreen = getPreferenceScreen(); - ((PreferenceScreen) findPreference("onlineOption")).setOnPreferenceClickListener(preference -> { + ((PreferenceScreen) Objects.requireNonNull(findPreference("onlineOption"))).setOnPreferenceClickListener(preference -> { setPreferenceScreen((PreferenceScreen) preference); return true; }); - ((PreferenceScreen) findPreference("general")).setOnPreferenceClickListener(preference -> { + ((PreferenceScreen) Objects.requireNonNull(findPreference("general"))).setOnPreferenceClickListener(preference -> { setPreferenceScreen((PreferenceScreen) preference); return true; }); - ((PreferenceScreen) findPreference("color")).setOnPreferenceClickListener(preference -> { - parentScreen = (PreferenceScreen) findPreference("general"); + ((PreferenceScreen) Objects.requireNonNull(findPreference("color"))).setOnPreferenceClickListener(preference -> { + parentScreen = findPreference("general"); setPreferenceScreen((PreferenceScreen) preference); return true; }); - ((PreferenceScreen) findPreference("sound")).setOnPreferenceClickListener(preference -> { + ((PreferenceScreen) Objects.requireNonNull(findPreference("sound"))).setOnPreferenceClickListener(preference -> { setPreferenceScreen((PreferenceScreen) preference); return true; }); - ((PreferenceScreen) findPreference("beatmaps")).setOnPreferenceClickListener(preference -> { + ((PreferenceScreen) Objects.requireNonNull(findPreference("beatmaps"))).setOnPreferenceClickListener(preference -> { setPreferenceScreen((PreferenceScreen) preference); return true; }); - ((PreferenceScreen) findPreference("advancedopts")).setOnPreferenceClickListener(preference -> { + ((PreferenceScreen) Objects.requireNonNull(findPreference("advancedopts"))).setOnPreferenceClickListener(preference -> { setPreferenceScreen((PreferenceScreen) preference); return true; }); // screens END - final EditTextPreference onlinePassword = (EditTextPreference) findPreference("onlinePassword"); - onlinePassword.setOnBindEditTextListener(editText -> { - editText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); - }); + final EditTextPreference onlinePassword = Objects.requireNonNull(findPreference("onlinePassword")); + onlinePassword.setOnBindEditTextListener(editText -> editText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD)); - final EditTextPreference skinToppref = (EditTextPreference) findPreference("skinTopPath"); + final EditTextPreference skinToppref = Objects.requireNonNull(findPreference("skinTopPath")); skinToppref.setOnPreferenceChangeListener((preference, newValue) -> { if (newValue.toString().trim().length() == 0) { skinToppref.setText(Config.getCorePath() + "Skin/"); @@ -152,31 +158,31 @@ public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { }); final Preference pref = findPreference("clear"); - pref.setOnPreferenceClickListener(preference -> { + Objects.requireNonNull(pref).setOnPreferenceClickListener(preference -> { LibraryManager.INSTANCE.clearCache(); return true; }); final Preference clearProps = findPreference("clear_properties"); - clearProps.setOnPreferenceClickListener(preference -> { + Objects.requireNonNull(clearProps).setOnPreferenceClickListener(preference -> { PropertiesLibrary.getInstance() .clear(mActivity); return true; }); final Preference register = findPreference("registerAcc"); - register.setOnPreferenceClickListener(preference -> { + Objects.requireNonNull(register).setOnPreferenceClickListener(preference -> { Intent intent = new Intent(ACTION_VIEW, Uri.parse(REGISTER_URL)); startActivity(intent); return true; }); final Preference update = findPreference("update"); - update.setOnPreferenceClickListener(preference -> { + Objects.requireNonNull(update).setOnPreferenceClickListener(preference -> { UpdateManager.INSTANCE.checkNewUpdates(false); return true; }); final Preference dither = findPreference("dither"); - dither.setOnPreferenceChangeListener((preference, newValue) -> { + Objects.requireNonNull(dither).setOnPreferenceChangeListener((preference, newValue) -> { if (Config.isUseDither() != (boolean) newValue) { GlobalManager.getInstance().getMainScene().restart(); } @@ -201,21 +207,21 @@ private void animateBackButton(@DrawableRes int newDrawable) { Animation animation = AnimationUtils.loadAnimation(mActivity, R.anim.rotate_360); animation.setAnimationListener(new Animation.AnimationListener() { public void onAnimationEnd(Animation animation) { - ImageButton backButton = (ImageButton) findViewById(R.id.back_button); + ImageButton backButton = Objects.requireNonNull(findViewById(R.id.back_button)); backButton.setImageDrawable(mActivity.getResources().getDrawable(newDrawable)); } public void onAnimationRepeat(Animation animation) {} public void onAnimationStart(Animation animation) {} }); - ((ImageButton) findViewById(R.id.back_button)).startAnimation(animation); + ((ImageButton) Objects.requireNonNull(findViewById(R.id.back_button))).startAnimation(animation); } private void animateView(@IdRes int viewId, @AnimRes int anim) { - findViewById(viewId).startAnimation(AnimationUtils.loadAnimation(mActivity, anim)); + ((View) Objects.requireNonNull(findViewById(viewId))).startAnimation(AnimationUtils.loadAnimation(mActivity, anim)); } private void setTitle(String title) { - ((TextView) findViewById(R.id.title)).setText(title); + ((TextView) Objects.requireNonNull(findViewById(R.id.title))).setText(title); } @Override @@ -248,13 +254,11 @@ private void navigateBack() { @Override protected void onLoadView() { - ((ImageButton) findViewById(R.id.back_button)).setOnClickListener(v -> { - navigateBack(); - }); + ((ImageButton) Objects.requireNonNull(findViewById(R.id.back_button))).setOnClickListener(v -> navigateBack()); } protected void playOnLoadAnim() { - View body = findViewById(R.id.body); + View body = Objects.requireNonNull(findViewById(R.id.body)); body.setAlpha(0); body.setTranslationX(400); body.animate().cancel(); @@ -268,7 +272,7 @@ protected void playOnLoadAnim() { } protected void playOnDismissAnim(Runnable action) { - View body = findViewById(R.id.body); + View body = Objects.requireNonNull(findViewById(R.id.body)); body.animate().cancel(); body.animate() .translationXBy(400) @@ -297,7 +301,7 @@ public void dismiss() { playOnDismissAnim(() -> { Config.loadConfig(mActivity); GlobalManager.getInstance().getMainScene().reloadOnlinePanel(); - GlobalManager.getInstance().getMainScene().loadTimeingPoints(false); + GlobalManager.getInstance().getMainScene().loadTimingPoints(false); GlobalManager.getInstance().getSongService().setVolume(Config.getBgmVolume()); GlobalManager.getInstance().getSongService().setGaming(false); SettingsMenu.super.dismiss(); diff --git a/src/ru/nsu/ccfit/zuev/osu/menu/SongMenu.java b/src/ru/nsu/ccfit/zuev/osu/menu/SongMenu.java index 049f8c48b..66348390c 100644 --- a/src/ru/nsu/ccfit/zuev/osu/menu/SongMenu.java +++ b/src/ru/nsu/ccfit/zuev/osu/menu/SongMenu.java @@ -6,6 +6,7 @@ import com.edlplan.ext.EdExtensionHelper; import com.edlplan.favorite.FavoriteLibrary; import com.edlplan.replay.OdrDatabase; +import com.edlplan.ui.fragment.FilterMenuFragment; import com.edlplan.ui.fragment.PropsMenuFragment; import com.edlplan.ui.fragment.ScoreMenuFragment; import com.reco1l.api.ibancho.RoomAPI; @@ -45,7 +46,6 @@ import ru.nsu.ccfit.zuev.osu.ToastLogger; import ru.nsu.ccfit.zuev.osu.TrackInfo; import ru.nsu.ccfit.zuev.osu.Utils; -import ru.nsu.ccfit.zuev.osu.async.AsyncTask; import ru.nsu.ccfit.zuev.osu.async.SyncTaskManager; import ru.nsu.ccfit.zuev.osu.beatmap.BeatmapData; import ru.nsu.ccfit.zuev.osu.beatmap.parser.BeatmapParser; @@ -70,6 +70,7 @@ public class SongMenu implements IUpdateHandler, MenuItemListener, IScrollBarListener { private final static Boolean musicMutex = true; + private final static Boolean bgMutex = true; private final Boolean backgroundMutex = true; public Scene scene; public Entity frontLayer = new Entity(); @@ -102,6 +103,7 @@ public class SongMenu implements IUpdateHandler, MenuItemListener, private ChangeableText trackInfo, mapper, beatmapInfo, beatmapInfo2, dimensionInfo; private boolean isSelectComplete = true; private AnimSprite scoringSwitcher = null; + private FilterMenuFragment filterMenu = null; private GroupType groupType = GroupType.MapSet; private Timer previousSelectionTimer; @@ -167,7 +169,7 @@ public synchronized void load() { selectedTrack = null; bgLoaded = true; SongMenuPool.getInstance().init(); - FilterMenu.getInstance().loadConfig(context); + loadFilterFragment(); // Preventing ModMenu to reload mod set if (!Multiplayer.isMultiplayer) @@ -191,12 +193,12 @@ public synchronized void load() { board = new ScoreBoard(scene, backLayer, this); - float oy = 10; +// float oy = 10; for (final BeatmapInfo i : LibraryManager.INSTANCE.getLibrary()) { final MenuItem item = new MenuItem(this, i); items.add(item); item.attachToScene(scene, backLayer); - oy += item.getHeight(); +// oy += item.getHeight(); } sortOrder = SortOrder.Title; sort(); @@ -473,7 +475,9 @@ public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, if (!moved) { velocityY = 0; - FilterMenu.getInstance().showMenu(SongMenu.this); + if (filterMenu == null) loadFilterFragment(); + + filterMenu.showMenu(SongMenu.this); } return true; } @@ -686,6 +690,16 @@ public boolean onAreaTouched(TouchEvent pSceneTouchEvent, } } + public void loadFilterFragment() { + filterMenu = new FilterMenuFragment(); + filterMenu.loadConfig(context); + } + + public void unloadFilterFragment() { + scene.clearChildScene(); + filterMenu = null; + } + public void toggleScoringSwitcher() { if (board.isShowOnlineScores()) { board.setShowOnlineScores(false); @@ -713,6 +727,7 @@ public void setRank() { public Scene getScene() { return scene; } + public FilterMenuFragment getFilterMenu() { return filterMenu; } public void show() { engine.setScene(scene); @@ -752,12 +767,11 @@ public void setFilter(final String filter, final SortOrder order, selectedItem = null; selectedTrack = null; } - System.gc(); } public void sort() { - if (!sortOrder.equals(FilterMenu.getInstance().getOrder())) { - sortOrder = FilterMenu.getInstance().getOrder(); + if (!sortOrder.equals(filterMenu.getOrder())) { + sortOrder = filterMenu.getOrder(); } Collections.sort(items, (i1, i2) -> { String s1; @@ -1111,7 +1125,7 @@ public void selectTrack(final TrackInfo track, boolean reloadBG) { } if (selectedTrack == track) { - synchronized (bgLoaded) { + synchronized (bgMutex) { if (!bgLoaded) { return; } @@ -1194,7 +1208,7 @@ public void selectTrack(final TrackInfo track, boolean reloadBG) { } scene.setBackground(new SpriteBackground(bg)); Config.setBackgroundQuality(quality); - synchronized (bgLoaded) { + synchronized (bgMutex) { bgLoaded = true; } } @@ -1222,30 +1236,27 @@ public void openScore(final int id, boolean showOnline, final String playerName) if (showOnline) { engine.setScene(new LoadingScreen().getScene()); ToastLogger.showTextId(R.string.online_loadrecord, false); - new AsyncTask() { - @Override - public void run() { - try { - String scorePack = OnlineManager.getInstance().getScorePack(id); - String[] params = scorePack.split("\\s+"); - if (params.length < 11) return; - - StatisticV2 stat = new StatisticV2(params); - if (stat.isLegacySC()) { - stat.processLegacySC(selectedTrack); - } - stat.setPlayerName(playerName); - scoreScene.load(stat, null, null, OnlineManager.getReplayURL(id), null, selectedTrack); - engine.setScene(scoreScene.getScene()); + Async.run(() -> { + try { + String scorePack = OnlineManager.getInstance().getScorePack(id); + String[] params = scorePack.split("\\s+"); + + if (params.length < 11) return; - } catch (OnlineManagerException e) { - Debug.e("Cannot load play info: " + e.getMessage(), e); - engine.setScene(scene); + StatisticV2 stat = new StatisticV2(params); + if (stat.isLegacySC()) { + stat.processLegacySC(selectedTrack); } + stat.setPlayerName(playerName); + scoreScene.load(stat, null, null, OnlineManager.getReplayURL(id), null, selectedTrack); + engine.setScene(scoreScene.getScene()); + } catch (OnlineManagerException e) { + Debug.e("Cannot load play info: " + e.getMessage(), e); + engine.setScene(scene); } - }.execute(); + }); return; } @@ -1454,7 +1465,7 @@ private void tryReloadMenuItems(SortOrder order) { private void reloadMenuItems(GroupType type) { if (!groupType.equals(type)) { groupType = type; - float oy = 10; +// float oy = 10; for (MenuItem item : items) { item.removeFromScene(); } @@ -1465,7 +1476,7 @@ private void reloadMenuItems(GroupType type) { final MenuItem item = new MenuItem(this, i); items.add(item); item.attachToScene(scene, backLayer); - oy += item.getHeight(); +// oy += item.getHeight(); } break; case SingleDiff: @@ -1474,18 +1485,17 @@ private void reloadMenuItems(GroupType type) { final MenuItem item = new MenuItem(this, i, j); items.add(item); item.attachToScene(scene, backLayer); - oy += item.getHeight(); +// oy += item.getHeight(); } } break; } - final String lowerFilter = FilterMenu.getInstance().getFilter().toLowerCase(); - final boolean favsOnly = FilterMenu.getInstance().isFavoritesOnly(); - final Set limit = FilterMenu.getInstance().getFavoriteFolder() == null ? null : FavoriteLibrary.get().getMaps(FilterMenu.getInstance().getFavoriteFolder()); + final String lowerFilter = filterMenu.getFilter().toLowerCase(); + final boolean favsOnly = filterMenu.isFavoritesOnly(); + final Set limit = FavoriteLibrary.get().getMaps(filterMenu.getFavoriteFolder()); for (final MenuItem item : items) { item.applyFilter(lowerFilter, favsOnly, limit); } - System.gc(); } } @@ -1498,7 +1508,7 @@ public void setStarsDisplay(float star) { } private void reSelectItem(String oldTrackFileName) { - if (!oldTrackFileName.equals("")) { + if (!oldTrackFileName.isEmpty()) { if (selectedTrack.getFilename().equals(oldTrackFileName) && items.size() > 1 && selectedItem != null && selectedItem.isVisible()) { velocityY = 0; float height = 0; diff --git a/src/ru/nsu/ccfit/zuev/osu/online/OnlineFileOperator.java b/src/ru/nsu/ccfit/zuev/osu/online/OnlineFileOperator.java index da3de58b3..1b5c587ed 100644 --- a/src/ru/nsu/ccfit/zuev/osu/online/OnlineFileOperator.java +++ b/src/ru/nsu/ccfit/zuev/osu/online/OnlineFileOperator.java @@ -32,11 +32,10 @@ public static void sendFile(String urlstr, String filename, String replayID) { } String checksum = FileUtils.getSHA256Checksum(file); - StringBuilder sb = new StringBuilder(); - sb.append(URLEncoder.encode(checksum, "UTF-8")); - sb.append("_"); - sb.append(URLEncoder.encode(replayID, "UTF-8")); - String signature = SecurityUtils.signRequest(sb.toString()); + String sb = URLEncoder.encode(checksum, "UTF-8") + + "_" + + URLEncoder.encode(replayID, "UTF-8"); + String signature = SecurityUtils.signRequest(sb); MediaType mime = MediaType.parse("application/octet-stream"); RequestBody fileBody = RequestBody.create(mime, file); @@ -48,10 +47,12 @@ public static void sendFile(String urlstr, String filename, String replayID) { .build(); Request request = new Request.Builder().url(urlstr) .post(requestBody).build(); - Response response = OnlineManager.client.newCall(request).execute(); - String responseMsg = response.body().string(); - - Debug.i("sendFile signatureResponse " + responseMsg); + try (Response response = OnlineManager.client.newCall(request).execute()) { + if (response.isSuccessful() && response.body() != null) { + String responseMsg = response.body().string(); + Debug.i("sendFile signatureResponse " + responseMsg); + } + } } catch (final IOException e) { Debug.e("sendFile IOException " + e.getMessage(), e); } catch (final Exception e) { @@ -85,15 +86,14 @@ public static boolean downloadFile(String urlstr, String filename, boolean check } Request request = builder.build(); - Response response = OnlineManager.client.newCall(request).execute(); - - if (response.isSuccessful()) { - BufferedSink sink = Okio.buffer(Okio.sink(file)); - sink.writeAll(response.body().source()); - sink.close(); + try (Response response = OnlineManager.client.newCall(request).execute()) { + if (response.isSuccessful() && response.body() != null) { + BufferedSink sink = Okio.buffer(Okio.sink(file)); + sink.writeAll(response.body().source()); + sink.close(); + } } - response.close(); return true; } catch (final IOException e) { Debug.e("downloadFile IOException " + e.getMessage(), e); diff --git a/src/ru/nsu/ccfit/zuev/osu/online/OnlineManager.java b/src/ru/nsu/ccfit/zuev/osu/online/OnlineManager.java index 018c68d98..3c5c6f83a 100644 --- a/src/ru/nsu/ccfit/zuev/osu/online/OnlineManager.java +++ b/src/ru/nsu/ccfit/zuev/osu/online/OnlineManager.java @@ -19,7 +19,7 @@ import ru.nsu.ccfit.zuev.osu.GlobalManager; import ru.nsu.ccfit.zuev.osu.ResourceManager; import ru.nsu.ccfit.zuev.osu.TrackInfo; -import ru.nsu.ccfit.zuev.osu.helper.MD5Calcuator; +import ru.nsu.ccfit.zuev.osu.helper.MD5Calculator; import ru.nsu.ccfit.zuev.osu.online.PostBuilder.RequestException; public class OnlineManager { @@ -123,7 +123,7 @@ public synchronized boolean logIn(String username, String password) throws Onlin post.addParam("username", username); post.addParam( "password", - MD5Calcuator.getStringMD5( + MD5Calculator.getStringMD5( escapeHTMLSpecialCharacters(addSlashes(String.valueOf(password).trim())) + "taikotaiko" )); post.addParam("version", onlineVersion); @@ -283,7 +283,7 @@ public ArrayList getTop(final File trackFile, final String hash) throws ArrayList response = sendRequest(post, endpoint + "getrank.php"); if (response == null) { - return new ArrayList(); + return new ArrayList<>(); } response.remove(0); @@ -298,7 +298,7 @@ public boolean loadAvatarToTextureManager() { public boolean loadAvatarToTextureManager(String avatarURL) { if (avatarURL == null || avatarURL.length() == 0) return false; - String filename = MD5Calcuator.getStringMD5(avatarURL); + String filename = MD5Calculator.getStringMD5(avatarURL); Debug.i("Loading avatar from " + avatarURL); Debug.i("filename = " + filename); File picfile = new File(Config.getCachePath(), filename); @@ -320,7 +320,7 @@ public boolean loadAvatarToTextureManager(String avatarURL) { } } else { // Avatar not found, download the default avatar - String defaultAvatarFilename = MD5Calcuator.getStringMD5(defaultAvatarURL); + String defaultAvatarFilename = MD5Calculator.getStringMD5(defaultAvatarURL); File avatarFile = new File(Config.getCachePath(), defaultAvatarFilename); OnlineFileOperator.downloadFile(defaultAvatarURL, avatarFile.getAbsolutePath()); diff --git a/src/ru/nsu/ccfit/zuev/osu/online/OnlinePanel.java b/src/ru/nsu/ccfit/zuev/osu/online/OnlinePanel.java index f1b0f75ec..e47911dca 100644 --- a/src/ru/nsu/ccfit/zuev/osu/online/OnlinePanel.java +++ b/src/ru/nsu/ccfit/zuev/osu/online/OnlinePanel.java @@ -47,13 +47,9 @@ public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTou if(OnlineManager.getInstance().isStayOnline()) { new ConfirmDialogFragment() .setMessage(R.string.dialog_visit_profile_page) - .showForResult(isAccepted -> { - GlobalManager.getInstance().getMainActivity().runOnUiThread(() -> { - new WebViewFragment().setURL( - WebViewFragment.PROFILE_URL + OnlineManager.getInstance().getUserId()) - .show(); - }); - }); + .showForResult(isAccepted -> GlobalManager.getInstance().getMainActivity().runOnUiThread(() -> new WebViewFragment().setURL( + WebViewFragment.PROFILE_URL + OnlineManager.getInstance().getUserId()) + .show())); } } return true; diff --git a/src/ru/nsu/ccfit/zuev/osu/online/OnlineScoring.java b/src/ru/nsu/ccfit/zuev/osu/online/OnlineScoring.java index 5bbff6b45..e9fc739a6 100644 --- a/src/ru/nsu/ccfit/zuev/osu/online/OnlineScoring.java +++ b/src/ru/nsu/ccfit/zuev/osu/online/OnlineScoring.java @@ -1,5 +1,6 @@ package ru.nsu.ccfit.zuev.osu.online; +import com.reco1l.framework.lang.execution.Async; import com.reco1l.legacy.ui.multiplayer.LobbyScene; import com.reco1l.legacy.ui.multiplayer.RoomScene; import org.anddev.andengine.util.Debug; @@ -9,13 +10,12 @@ import ru.nsu.ccfit.zuev.osu.ToastLogger; import ru.nsu.ccfit.zuev.osu.TrackInfo; -import ru.nsu.ccfit.zuev.osu.async.AsyncTask; import ru.nsu.ccfit.zuev.osu.scoring.StatisticV2; public class OnlineScoring { private static final int attemptCount = 5; private static OnlineScoring instance = null; - private Boolean onlineMutex = new Boolean(false); + private final Boolean onlineMutex = Boolean.FALSE; private OnlinePanel panel = null; private OnlinePanel secondPanel = null; private boolean avatarLoaded = false; @@ -35,7 +35,7 @@ public OnlinePanel getPanel() { } public OnlinePanel createSecondPanel() { - if (OnlineManager.getInstance().isStayOnline() == false) + if (!OnlineManager.getInstance().isStayOnline()) return null; secondPanel = new OnlinePanel(); secondPanel.setInfo(); @@ -75,126 +75,114 @@ public void updatePanelAvatars() { } public void login() { - if (OnlineManager.getInstance().isStayOnline() == false) + if (!OnlineManager.getInstance().isStayOnline()) return; avatarLoaded = false; - new AsyncTask() { - @Override - public void run() { - synchronized (onlineMutex) { - boolean success = false; - //Trying to send request - for (int i = 0; i < 3; i++) { - setPanelMessage("Logging in...", ""); + Async.run(() -> { + synchronized (onlineMutex) { + boolean success = false; + + //Trying to send request + for (int i = 0; i < 3; i++) { + setPanelMessage("Logging in...", ""); + try { + success = OnlineManager.getInstance().logIn(); + } catch (OnlineManager.OnlineManagerException e) { + Debug.e("Login error: " + e.getMessage()); + setPanelMessage("Login failed", "Retrying in 5 sec"); try { - success = OnlineManager.getInstance().logIn(); - } catch (OnlineManager.OnlineManagerException e) { - Debug.e("Login error: " + e.getMessage()); - setPanelMessage("Login failed", "Retrying in 5 sec"); - try { - Thread.sleep(3000); - } catch (InterruptedException e1) { - break; - } - continue; + Thread.sleep(3000); + } catch (InterruptedException e1) { + break; } - break; - } - if (success) { - updatePanels(); - OnlineManager.getInstance().setStayOnline(true); - loadAvatar(true); - } else { - setPanelMessage("Cannot log in", OnlineManager.getInstance().getFailMessage()); - OnlineManager.getInstance().setStayOnline(false); + continue; } + break; + } + if (success) { + updatePanels(); + OnlineManager.getInstance().setStayOnline(true); + loadAvatar(true); + } else { + setPanelMessage("Cannot log in", OnlineManager.getInstance().getFailMessage()); + OnlineManager.getInstance().setStayOnline(false); } } - }.execute(); + }); } public void startPlay(final TrackInfo track, final String hash) { - if (OnlineManager.getInstance().isStayOnline() == false) + if (!OnlineManager.getInstance().isStayOnline()) return; - new AsyncTask() { - @Override - public void run() { - synchronized (onlineMutex) { - for (int i = 0; i < attemptCount; i++) { - try { - OnlineManager.getInstance().startPlay(track, hash); - } catch (OnlineManager.OnlineManagerException e) { - Debug.e("Login error: " + e.getMessage()); - continue; - } - break; + Async.run(() -> { + synchronized (onlineMutex) { + for (int i = 0; i < attemptCount; i++) { + try { + OnlineManager.getInstance().startPlay(track, hash); + } catch (OnlineManager.OnlineManagerException e) { + Debug.e("Login error: " + e.getMessage()); + continue; } + break; + } - if (OnlineManager.getInstance().getFailMessage().length() > 0) { - ToastLogger.showText(OnlineManager.getInstance().getFailMessage(), true); - } + if (OnlineManager.getInstance().getFailMessage().length() > 0) { + ToastLogger.showText(OnlineManager.getInstance().getFailMessage(), true); } } - }.execute(); + }); } public void sendRecord(final StatisticV2 record, final SendingPanel panel, final String replay) { - if (OnlineManager.getInstance().isStayOnline() == false) - return; - if (OnlineManager.getInstance().isReadyToSend() == false) + if (!OnlineManager.getInstance().isStayOnline() || !OnlineManager.getInstance().isReadyToSend()) return; Debug.i("Sending score"); final String recordData = record.compile(); - new AsyncTask() { - @Override - public void run() { - boolean success = false; - synchronized (onlineMutex) { - for (int i = 0; i < attemptCount; i++) { - if (!record.isScoreValid()) { - Debug.e("Detected illegal actions."); - break; - } - - try { - success = OnlineManager.getInstance().sendRecord(recordData); - } catch (OnlineManager.OnlineManagerException e) { - Debug.e("Login error: " + e.getMessage()); - success = false; - } - - if (OnlineManager.getInstance().getFailMessage().length() > 0) { - ToastLogger.showText(OnlineManager.getInstance().getFailMessage(), true); - if (OnlineManager.getInstance().getFailMessage().equals("Invalid record data")) - i = attemptCount; - } else if (success) { - OnlineManager.getInstance().sendReplay(replay); - updatePanels(); - OnlineManager mgr = OnlineManager.getInstance(); - panel.show(mgr.getMapRank(), mgr.getScore(), mgr.getRank(), mgr.getAccuracy()); - break; - } + Async.run(() -> { + boolean success = false; + synchronized (onlineMutex) { + for (int i = 0; i < attemptCount; i++) { + if (!record.isScoreValid()) { + Debug.e("Detected illegal actions."); + break; + } + try { + success = OnlineManager.getInstance().sendRecord(recordData); + } catch (OnlineManager.OnlineManagerException e) { + Debug.e("Login error: " + e.getMessage()); + success = false; + } - try { - Thread.sleep(5000); - } catch (InterruptedException e) { - } + if (OnlineManager.getInstance().getFailMessage().length() > 0) { + ToastLogger.showText(OnlineManager.getInstance().getFailMessage(), true); + if (OnlineManager.getInstance().getFailMessage().equals("Invalid record data")) + i = attemptCount; + } else if (success) { + OnlineManager.getInstance().sendReplay(replay); + updatePanels(); + OnlineManager mgr = OnlineManager.getInstance(); + panel.show(mgr.getMapRank(), mgr.getScore(), mgr.getRank(), mgr.getAccuracy()); + break; } - if (!success) { - panel.setFail(); + try { + Thread.sleep(5000); + } catch (InterruptedException ignored) { } + } + if (!success) { + panel.setFail(); } } - }.execute(); + }); } public ArrayList getTop(final File trackFile, final String hash) { @@ -203,7 +191,7 @@ public ArrayList getTop(final File trackFile, final String hash) { return OnlineManager.getInstance().getTop(trackFile, hash); } catch (OnlineManager.OnlineManagerException e) { Debug.e("Cannot load scores " + e.getMessage()); - return new ArrayList(); + return new ArrayList<>(); } } } @@ -214,18 +202,15 @@ public void loadAvatar(final boolean both) { if (avatarUrl == null || avatarUrl.length() == 0) return; - new AsyncTask() { - @Override - public void run() { - synchronized (onlineMutex) { - avatarLoaded = OnlineManager.getInstance().loadAvatarToTextureManager(); - if (both) - updatePanelAvatars(); - else if (secondPanel != null) - secondPanel.setAvatar(avatarLoaded ? avatarUrl : null); - } + Async.run(() -> { + synchronized (onlineMutex) { + avatarLoaded = OnlineManager.getInstance().loadAvatarToTextureManager(); + if (both) + updatePanelAvatars(); + else if (secondPanel != null) + secondPanel.setAvatar(avatarLoaded ? avatarUrl : null); } - }.execute(); + }); } public boolean isAvatarLoaded() { diff --git a/src/ru/nsu/ccfit/zuev/osu/online/PostBuilder.java b/src/ru/nsu/ccfit/zuev/osu/online/PostBuilder.java index 5afd43b03..4694acd05 100644 --- a/src/ru/nsu/ccfit/zuev/osu/online/PostBuilder.java +++ b/src/ru/nsu/ccfit/zuev/osu/online/PostBuilder.java @@ -3,7 +3,6 @@ import com.dgsrz.bancho.security.SecurityUtils; import okhttp3.FormBody; -import okhttp3.RequestBody; import okhttp3.Response; import okhttp3.Request; @@ -16,11 +15,9 @@ import java.net.URLEncoder; import java.util.ArrayList; -import ru.nsu.ccfit.zuev.osuplus.BuildConfig; - public class PostBuilder { - private FormBody.Builder formBodyBuilder = new FormBody.Builder(); - private StringBuilder values = new StringBuilder(); + private final FormBody.Builder formBodyBuilder = new FormBody.Builder(); + private final StringBuilder values = new StringBuilder(); public void addParam(final String key, final String value) { try { @@ -29,8 +26,7 @@ public void addParam(final String key, final String value) { } formBodyBuilder.add(key, value); values.append(URLEncoder.encode(value, "UTF-8")); - } catch (UnsupportedEncodingException e) { - return; + } catch (UnsupportedEncodingException ignored) { } } @@ -58,14 +54,14 @@ public ArrayList requestWithAttempts(final String scriptUrl, int attempt || !(response.get(0).equals("FAIL") || response.get(0).equals("SUCCESS"))) { try { Thread.sleep(3000); - } catch (InterruptedException e) { + } catch (InterruptedException ignored) { } continue; } break; } - if (response == null) response = new ArrayList(); + if (response == null) response = new ArrayList<>(); if (response.isEmpty()) { response.add(""); @@ -74,25 +70,27 @@ public ArrayList requestWithAttempts(final String scriptUrl, int attempt } private ArrayList request(final String scriptUrl) throws RequestException { - ArrayList response = new ArrayList(); - - try { - Request request = new Request.Builder() - .url(scriptUrl) - .post(formBodyBuilder.build()) - .build(); - Response resp = OnlineManager.client.newCall(request).execute(); - - Debug.i("request url=" + scriptUrl); - Debug.i("request --------Content---------"); - String line = null; - BufferedReader reader = new BufferedReader(new StringReader(resp.body().string())); - while((line = reader.readLine()) != null) { - Debug.i(String.format("request [%d]: %s", response.size(), line)); - response.add(line); + ArrayList response = new ArrayList<>(); + + Request request = new Request.Builder() + .url(scriptUrl) + .post(formBodyBuilder.build()) + .build(); + + try (Response resp = OnlineManager.client.newCall(request).execute()) { + + if (resp.isSuccessful() && resp.body() != null) { + Debug.i("request url=" + scriptUrl); + Debug.i("request --------Content---------"); + String line; + BufferedReader reader = new BufferedReader(new StringReader(resp.body().string())); + while ((line = reader.readLine()) != null) { + Debug.i(String.format("request [%d]: %s", response.size(), line)); + response.add(line); + } + Debug.i("request url=" + scriptUrl); + Debug.i("request -----End of content-----"); } - Debug.i("request url=" + scriptUrl); - Debug.i("request -----End of content-----"); } catch(Exception e) { Debug.e(e.getMessage(), e); } diff --git a/src/ru/nsu/ccfit/zuev/osu/polygon/Spline.java b/src/ru/nsu/ccfit/zuev/osu/polygon/Spline.java index 9c08c49db..7978e09e1 100644 --- a/src/ru/nsu/ccfit/zuev/osu/polygon/Spline.java +++ b/src/ru/nsu/ccfit/zuev/osu/polygon/Spline.java @@ -20,16 +20,16 @@ public class Spline { private ArrayList m_points_copy = null; private ArrayList m_lengths = null; public Spline() { - m_ctrl_pts = new ArrayList(); + m_ctrl_pts = new ArrayList<>(); m_curve_type = CurveTypes.Linear; - m_path = new ArrayList(); - m_points = new ArrayList(); + m_path = new ArrayList<>(); + m_points = new ArrayList<>(); } public Spline(ArrayList theControlPoints, CurveTypes theCurveType) { - m_ctrl_pts = new ArrayList(theControlPoints); + m_ctrl_pts = new ArrayList<>(theControlPoints); m_curve_type = theCurveType; - m_path = new ArrayList(); - m_points = new ArrayList(); + m_path = new ArrayList<>(); + m_points = new ArrayList<>(); sliderthing(m_curve_type, m_ctrl_pts, m_path, m_points); } @@ -55,7 +55,7 @@ private static float Rho(Line line) { private static ArrayList CreateBezier(ArrayList input) { float DetailLevel2 = (float) DetailLevel; PointF[] working = new PointF[input.size()]; - ArrayList output = new ArrayList(); + ArrayList output = new ArrayList<>(); PointF lll; @@ -191,15 +191,13 @@ public static CurveTypes getCurveType(char c) { return CurveTypes.Catmull; case 'P': return CurveTypes.PerfectCurve; - case 'B': - return CurveTypes.Bezier; default: return CurveTypes.Bezier; } } public ArrayList getControlPoints() { - if (m_ctrl_pts_copy == null) m_ctrl_pts_copy = new ArrayList(m_ctrl_pts); + if (m_ctrl_pts_copy == null) m_ctrl_pts_copy = new ArrayList<>(m_ctrl_pts); return m_ctrl_pts_copy; } @@ -217,18 +215,18 @@ public void setType(CurveTypes type) { } public ArrayList getPath() { - if (m_path_copy == null) m_path_copy = new ArrayList(m_path); + if (m_path_copy == null) m_path_copy = new ArrayList<>(m_path); return m_path_copy; } public ArrayList getPoints() { - if (m_points_copy == null) m_points_copy = new ArrayList(m_points); + if (m_points_copy == null) m_points_copy = new ArrayList<>(m_points); return m_points_copy; } public ArrayList getLengths() { if (m_lengths == null) { - m_lengths = new ArrayList(m_path.size() + 1); + m_lengths = new ArrayList<>(m_path.size() + 1); float length_so_far = 0; for (int x = 0; x < m_path.size(); x++) { m_lengths.add(length_so_far); @@ -312,7 +310,7 @@ private void sliderthing(CurveTypes CurveType, ArrayList sliderCurvePoin int lastIndex = 0; for (int i = 0; i < sliderCurvePoints.size(); i++) if ((i > 0 && sliderCurvePoints.get(i) == sliderCurvePoints.get(i - 1)) || i == sliderCurvePoints.size() - 1) { - ArrayList thisLength = new ArrayList(sliderCurvePoints.subList(lastIndex, i - lastIndex + ((i == sliderCurvePoints.size() - 1) ? 1 : 0))); // + 1); // i145 + ArrayList thisLength = new ArrayList<>(sliderCurvePoints.subList(lastIndex, i - lastIndex + ((i == sliderCurvePoints.size() - 1) ? 1 : 0))); // + 1); // i145 ArrayList points1 = CreateBezier(thisLength); points.addAll(points1); @@ -389,7 +387,7 @@ public enum CurveTypes { /// /// Probably another XNA class? Guessing its structure based on usage /// - public class Line { + public static class Line { public PointF p1, p2; public Line(PointF Start, PointF End) { diff --git a/src/ru/nsu/ccfit/zuev/osu/scoring/ScoreLibrary.java b/src/ru/nsu/ccfit/zuev/osu/scoring/ScoreLibrary.java index 4bbac5852..f96f20aa7 100644 --- a/src/ru/nsu/ccfit/zuev/osu/scoring/ScoreLibrary.java +++ b/src/ru/nsu/ccfit/zuev/osu/scoring/ScoreLibrary.java @@ -51,7 +51,7 @@ public static String getTrackDir(final String track) { if (s.endsWith(".osu")) { return s.substring(0, s.indexOf('/')); } else { - return s.substring(s.indexOf('/') + 1, s.length()); + return s.substring(s.indexOf('/') + 1); } } @@ -105,9 +105,9 @@ private void loadOld(Context context) { if (obj instanceof Map) { if (versionStr.equals("scores1")) { final Map> oldStat = (Map>) obj; - scores = new HashMap>(); + scores = new HashMap<>(); for (final String str : oldStat.keySet()) { - final ArrayList newStat = new ArrayList(); + final ArrayList newStat = new ArrayList<>(); for (final Statistic s : oldStat.get(str)) { newStat.add(new StatisticV2(s)); } @@ -119,7 +119,7 @@ private void loadOld(Context context) { scores.put(str, newStat); } } - } else if (versionStr.equals("scores2")) { + } else { scores = (Map>) obj; } } diff --git a/src/ru/nsu/ccfit/zuev/osu/scoring/ScoringScene.java b/src/ru/nsu/ccfit/zuev/osu/scoring/ScoringScene.java index 8ee2feba6..28b21e65a 100644 --- a/src/ru/nsu/ccfit/zuev/osu/scoring/ScoringScene.java +++ b/src/ru/nsu/ccfit/zuev/osu/scoring/ScoringScene.java @@ -1,7 +1,7 @@ package ru.nsu.ccfit.zuev.osu.scoring; -import com.edlplan.ui.fragment.InGameSettingMenu; import com.edlplan.framework.utils.functionality.SmartIterator; +import com.edlplan.ui.fragment.InGameSettingMenu; import com.reco1l.framework.lang.Execution; import com.reco1l.legacy.Multiplayer; import com.reco1l.legacy.ui.multiplayer.RoomScene; @@ -74,7 +74,6 @@ public void load(final StatisticV2 stat, final TrackInfo track, if (replay != null && track == null) { replayStat = stat; } - InGameSettingMenu.getInstance().dismiss(); TextureRegion tex = ResourceManager.getInstance() .getTextureIfLoaded("::background"); if (tex == null) { @@ -140,15 +139,15 @@ public void load(final StatisticV2 stat, final TrackInfo track, final Sprite rankingText = new Sprite(Utils.toRes(580), 0, ResourceManager.getInstance().getTexture("ranking-title")); - rankingText.setPosition(Config.getRES_WIDTH() * 5 / 6 - rankingText.getWidth() / 2, 0); + rankingText.setPosition((float) (Config.getRES_WIDTH() * 5) / 6 - rankingText.getWidth() / 2, 0); scene.attachChild(rankingText); - String scoreStr = String.valueOf(stat.getTotalScoreWithMultiplier()); + StringBuilder scoreStr = new StringBuilder(String.valueOf(stat.getTotalScoreWithMultiplier())); while (scoreStr.length() < 8) { - scoreStr = '0' + scoreStr; + scoreStr.insert(0, "0"); } final ScoreNumber scoreNum = new ScoreNumber(Utils.toRes(220 + x), - Utils.toRes(18 + y), scoreStr, 1, false); + Utils.toRes(18 + y), scoreStr.toString(), 1, false); scoreNum.attachToScene(scene); final ScoreNumber hit300num = new ScoreNumber(Utils.toRes(138 + x), @@ -185,7 +184,7 @@ public void load(final StatisticV2 stat, final TrackInfo track, ResourceManager.getInstance().getTexture("ranking-accuracy")); scene.attachChild(accText); final ScoreNumber maxCombo = new ScoreNumber(Utils.toRes(20 + x), - Utils.toRes(maxComboText.getY() + 38), String.valueOf(stat.getMaxCombo()) + "x", 1, + Utils.toRes(maxComboText.getY() + 38), stat.getMaxCombo() + "x", 1, false); maxCombo.attachToScene(scene); final String accStr = String @@ -202,7 +201,7 @@ public void load(final StatisticV2 stat, final TrackInfo track, mark.registerEntityModifier(new ParallelEntityModifier( new FadeInModifier(2), new ScaleModifier(2, 2, 1))); } - mark.setPosition(Config.getRES_WIDTH() * 5 / 6 - mark.getWidth() / 2, 80); + mark.setPosition((float) (Config.getRES_WIDTH() * 5) / 6 - mark.getWidth() / 2, 80); final Sprite backBtn = new Sprite(Utils.toRes(580), Utils.toRes(490), ResourceManager.getInstance().getTexture("ranking-back")) { @@ -540,7 +539,7 @@ public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, SendingPanel sendingPanel = new SendingPanel(OnlineManager.getInstance().getRank(), OnlineManager.getInstance().getScore(), OnlineManager.getInstance().getAccuracy()); - sendingPanel.setPosition(Config.getRES_WIDTH() / 2 - 400, Utils.toRes(-300)); + sendingPanel.setPosition((float) Config.getRES_WIDTH() / 2 - 400, Utils.toRes(-300)); scene.registerTouchArea(sendingPanel.getDismissTouchArea()); scene.attachChild(sendingPanel); ScoreLibrary.getInstance().sendScoreOnline(stat, replay, sendingPanel); diff --git a/src/ru/nsu/ccfit/zuev/osu/scoring/StatisticV2.java b/src/ru/nsu/ccfit/zuev/osu/scoring/StatisticV2.java index cc6e67ea8..a284bfcfd 100644 --- a/src/ru/nsu/ccfit/zuev/osu/scoring/StatisticV2.java +++ b/src/ru/nsu/ccfit/zuev/osu/scoring/StatisticV2.java @@ -325,8 +325,6 @@ public String getMark() { for (final GameMod m : mod) { switch (m) { case MOD_HIDDEN: - isH = true; - break forcycle; case MOD_FLASHLIGHT: isH = true; break forcycle; @@ -809,7 +807,7 @@ public static float getSpeedChangeScoreMultiplier(float speed, EnumSet multi = 1.0f + (multi - 1.0f) * 0.24f; } else if (multi < 1){ multi = (float) Math.pow(0.3, (1.0 - multi) * 4); - } else if (multi == 1){ + } else { return 1f; } if (mod.contains(GameMod.MOD_DOUBLETIME) || mod.contains(GameMod.MOD_NIGHTCORE)){ diff --git a/src/ru/nsu/ccfit/zuev/osu/storyboard/OsbParser.java b/src/ru/nsu/ccfit/zuev/osu/storyboard/OsbParser.java index 21f0a441d..1f98a54c9 100644 --- a/src/ru/nsu/ccfit/zuev/osu/storyboard/OsbParser.java +++ b/src/ru/nsu/ccfit/zuev/osu/storyboard/OsbParser.java @@ -22,10 +22,10 @@ */ public class OsbParser { public static OsbParser instance = new OsbParser(); - private LinkedList sprites = new LinkedList(); - private ArrayList timingPoints = new ArrayList(); - private ArrayList hitSounds = new ArrayList(); - private HashMap variablesMap = new HashMap(); + private LinkedList sprites = new LinkedList<>(); + private ArrayList timingPoints = new ArrayList<>(); + private ArrayList hitSounds = new ArrayList<>(); + private HashMap variablesMap = new HashMap<>(); private String line; private String[] info; private float sliderMultiplier; @@ -72,24 +72,14 @@ public void parse(String path) throws IOException { } source.close(); } - Collections.sort(hitSounds, new Comparator() { - @Override - public int compare(HitSound lhs, HitSound rhs) { - return (int) (lhs.time - rhs.time); - } - }); - Collections.sort(sprites, new Comparator() { - @Override - public int compare(OsuSprite lhs, OsuSprite rhs) { - return (int) (lhs.spriteStartTime - rhs.spriteStartTime); - } - }); + Collections.sort(hitSounds, (lhs, rhs) -> (int) (lhs.time - rhs.time)); + Collections.sort(sprites, (lhs, rhs) -> (int) (lhs.spriteStartTime - rhs.spriteStartTime)); } private void parseObjects(BufferedSource source) throws IOException { line = source.readUtf8Line(); while (line != null) { - if (line.equals("")) { + if (line.isEmpty()) { break; } @@ -101,14 +91,19 @@ private void parseObjects(BufferedSource source) throws IOException { } info = line.split(","); int layer = 0; - if (info[1].equals("Background")) { - layer = 0; - } else if (info[1].equals("Fail")) { - layer = 1; - } else if (info[1].equals("Pass")) { - layer = 2; - } else if (info[1].equals("Foreground")) { - layer = 3; + switch (info[1]) { + case "Background": + layer = 0; + break; + case "Fail": + layer = 1; + break; + case "Pass": + layer = 2; + break; + case "Foreground": + layer = 3; + break; } OsuSprite.Origin origin = OsuSprite.Origin.valueOf(info[2]); String filePath = info[3]; @@ -127,14 +122,19 @@ private void parseObjects(BufferedSource source) throws IOException { } info = line.split(","); int layer = 0; - if (info[1].equals("Background")) { - layer = 0; - } else if (info[1].equals("Fail")) { - layer = 1; - } else if (info[1].equals("Pass")) { - layer = 2; - } else if (info[1].equals("Foreground")) { - layer = 3; + switch (info[1]) { + case "Background": + layer = 0; + break; + case "Fail": + layer = 1; + break; + case "Pass": + layer = 2; + break; + case "Foreground": + layer = 3; + break; } OsuSprite.Origin origin = OsuSprite.Origin.valueOf(info[2]); String filePath = info[3]; @@ -157,7 +157,7 @@ private void parseObjects(BufferedSource source) throws IOException { } private ArrayList parseEvents(BufferedSource source) throws IOException { - ArrayList eventList = new ArrayList(); + ArrayList eventList = new ArrayList<>(); line = source.readUtf8Line(); if (line.startsWith("_")) { line = line.replaceAll("_", " "); @@ -191,12 +191,16 @@ private ArrayList parseEvents(BufferedSource source) throws IOExceptio } currentOsuEvent.triggerType = info[1]; int soundType = -1; - if (currentOsuEvent.triggerType.equals("HitSoundWhistle")) { - soundType = 2; - } else if (currentOsuEvent.triggerType.equals("HitSoundFinish")) { - soundType = 4; - } else if (currentOsuEvent.triggerType.equals("HitSoundClap")) { - soundType = 8; + switch (currentOsuEvent.triggerType) { + case "HitSoundWhistle": + soundType = 2; + break; + case "HitSoundFinish": + soundType = 4; + break; + case "HitSoundClap": + soundType = 8; + break; } currentOsuEvent.subEvents = parseSubEvents(source); for (HitSound hitSound : hitSounds) {//real start time @@ -208,7 +212,7 @@ private ArrayList parseEvents(BufferedSource source) throws IOExceptio } else { currentOsuEvent.ease = Integer.parseInt(info[1]); currentOsuEvent.startTime = Long.parseLong(info[2]); - currentOsuEvent.endTime = info[3].equals("") ? currentOsuEvent.startTime + 1 : Long.parseLong(info[3]); + currentOsuEvent.endTime = info[3].isEmpty() ? currentOsuEvent.startTime + 1 : Long.parseLong(info[3]); float[] params = null; switch (command) { case F: @@ -276,7 +280,7 @@ private ArrayList parseEvents(BufferedSource source) throws IOExceptio } private ArrayList parseSubEvents(BufferedSource source) throws IOException { - ArrayList subOsuEventList = new ArrayList(); + ArrayList subOsuEventList = new ArrayList<>(); while ((line = source.readUtf8Line()) != null && (line.startsWith(" ") || line.startsWith("__"))) { line = line.replaceAll("_", " ").trim(); for (String s : variablesMap.keySet()) { @@ -290,7 +294,7 @@ private ArrayList parseSubEvents(BufferedSource source) throws IOExcep subEvent.command = subCommand; subEvent.ease = Integer.parseInt(info[1]); subEvent.startTime = Long.parseLong(info[2]); - subEvent.endTime = info[3].equals("") ? subEvent.startTime + 1 : Long.parseLong(info[3]); + subEvent.endTime = info[3].isEmpty() ? subEvent.startTime + 1 : Long.parseLong(info[3]); float[] params = null; switch (subCommand) { case F: @@ -371,16 +375,22 @@ public void loadBeatmap(File file) throws IOException { if (matcher.find()) { String title = matcher.group(1); - if (title.equals("General")) { - parseGeneral(source); - } else if (title.equals("Difficulty")) { - parseDifficulty(source); - } else if (title.equals("Events")) { - parseEvent(source); - } else if (title.equals("TimingPoints")) { - parseTimingPoints(source); - } else if (title.equals("HitObjects")) { - parseHitObject(source); + switch (title) { + case "General": + parseGeneral(source); + break; + case "Difficulty": + parseDifficulty(source); + break; + case "Events": + parseEvent(source); + break; + case "TimingPoints": + parseTimingPoints(source); + break; + case "HitObjects": + parseHitObject(source); + break; } } } @@ -391,7 +401,7 @@ private void parseGeneral(BufferedSource source) throws IOException { String line; while ((line = source.readUtf8Line()) != null) { line = line.trim(); - if (line.equals("")) return; + if (line.isEmpty()) return; String[] values = line.split(":"); String key = values[0]; String value = values[1].trim(); @@ -408,7 +418,7 @@ private void parseEvent(BufferedSource source) throws IOException { String info[]; while ((line = source.readUtf8Line()) != null) { line = line.trim(); - if (line.equals("")) return; + if (line.isEmpty()) return; if (line.contains(",")) { info = line.split(","); @@ -427,7 +437,7 @@ private void parseVariables(BufferedSource source) throws IOException { String line; while ((line = source.readUtf8Line()) != null) { line = line.trim(); - if (line.equals("")) return; + if (line.isEmpty()) return; String[] values = line.split("="); String key = values[0]; String value = values[1].trim(); @@ -439,7 +449,7 @@ private void parseDifficulty(BufferedSource source) throws IOException { String line; while ((line = source.readUtf8Line()) != null) { line = line.trim(); - if (line.equals("")) return; + if (line.isEmpty()) return; String[] values = line.split(":"); if (values[0].equals("SliderMultiplier")) { sliderMultiplier = Float.parseFloat(values[1]); @@ -452,7 +462,7 @@ private void parseTimingPoints(BufferedSource source) throws IOException { float lastLengthPerBeat = -100; while ((line = source.readUtf8Line()) != null) { line = line.trim(); - if (line.equals("")) return; + if (line.isEmpty()) return; String[] values = line.split(","); TimingPoint timingPoint = new TimingPoint(); timingPoint.startTime = (long) Float.parseFloat(values[0]); @@ -470,7 +480,7 @@ private void parseHitObject(BufferedSource source) throws IOException { String line; while ((line = source.readUtf8Line()) != null) { line = line.trim(); - if (line.equals("")) return; + if (line.isEmpty()) return; String[] values = line.split(","); int objectType = Integer.parseInt(values[3]); if ((objectType & 1) == 1) {//circle @@ -497,7 +507,6 @@ private void parseHitObject(BufferedSource source) throws IOException { for (int i = 0; i < count; i++) { HitSound hitSound = new HitSound(); if (values.length > 8) { - assert soundTypes != null; hitSound.soundType = Integer.parseInt(soundTypes[i]); } else { hitSound.soundType = Integer.parseInt(values[4]); diff --git a/src/ru/nsu/ccfit/zuev/osu/storyboard/OsuSprite.java b/src/ru/nsu/ccfit/zuev/osu/storyboard/OsuSprite.java index a39438d58..38cfa60c6 100644 --- a/src/ru/nsu/ccfit/zuev/osu/storyboard/OsuSprite.java +++ b/src/ru/nsu/ccfit/zuev/osu/storyboard/OsuSprite.java @@ -106,7 +106,7 @@ public OsuSprite(float x, float y, int layer, Origin origin, String filePath, Ar th *= 2; } BuildableBitmapTextureAtlas mBitmapTextureAtlas = new BuildableBitmapTextureAtlas(tw, th, TextureOptions.BILINEAR); - ArrayList textureRegions = new ArrayList(); + ArrayList textureRegions = new ArrayList<>(); for (int i = 0; i < count; i++) { File temp = new File(StoryBoardTestActivity.FOLDER, filePath.substring(0, filePath.lastIndexOf(".")) + i + fileExt); if (temp.exists()) { @@ -124,7 +124,7 @@ public OsuSprite(float x, float y, int layer, Origin origin, String filePath, Ar return; } try { - mBitmapTextureAtlas.build(new BlackPawnTextureBuilder(0)); + mBitmapTextureAtlas.build(new BlackPawnTextureBuilder<>(0)); } catch (ITextureBuilder.TextureAtlasSourcePackingException e) { e.printStackTrace(); } @@ -268,7 +268,7 @@ private void setUpSprite() { } } parallelEntityModifier = new ParallelEntityModifier(entityModifiers); - parallelEntityModifier.addModifierListener(new IModifier.IModifierListener() { + parallelEntityModifier.addModifierListener(new IModifier.IModifierListener<>() { @Override public void onModifierStarted(IModifier pModifier, IEntity pItem) { @@ -336,6 +336,7 @@ private IEntityModifier parseModifier(OsuEvent osuEvent) { break; } float duration = (osuEvent.endTime - osuEvent.startTime) / 1000f; + label: switch (osuEvent.command) { case F://Fade if (iEaseFunction != null) { @@ -397,12 +398,16 @@ private IEntityModifier parseModifier(OsuEvent osuEvent) { break; case P://Parameter iEntityModifier = new DelayModifier(0f);//fake modifier - if (osuEvent.P.equals("H")) { - sprite.setFlippedHorizontal(true); - } else if (osuEvent.P.equals("V")) { - sprite.setFlippedVertical(true); - } else if (osuEvent.P.equals("A")) { - sprite.setBlendFunction(GLES10.GL_SRC_ALPHA, GLES10.GL_ONE); + switch (osuEvent.P) { + case "H": + sprite.setFlippedHorizontal(true); + break; + case "V": + sprite.setFlippedVertical(true); + break; + case "A": + sprite.setBlendFunction(GLES10.GL_SRC_ALPHA, GLES10.GL_ONE); + break; } break; case L: { @@ -432,16 +437,20 @@ private IEntityModifier parseModifier(OsuEvent osuEvent) { case T: { ArrayList subEventList = osuEvent.subEvents; ArrayList hitSounds = OsbParser.instance.getHitSounds(); - ArrayList entityModifierList = new ArrayList(); + ArrayList entityModifierList = new ArrayList<>(); int soundType; - if (osuEvent.triggerType.equals("HitSoundWhistle")) { - soundType = 2; - } else if (osuEvent.triggerType.equals("HitSoundFinish")) { - soundType = 4; - } else if (osuEvent.triggerType.equals("HitSoundClap")) { - soundType = 8; - } else { - break; + switch (osuEvent.triggerType) { + case "HitSoundWhistle": + soundType = 2; + break; + case "HitSoundFinish": + soundType = 4; + break; + case "HitSoundClap": + soundType = 8; + break; + default: + break label; } long firstSoundTime = -1; for (HitSound hitSound : hitSounds) { @@ -478,7 +487,7 @@ private IEntityModifier parseModifier(OsuEvent osuEvent) { } } if (entityModifierList.size() > 0) { - iEntityModifier = new ParallelEntityModifier(entityModifierList.toArray(new IEntityModifier[entityModifierList.size()])); + iEntityModifier = new ParallelEntityModifier(entityModifierList.toArray(new IEntityModifier[0])); } } break; diff --git a/src/ru/nsu/ccfit/zuev/push/PushNotificationService.java b/src/ru/nsu/ccfit/zuev/push/PushNotificationService.java index 643bd0994..a75f74463 100644 --- a/src/ru/nsu/ccfit/zuev/push/PushNotificationService.java +++ b/src/ru/nsu/ccfit/zuev/push/PushNotificationService.java @@ -18,11 +18,9 @@ import java.util.HashMap; -import org.anddev.andengine.util.Debug; - import ru.nsu.ccfit.zuev.osu.MainActivity; import ru.nsu.ccfit.zuev.osuplus.R; -import ru.nsu.ccfit.zuev.osu.helper.MD5Calcuator; +import ru.nsu.ccfit.zuev.osu.helper.MD5Calculator; import ru.nsu.ccfit.zuev.osu.online.OnlineFileOperator; /** @@ -35,7 +33,7 @@ public class PushNotificationService extends FirebaseMessagingService { @Override public void onMessageReceived(RemoteMessage remoteMessage) { if(remoteMessage.getData().size() > 0) { - HashMap data = new HashMap(remoteMessage.getData()); + HashMap data = new HashMap<>(remoteMessage.getData()); String channelId = "ru.nsu.ccfit.zuev.push"; Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); @@ -55,7 +53,7 @@ public void onMessageReceived(RemoteMessage remoteMessage) { .setSound(defaultSoundUri); if(!imageUrl.isEmpty()) { - String filePath = getCacheDir().getPath() + "/" + MD5Calcuator.getStringMD5("osuplus" + imageUrl); + String filePath = getCacheDir().getPath() + "/" + MD5Calculator.getStringMD5("osuplus" + imageUrl); boolean downloaded = OnlineFileOperator.downloadFile(imageUrl, filePath); if(downloaded) { Bitmap bitmap = BitmapFactory.decodeFile(filePath); diff --git a/src/ru/nsu/ccfit/zuev/skins/SkinManager.java b/src/ru/nsu/ccfit/zuev/skins/SkinManager.java index f368841fb..9cda8537e 100644 --- a/src/ru/nsu/ccfit/zuev/skins/SkinManager.java +++ b/src/ru/nsu/ccfit/zuev/skins/SkinManager.java @@ -11,8 +11,8 @@ public class SkinManager { private static SkinManager instance = new SkinManager(); - private static Map frameCount = new HashMap(); - private static Map stdframeCount = new HashMap(); + private static Map frameCount = new HashMap<>(); + private static Map stdframeCount = new HashMap<>(); private static boolean skinEnabled = true; static { @@ -114,7 +114,7 @@ public void loadBeatmapSkin(final String beatmapFolder) { } public void clearSkin() { - if (skinname.equals("")) { + if (skinname.isEmpty()) { return; } skinname = "";