From 0211102f23f95fd1425ff24b0b1a9807ccf0e07c Mon Sep 17 00:00:00 2001 From: khanhduytran0 Date: Sun, 15 Nov 2020 19:16:28 +0700 Subject: [PATCH] Abstracts to BaseLauncherActivity.java for easier maintaining multiple designs --- .../kdt/pojavlaunch/BaseLauncherActivity.java | 24 + .../kdt/pojavlaunch/MCLauncherActivity.java | 486 ++--------------- .../pojavlaunch/PojavLauncherActivity.java | 492 ++---------------- .../tasks/MinecraftDownloaderTask.java | 317 +++++++++++ .../tasks/RefreshVersionListTask.java | 128 +++++ 5 files changed, 542 insertions(+), 905 deletions(-) create mode 100644 app/src/main/java/net/kdt/pojavlaunch/BaseLauncherActivity.java create mode 100644 app/src/main/java/net/kdt/pojavlaunch/tasks/MinecraftDownloaderTask.java create mode 100644 app/src/main/java/net/kdt/pojavlaunch/tasks/RefreshVersionListTask.java diff --git a/app/src/main/java/net/kdt/pojavlaunch/BaseLauncherActivity.java b/app/src/main/java/net/kdt/pojavlaunch/BaseLauncherActivity.java new file mode 100644 index 000000000..f55839255 --- /dev/null +++ b/app/src/main/java/net/kdt/pojavlaunch/BaseLauncherActivity.java @@ -0,0 +1,24 @@ +package net.kdt.pojavlaunch; + +import android.support.v7.app.*; +import android.widget.*; +import net.kdt.pojavlaunch.fragments.*; +import net.kdt.pojavlaunch.tasks.*; + +public abstract class BaseLauncherActivity extends AppCompatActivity { + public Button mPlayButton; + public ConsoleFragment mConsoleView; + public CrashFragment mCrashView; + public ProgressBar mLaunchProgress; + public Spinner mVersionSelector; + public TextView mLaunchTextStatus, mTextVersion; + + public JMinecraftVersionList mVersionList; + public MinecraftDownloaderTask mTask; + public MCProfile.Builder mProfile; + public String[] mAvailableVersions; + + public boolean mIsAssetsProcessing = false; + + public abstract void statusIsLaunching(boolean isLaunching); +} diff --git a/app/src/main/java/net/kdt/pojavlaunch/MCLauncherActivity.java b/app/src/main/java/net/kdt/pojavlaunch/MCLauncherActivity.java index 0690a8226..0228d7ac6 100644 --- a/app/src/main/java/net/kdt/pojavlaunch/MCLauncherActivity.java +++ b/app/src/main/java/net/kdt/pojavlaunch/MCLauncherActivity.java @@ -29,10 +29,11 @@ import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.app.*; import org.apache.commons.io.*; +import net.kdt.pojavlaunch.tasks.*; //import android.support.v7.view.menu.*; //import net.zhuoweizhang.boardwalk.downloader.*; -public class MCLauncherActivity extends AppCompatActivity +public class MCLauncherActivity extends BaseLauncherActivity { //private FragmentTabHost mTabHost; private LinearLayout fullTab; @@ -44,31 +45,17 @@ public class MCLauncherActivity extends AppCompatActivity private ViewPager viewPager; private TabLayout tabLayout; - private TextView tvVersion, tvUsernameView; - private Spinner versionSelector; - private String[] availableVersions; - private MCProfile.Builder profile; + private TextView tvUsernameView; private String profilePath = null; - private CrashFragment crashView; - private ConsoleFragment consoleView; private ViewPagerAdapter viewPageAdapter; - private ProgressBar launchProgress; - private TextView launchTextStatus; private Button switchUsrBtn, logoutBtn; // MineButtons private ViewGroup leftView, rightView; - private Button playButton; - - private Gson gson; - - private JMinecraftVersionList versionList; - private static volatile boolean isAssetsProcessing = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - gson = new Gson(); viewInit(); @@ -97,26 +84,26 @@ public class MCLauncherActivity extends AppCompatActivity tabLayout = findViewById(R.id.launchermainTabLayout); viewPager = findViewById(R.id.launchermainTabPager); - consoleView = new ConsoleFragment(); - crashView = new CrashFragment(); + mConsoleView = new ConsoleFragment(); + mCrashView = new CrashFragment(); viewPageAdapter = new ViewPagerAdapter(getSupportFragmentManager()); viewPageAdapter.addFragment(new LauncherFragment(), getStr(R.string.mcl_tab_news)); - viewPageAdapter.addFragment(consoleView, getStr(R.string.mcl_tab_console)); - viewPageAdapter.addFragment(crashView, getStr(R.string.mcl_tab_crash)); + viewPageAdapter.addFragment(mConsoleView, getStr(R.string.mcl_tab_console)); + viewPageAdapter.addFragment(mCrashView, getStr(R.string.mcl_tab_crash)); viewPager.setAdapter(viewPageAdapter); tabLayout.setupWithViewPager(viewPager); tvUsernameView = (TextView) findId(R.id.launcherMainUsernameView); - tvVersion = (TextView) findId(R.id.launcherMainVersionView); + mTextVersion = (TextView) findId(R.id.launcherMainVersionView); try { profilePath = PojavProfile.getCurrentProfilePath(this); - profile = PojavProfile.getCurrentProfileContent(this); + mProfile = PojavProfile.getCurrentProfileContent(this); - tvUsernameView.setText(profile.getUsername()); + tvUsernameView.setText(mProfile.getUsername()); } catch(Exception e) { //Tools.throwError(this, e); e.printStackTrace(); @@ -163,103 +150,29 @@ public class MCLauncherActivity extends AppCompatActivity versions.add(e.getMessage()); } finally { - availableVersions = versions.toArray(new String[0]); + mAvailableVersions = versions.toArray(new String[0]); } //availableVersions; - ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, availableVersions); + ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, mAvailableVersions); adapter.setDropDownViewResource(android.R.layout.simple_list_item_single_choice); - versionSelector = (Spinner) findId(R.id.launcherMainSelectVersion); - versionSelector.setAdapter(adapter); + mVersionSelector = (Spinner) findId(R.id.launcherMainSelectVersion); + mVersionSelector.setAdapter(adapter); - launchProgress = (ProgressBar) findId(R.id.progressDownloadBar); - launchTextStatus = (TextView) findId(R.id.progressDownloadText); + mLaunchProgress = (ProgressBar) findId(R.id.progressDownloadBar); + mLaunchTextStatus = (TextView) findId(R.id.progressDownloadText); LinearLayout exitLayout = (LinearLayout) findId(R.id.launcherMainExitbtns); switchUsrBtn = (Button) exitLayout.getChildAt(0); logoutBtn = (Button) exitLayout.getChildAt(1); leftView = (LinearLayout) findId(R.id.launcherMainLeftLayout); - playButton = (Button) findId(R.id.launcherMainPlayButton); + mPlayButton = (Button) findId(R.id.launcherMainPlayButton); rightView = (ViewGroup) findId(R.id.launcherMainRightLayout); statusIsLaunching(false); } - public class RefreshVersionListTask extends AsyncTask>{ - - @Override - protected ArrayList doInBackground(Void[] p1) - { - try{ - versionList = gson.fromJson(DownloadUtils.downloadString("https://launchermeta.mojang.com/mc/game/version_manifest.json"), JMinecraftVersionList.class); - ArrayList versionStringList = filter(versionList.versions, new File(Tools.versnDir).listFiles()); - - return versionStringList; - } catch (Exception e){ - e.printStackTrace(); - } - return null; - } - - @Override - protected void onPostExecute(ArrayList result) - { - super.onPostExecute(result); - - final PopupMenu popup = new PopupMenu(MCLauncherActivity.this, versionSelector); - popup.getMenuInflater().inflate(R.menu.menu_versionopt, popup.getMenu()); - - if(result != null && result.size() > 0) { - ArrayAdapter adapter = new ArrayAdapter(MCLauncherActivity.this, android.R.layout.simple_spinner_item, result); - adapter.setDropDownViewResource(android.R.layout.simple_list_item_single_choice); - versionSelector.setAdapter(adapter); - versionSelector.setSelection(selectAt(result.toArray(new String[0]), profile.getVersion())); - } else { - versionSelector.setSelection(selectAt(availableVersions, profile.getVersion())); - } - versionSelector.setOnItemSelectedListener(new OnItemSelectedListener(){ - - @Override - public void onItemSelected(AdapterView p1, View p2, int p3, long p4) - { - String version = p1.getItemAtPosition(p3).toString(); - profile.setVersion(version); - - PojavProfile.setCurrentProfile(MCLauncherActivity.this, profile); - if (PojavProfile.isFileType(MCLauncherActivity.this)) { - PojavProfile.setCurrentProfile(MCLauncherActivity.this, MCProfile.build(profile)); - } - - tvVersion.setText(getStr(R.string.mcl_version_msg, version)); - } - - @Override - public void onNothingSelected(AdapterView p1) - { - // TODO: Implement this method - } - }); - versionSelector.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener(){ - @Override - public boolean onItemLongClick(AdapterView p1, View p2, int p3, long p4) - { - // Implement copy, remove, reinstall,... - popup.show(); - return true; - } - }); - - popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { - public boolean onMenuItemClick(MenuItem item) { - return true; - } - }); - - tvVersion.setText(getStr(R.string.mcl_version_msg) + versionSelector.getSelectedItem()); - } - } - @Override protected void onPostResume() { super.onPostResume(); @@ -268,50 +181,16 @@ public class MCLauncherActivity extends AppCompatActivity private float updateWidthHeight() { float leftRightWidth = (float) CallbackBridge.windowWidth / 100f * 32f; - float playButtonWidth = CallbackBridge.windowWidth - leftRightWidth * 2f; + float mPlayButtonWidth = CallbackBridge.windowWidth - leftRightWidth * 2f; LinearLayout.LayoutParams leftRightParams = new LinearLayout.LayoutParams((int) leftRightWidth, (int) Tools.dpToPx(this, CallbackBridge.windowHeight / 9)); - LinearLayout.LayoutParams playButtonParams = new LinearLayout.LayoutParams((int) playButtonWidth, (int) Tools.dpToPx(this, CallbackBridge.windowHeight / 9)); + LinearLayout.LayoutParams mPlayButtonParams = new LinearLayout.LayoutParams((int) mPlayButtonWidth, (int) Tools.dpToPx(this, CallbackBridge.windowHeight / 9)); leftView.setLayoutParams(leftRightParams); rightView.setLayoutParams(leftRightParams); - playButton.setLayoutParams(playButtonParams); + mPlayButton.setLayoutParams(mPlayButtonParams); return leftRightWidth; } - private JMinecraftVersionList.Version findVersion(String version) { - if (versionList != null) { - for (JMinecraftVersionList.Version valueVer: versionList.versions) { - if (valueVer.id.equals(version)) { - return valueVer; - } - } - } - - // Custom version, inherits from base. - return Tools.getVersionInfo(version); - } - - private ArrayList filter(JMinecraftVersionList.Version[] list1, File[] list2) { - ArrayList output = new ArrayList(); - - for (JMinecraftVersionList.Version value1: list1) { - if ((value1.type.equals("release") && LauncherPreferences.PREF_VERTYPE_RELEASE) || - (value1.type.equals("snapshot") && LauncherPreferences.PREF_VERTYPE_SNAPSHOT) || - (value1.type.equals("old_alpha") && LauncherPreferences.PREF_VERTYPE_OLDALPHA) || - (value1.type.equals("old_beta") && LauncherPreferences.PREF_VERTYPE_OLDBETA)) { - output.add(value1.id); - } - } - - for (File value2: list2) { - if (!output.contains(value2.getName())) { - output.add(value2.getName()); - } - } - - return output; - } - public void mcaccSwitchUser(View view) { showProfileInfo(); @@ -349,7 +228,7 @@ public class MCLauncherActivity extends AppCompatActivity protected void onResumeFragments() { super.onResumeFragments(); - new RefreshVersionListTask().execute(); + new RefreshVersionListTask(this).execute(); try{ final ProgressDialog barrier = new ProgressDialog(this); @@ -363,7 +242,7 @@ public class MCLauncherActivity extends AppCompatActivity @Override public void run() { - while (consoleView == null) { + while (mConsoleView == null) { try { Thread.sleep(20); } catch (Throwable th) {} @@ -378,7 +257,7 @@ public class MCLauncherActivity extends AppCompatActivity public void run() { try { - consoleView.putLog(""); + mConsoleView.putLog(""); barrier.dismiss(); } catch (Throwable th) { startActivity(getIntent()); @@ -390,8 +269,8 @@ public class MCLauncherActivity extends AppCompatActivity }).start(); File lastCrashFile = Tools.lastFileModified(Tools.crashPath); - if(CrashFragment.isNewCrash(lastCrashFile) || !crashView.getLastCrash().isEmpty()){ - crashView.resetCrashLog = false; + if(CrashFragment.isNewCrash(lastCrashFile) || !mCrashView.getLastCrash().isEmpty()){ + mCrashView.resetCrashLog = false; selectTabPage(2); } else throw new Exception(); } catch(Throwable e){ @@ -399,20 +278,6 @@ public class MCLauncherActivity extends AppCompatActivity } } - public int selectAt(String[] strArr, String select) - { - int count = 0; - for(String str : strArr){ - if(str.equals(select)){ - return count; - } - else{ - count++; - } - } - return -1; - } - @Override protected void onResume(){ super.onResume(); @@ -422,19 +287,19 @@ public class MCLauncherActivity extends AppCompatActivity } private boolean canBack = false; - private void statusIsLaunching(boolean isLaunching) + public void statusIsLaunching(boolean isLaunching) { LinearLayout.LayoutParams reparam = new LinearLayout.LayoutParams((int) updateWidthHeight(), LinearLayout.LayoutParams.WRAP_CONTENT); ViewGroup.MarginLayoutParams lmainTabParam = (ViewGroup.MarginLayoutParams) fullTab.getLayoutParams(); int launchVisibility = isLaunching ? View.VISIBLE : View.GONE; - launchProgress.setVisibility(launchVisibility); - launchTextStatus.setVisibility(launchVisibility); + mLaunchProgress.setVisibility(launchVisibility); + mLaunchTextStatus.setVisibility(launchVisibility); lmainTabParam.bottomMargin = reparam.height; leftView.setLayoutParams(reparam); switchUsrBtn.setEnabled(!isLaunching); logoutBtn.setEnabled(!isLaunching); - versionSelector.setEnabled(!isLaunching); + mVersionSelector.setEnabled(!isLaunching); canBack = !isLaunching; } @Override @@ -451,301 +316,20 @@ public class MCLauncherActivity extends AppCompatActivity return super.onTouchEvent(event); } - private GameRunnerTask mTask; - public void launchGame(View v) { - if (!canBack && isAssetsProcessing) { - isAssetsProcessing = false; + if (!canBack && mIsAssetsProcessing) { + mIsAssetsProcessing = false; statusIsLaunching(false); } else if (canBack) { v.setEnabled(false); - mTask = new GameRunnerTask(); - mTask.execute(profile.getVersion()); - crashView.resetCrashLog = true; + mTask = new MinecraftDownloaderTask(this); + mTask.execute(mProfile.getVersion()); + mCrashView.resetCrashLog = true; } } - public class GameRunnerTask extends AsyncTask - { - private boolean launchWithError = false; - - @Override - protected void onPreExecute() { - launchProgress.setMax(1); - statusIsLaunching(true); - } - - private JMinecraftVersionList.Version verInfo; - @Override - protected Throwable doInBackground(final String[] p1) { - Throwable throwable = null; - try { - final String downVName = "/" + p1[0] + "/" + p1[0]; - - //Downloading libraries - String minecraftMainJar = Tools.versnDir + downVName + ".jar"; - JAssets assets = null; - try { - //com.pojavdx.dx.mod.Main.debug = true; - - String verJsonDir = Tools.versnDir + downVName + ".json"; - - verInfo = findVersion(p1[0]); - - if (verInfo.url != null && !new File(verJsonDir).exists()) { - publishProgress("1", "Downloading " + p1[0] + " configuration..."); - Tools.downloadFile( - verInfo.url, - verJsonDir - ); - } - - verInfo = Tools.getVersionInfo(p1[0]); - assets = downloadIndex(verInfo.assets, new File(Tools.ASSETS_PATH, "indexes/" + verInfo.assets + ".json")); - - File outLib; - String libPathURL; - - setMax(verInfo.libraries.length + 4 + assets.objects.size()); - for (final DependentLibrary libItem : verInfo.libraries) { - - if (// libItem.name.startsWith("com.google.code.gson:gson") || - // libItem.name.startsWith("com.mojang:realms") || - libItem.name.startsWith("net.java.jinput") || - // libItem.name.startsWith("net.minecraft.launchwrapper") || - - // FIXME lib below! - // libItem.name.startsWith("optifine:launchwrapper-of") || - - // libItem.name.startsWith("org.lwjgl.lwjgl:lwjgl") || - libItem.name.startsWith("org.lwjgl") - // libItem.name.startsWith("tv.twitch") - ) { // Black list - publishProgress("1", "Ignored " + libItem.name); - //Thread.sleep(100); - } else { - - String[] libInfo = libItem.name.split(":"); - String libArtifact = Tools.artifactToPath(libInfo[0], libInfo[1], libInfo[2]); - outLib = new File(Tools.libraries + "/" + libArtifact); - outLib.getParentFile().mkdirs(); - - if (!outLib.exists()) { - publishProgress("1", getString(R.string.mcl_launch_download_lib, libItem.name)); - - boolean skipIfFailed = false; - - if (libItem.downloads == null || libItem.downloads.artifact == null) { - MinecraftLibraryArtifact artifact = new MinecraftLibraryArtifact(); - artifact.url = (libItem.url == null ? "https://libraries.minecraft.net/" : libItem.url) + libArtifact; - libItem.downloads = new DependentLibrary.LibraryDownloads(artifact); - - skipIfFailed = true; - } - try { - libPathURL = libItem.downloads.artifact.url; - Tools.downloadFile( - libPathURL, - outLib.getAbsolutePath() - ); - } catch (Throwable th) { - if (!skipIfFailed) { - throw th; - } else { - th.printStackTrace(); - publishProgress("0", th.getMessage()); - } - } - } - } - } - - publishProgress("1", getString(R.string.mcl_launch_download_client, p1[0])); - File minecraftMainFile = new File(minecraftMainJar); - if (!minecraftMainFile.exists() || minecraftMainFile.length() == 0l) { - try { - Tools.downloadFile( - verInfo.downloads.values().toArray(new MinecraftClientInfo[0])[0].url, - minecraftMainJar - ); - } catch (Throwable th) { - if (verInfo.inheritsFrom != null) { - minecraftMainFile.delete(); - IOUtils.copy(new FileInputStream(new File(Tools.versnDir, verInfo.inheritsFrom + "/" + verInfo.inheritsFrom + ".jar")), new FileOutputStream(minecraftMainFile)); - } else { - throw th; - } - } - } - } catch (Throwable e) { - launchWithError = true; - throw e; - } - - publishProgress("1", getString(R.string.mcl_launch_cleancache)); - // new File(inputPath).delete(); - - for (File f : new File(Tools.versnDir).listFiles()) { - if(f.getName().endsWith(".part")) { - Log.d(Tools.APP_NAME, "Cleaning cache: " + f); - f.delete(); - } - } - - isAssetsProcessing = true; - playButton.post(new Runnable(){ - - @Override - public void run() - { - playButton.setText("Skip"); - playButton.setEnabled(true); - } - }); - publishProgress("1", getString(R.string.mcl_launch_download_assets)); - try { - downloadAssets(assets, verInfo.assets, new File(Tools.ASSETS_PATH)); - } catch (Exception e) { - e.printStackTrace(); - - // Ignore it - launchWithError = false; - } finally { - isAssetsProcessing = false; - } - } catch (Throwable th){ - throwable = th; - } finally { - return throwable; - } - } - private int addProgress = 0; // 34 - - public void zeroProgress() - { - addProgress = 0; - } - - public void setMax(final int value) - { - launchProgress.post(new Runnable(){ - - @Override - public void run() - { - launchProgress.setMax(value); - } - }); - } - - @Override - protected void onProgressUpdate(String... p1) - { - int addedProg = Integer.parseInt(p1[0]); - if (addedProg != -1) { - addProgress = addProgress + addedProg; - launchProgress.setProgress(addProgress); - - launchTextStatus.setText(p1[1]); - } - - if (p1.length < 3) consoleView.putLog(p1[1] + (p1.length < 3 ? "\n" : "")); - } - - @Override - protected void onPostExecute(Throwable p1) - { - playButton.setText("Play"); - playButton.setEnabled(true); - launchProgress.setMax(100); - launchProgress.setProgress(0); - statusIsLaunching(false); - if(p1 != null) { - p1.printStackTrace(); - Tools.showError(MCLauncherActivity.this, p1); - } - if(!launchWithError) { - crashView.setLastCrash(""); - - try { - /* - List jvmArgs = ManagementFactory.getRuntimeMXBean().getInputArguments(); - jvmArgs.add("-Xms128M"); - jvmArgs.add("-Xmx1G"); - */ - Intent mainIntent = new Intent(MCLauncherActivity.this, MainActivity.class); - // mainIntent.addFlags(Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT); - mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT); - mainIntent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK); - if (LauncherPreferences.PREF_FREEFORM) { - DisplayMetrics dm = new DisplayMetrics(); - getWindowManager().getDefaultDisplay().getMetrics(dm); - - ActivityOptions options = (ActivityOptions) ActivityOptions.class.getMethod("makeBasic").invoke(null); - Rect freeformRect = new Rect(0, 0, dm.widthPixels / 2, dm.heightPixels / 2); - options.getClass().getDeclaredMethod("setLaunchBounds", Rect.class).invoke(options, freeformRect); - startActivity(mainIntent, options.toBundle()); - } else { - startActivity(mainIntent); - } - } - catch (Throwable e) { - Tools.showError(MCLauncherActivity.this, e); - } - - /* - FloatingIntent maini = new FloatingIntent(PojavLauncherActivity.this, MainActivity.class); - maini.startFloatingActivity(); - */ - } - - mTask = null; - } - - public static final String MINECRAFT_RES = "http://resources.download.minecraft.net/"; - - public JAssets downloadIndex(String versionName, File output) throws Throwable { - if (!output.exists()) { - output.getParentFile().mkdirs(); - DownloadUtils.downloadFile(verInfo.assetIndex != null ? verInfo.assetIndex.url : "http://s3.amazonaws.com/Minecraft.Download/indexes/" + versionName + ".json", output); - } - - return gson.fromJson(Tools.read(output.getAbsolutePath()), JAssets.class); - } - - public void downloadAsset(JAssetInfo asset, File objectsDir) throws IOException, Throwable { - String assetPath = asset.hash.substring(0, 2) + "/" + asset.hash; - File outFile = new File(objectsDir, assetPath); - if (!outFile.exists()) { - DownloadUtils.downloadFile(MINECRAFT_RES + assetPath, outFile); - } - } - - public void downloadAssets(JAssets assets, String assetsVersion, File outputDir) throws IOException, Throwable { - File hasDownloadedFile = new File(outputDir, "downloaded/" + assetsVersion + ".downloaded"); - if (!hasDownloadedFile.exists()) { - System.out.println("Assets begin time: " + System.currentTimeMillis()); - Map assetsObjects = assets.objects; - launchProgress.setMax(assetsObjects.size()); - zeroProgress(); - File objectsDir = new File(outputDir, "objects"); - int downloadedSs = 0; - for (JAssetInfo asset : assetsObjects.values()) { - if (!isAssetsProcessing) { - return; - } - - downloadAsset(asset, objectsDir); - publishProgress("1", getString(R.string.mcl_launch_downloading, assetsObjects.keySet().toArray(new String[0])[downloadedSs])); - downloadedSs++; - } - hasDownloadedFile.getParentFile().mkdirs(); - hasDownloadedFile.createNewFile(); - System.out.println("Assets end time: " + System.currentTimeMillis()); - } - } - } + public View findId(int id) { diff --git a/app/src/main/java/net/kdt/pojavlaunch/PojavLauncherActivity.java b/app/src/main/java/net/kdt/pojavlaunch/PojavLauncherActivity.java index 990e0444b..1a5686e60 100644 --- a/app/src/main/java/net/kdt/pojavlaunch/PojavLauncherActivity.java +++ b/app/src/main/java/net/kdt/pojavlaunch/PojavLauncherActivity.java @@ -27,10 +27,11 @@ import org.apache.commons.io.*; import org.lwjgl.glfw.*; import android.support.v7.app.AlertDialog; +import net.kdt.pojavlaunch.tasks.*; //import android.support.v7.view.menu.*; //import net.zhuoweizhang.boardwalk.downloader.*; -public class PojavLauncherActivity extends AppCompatActivity +public class PojavLauncherActivity extends BaseLauncherActivity { //private FragmentTabHost mTabHost; private LinearLayout fullTab, leftTab; @@ -42,38 +43,26 @@ public class PojavLauncherActivity extends AppCompatActivity private ViewPager viewPager; private VerticalTabLayout tabLayout; - private TextView tvVersion, tvUsernameView; - private Spinner accountSelector, versionSelector; - private String[] availableVersions; - private MCProfile.Builder profile; + private TextView tvUsernameView; + private Spinner accountSelector; private String profilePath = null; - private CrashFragment crashView; - private ConsoleFragment consoleView; private ViewPagerAdapter viewPageAdapter; - private ProgressBar launchProgress; - private TextView launchTextStatus; private Button switchUsrBtn, logoutBtn; // MineButtons private ViewGroup leftView, rightView; - private Button playButton; - - private Gson gson; - - private JMinecraftVersionList versionList; - private static volatile boolean isAssetsProcessing = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - gson = new Gson(); viewInit(); Tools.setFullscreen(this); - if (BuildConfig.DEBUG) + if (BuildConfig.DEBUG) { Toast.makeText(this, "Launcher process id: " + android.os.Process.myPid(), Toast.LENGTH_LONG).show(); + } } // DEBUG //new android.support.design.widget.NavigationView(this); @@ -91,13 +80,13 @@ public class PojavLauncherActivity extends AppCompatActivity tabLayout = findViewById(R.id.launchermainTabLayout); viewPager = findViewById(R.id.launchermainTabPager); - consoleView = new ConsoleFragment(); - crashView = new CrashFragment(); + mConsoleView = new ConsoleFragment(); + mCrashView = new CrashFragment(); viewPageAdapter = new ViewPagerAdapter(getSupportFragmentManager()); viewPageAdapter.addFragment(new LauncherFragment(), R.drawable.ic_menu_news, getString(R.string.mcl_tab_news)); - viewPageAdapter.addFragment(consoleView, R.drawable.ic_menu_java, getString(R.string.mcl_tab_console)); - viewPageAdapter.addFragment(crashView, 0, getString(R.string.mcl_tab_crash)); + viewPageAdapter.addFragment(mConsoleView, R.drawable.ic_menu_java, getString(R.string.mcl_tab_console)); + viewPageAdapter.addFragment(mCrashView, 0, getString(R.string.mcl_tab_crash)); viewPageAdapter.addFragment(new LauncherPreferenceFragment(), R.drawable.ic_menu_settings, getString(R.string.mcl_option_settings)); viewPager.setAdapter(viewPageAdapter); @@ -106,13 +95,13 @@ public class PojavLauncherActivity extends AppCompatActivity tabLayout.setLastTabAsBottom(); tvUsernameView = (TextView) findViewById(R.id.launcherMainUsernameView); - tvVersion = (TextView) findViewById(R.id.launcherMainVersionView); + mTextVersion = (TextView) findViewById(R.id.launcherMainVersionView); try { profilePath = PojavProfile.getCurrentProfilePath(this); - profile = PojavProfile.getCurrentProfileContent(this); + mProfile = PojavProfile.getCurrentProfileContent(this); - tvUsernameView.setText(profile.getUsername()); + tvUsernameView.setText(mProfile.getUsername()); } catch(Exception e) { //Tools.throwError(this, e); e.printStackTrace(); @@ -178,103 +167,29 @@ public class PojavLauncherActivity extends AppCompatActivity versions.add(e.getMessage()); } finally { - availableVersions = versions.toArray(new String[0]); + mAvailableVersions = versions.toArray(new String[0]); } - //availableVersions; + //mAvailableVersions; - ArrayAdapter adapterVer = new ArrayAdapter(this, android.R.layout.simple_spinner_item, availableVersions); + ArrayAdapter adapterVer = new ArrayAdapter(this, android.R.layout.simple_spinner_item, mAvailableVersions); adapterVer.setDropDownViewResource(android.R.layout.simple_list_item_single_choice); - versionSelector = (Spinner) findViewById(R.id.launchermain_spinner_version); - versionSelector.setAdapter(adapterVer); + mVersionSelector = (Spinner) findViewById(R.id.launchermain_spinner_version); + mVersionSelector.setAdapter(adapterVer); - launchProgress = (ProgressBar) findViewById(R.id.progressDownloadBar); - launchTextStatus = (TextView) findViewById(R.id.progressDownloadText); + mLaunchProgress = (ProgressBar) findViewById(R.id.progressDownloadBar); + mLaunchTextStatus = (TextView) findViewById(R.id.progressDownloadText); LinearLayout exitLayout = (LinearLayout) findViewById(R.id.launcherMainExitbtns); switchUsrBtn = (Button) exitLayout.getChildAt(0); logoutBtn = (Button) exitLayout.getChildAt(1); leftView = (LinearLayout) findViewById(R.id.launcherMainLeftLayout); - playButton = (Button) findViewById(R.id.launcherMainPlayButton); + mPlayButton = (Button) findViewById(R.id.launcherMainPlayButton); rightView = (ViewGroup) findViewById(R.id.launcherMainRightLayout); statusIsLaunching(false); } - public class RefreshVersionListTask extends AsyncTask>{ - - @Override - protected ArrayList doInBackground(Void[] p1) - { - try{ - versionList = gson.fromJson(DownloadUtils.downloadString("https://launchermeta.mojang.com/mc/game/version_manifest.json"), JMinecraftVersionList.class); - ArrayList versionStringList = filter(versionList.versions, new File(Tools.versnDir).listFiles()); - - return versionStringList; - } catch (Exception e){ - e.printStackTrace(); - } - return null; - } - - @Override - protected void onPostExecute(ArrayList result) - { - super.onPostExecute(result); - - final PopupMenu popup = new PopupMenu(PojavLauncherActivity.this, versionSelector); - popup.getMenuInflater().inflate(R.menu.menu_versionopt, popup.getMenu()); - - if(result != null && result.size() > 0) { - ArrayAdapter adapter = new ArrayAdapter(PojavLauncherActivity.this, android.R.layout.simple_spinner_item, result); - adapter.setDropDownViewResource(android.R.layout.simple_list_item_single_choice); - versionSelector.setAdapter(adapter); - versionSelector.setSelection(selectAt(result.toArray(new String[0]), profile.getVersion())); - } else { - versionSelector.setSelection(selectAt(availableVersions, profile.getVersion())); - } - versionSelector.setOnItemSelectedListener(new OnItemSelectedListener(){ - - @Override - public void onItemSelected(AdapterView p1, View p2, int p3, long p4) - { - String version = p1.getItemAtPosition(p3).toString(); - profile.setVersion(version); - - PojavProfile.setCurrentProfile(PojavLauncherActivity.this, profile); - if (PojavProfile.isFileType(PojavLauncherActivity.this)) { - PojavProfile.setCurrentProfile(PojavLauncherActivity.this, MCProfile.build(profile)); - } - - tvVersion.setText(getString(R.string.mcl_version_msg, version)); - } - - @Override - public void onNothingSelected(AdapterView p1) - { - // TODO: Implement this method - } - }); - versionSelector.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener(){ - @Override - public boolean onItemLongClick(AdapterView p1, View p2, int p3, long p4) - { - // Implement copy, remove, reinstall,... - popup.show(); - return true; - } - }); - - popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { - public boolean onMenuItemClick(MenuItem item) { - return true; - } - }); - - tvVersion.setText(getString(R.string.mcl_version_msg) + versionSelector.getSelectedItem()); - } - } - @Override protected void onPostResume() { super.onPostResume(); @@ -283,50 +198,16 @@ public class PojavLauncherActivity extends AppCompatActivity private float updateWidthHeight() { float leftRightWidth = (float) CallbackBridge.windowWidth / 100f * 32f; - float playButtonWidth = CallbackBridge.windowWidth - leftRightWidth * 2f; + float mPlayButtonWidth = CallbackBridge.windowWidth - leftRightWidth * 2f; LinearLayout.LayoutParams leftRightParams = new LinearLayout.LayoutParams((int) leftRightWidth, (int) Tools.dpToPx(this, CallbackBridge.windowHeight / 9)); - LinearLayout.LayoutParams playButtonParams = new LinearLayout.LayoutParams((int) playButtonWidth, (int) Tools.dpToPx(this, CallbackBridge.windowHeight / 9)); + LinearLayout.LayoutParams mPlayButtonParams = new LinearLayout.LayoutParams((int) mPlayButtonWidth, (int) Tools.dpToPx(this, CallbackBridge.windowHeight / 9)); leftView.setLayoutParams(leftRightParams); rightView.setLayoutParams(leftRightParams); - playButton.setLayoutParams(playButtonParams); + mPlayButton.setLayoutParams(mPlayButtonParams); return leftRightWidth; } - private JMinecraftVersionList.Version findVersion(String version) { - if (versionList != null) { - for (JMinecraftVersionList.Version valueVer: versionList.versions) { - if (valueVer.id.equals(version)) { - return valueVer; - } - } - } - - // Custom version, inherits from base. - return Tools.getVersionInfo(version); - } - - private ArrayList filter(JMinecraftVersionList.Version[] list1, File[] list2) { - ArrayList output = new ArrayList(); - - for (JMinecraftVersionList.Version value1: list1) { - if ((value1.type.equals("release") && LauncherPreferences.PREF_VERTYPE_RELEASE) || - (value1.type.equals("snapshot") && LauncherPreferences.PREF_VERTYPE_SNAPSHOT) || - (value1.type.equals("old_alpha") && LauncherPreferences.PREF_VERTYPE_OLDALPHA) || - (value1.type.equals("old_beta") && LauncherPreferences.PREF_VERTYPE_OLDBETA)) { - output.add(value1.id); - } - } - - for (File value2: list2) { - if (!output.contains(value2.getName())) { - output.add(value2.getName()); - } - } - - return output; - } - public void mcaccSwitchUser(View view) { showProfileInfo(); @@ -364,7 +245,7 @@ public class PojavLauncherActivity extends AppCompatActivity protected void onResumeFragments() { super.onResumeFragments(); - new RefreshVersionListTask().execute(); + new RefreshVersionListTask(this).execute(); try{ final ProgressDialog barrier = new ProgressDialog(this); @@ -378,7 +259,7 @@ public class PojavLauncherActivity extends AppCompatActivity @Override public void run() { - while (consoleView == null) { + while (mConsoleView == null) { try { Thread.sleep(20); } catch (Throwable th) {} @@ -393,7 +274,7 @@ public class PojavLauncherActivity extends AppCompatActivity public void run() { try { - consoleView.putLog(""); + mConsoleView.putLog(""); barrier.dismiss(); } catch (Throwable th) { startActivity(getIntent()); @@ -405,8 +286,8 @@ public class PojavLauncherActivity extends AppCompatActivity }).start(); File lastCrashFile = Tools.lastFileModified(Tools.crashPath); - if(CrashFragment.isNewCrash(lastCrashFile) || !crashView.getLastCrash().isEmpty()){ - crashView.resetCrashLog = false; + if(CrashFragment.isNewCrash(lastCrashFile) || !mCrashView.getLastCrash().isEmpty()){ + mCrashView.resetCrashLog = false; selectTabPage(2); } else throw new Exception(); } catch(Throwable e){ @@ -414,20 +295,6 @@ public class PojavLauncherActivity extends AppCompatActivity } } - public int selectAt(String[] strArr, String select) - { - int count = 0; - for(String str : strArr){ - if(str.equals(select)){ - return count; - } - else{ - count++; - } - } - return -1; - } - @Override protected void onResume(){ super.onResume(); @@ -437,21 +304,21 @@ public class PojavLauncherActivity extends AppCompatActivity } private boolean canBack = false; - private void statusIsLaunching(boolean isLaunching) { + public void statusIsLaunching(boolean isLaunching) { // As preference fragment put to tab, changes without notice, so need re-load pref if (isLaunching) LauncherPreferences.loadPreferences(); LinearLayout.LayoutParams reparam = new LinearLayout.LayoutParams((int) updateWidthHeight(), LinearLayout.LayoutParams.WRAP_CONTENT); ViewGroup.MarginLayoutParams lmainTabParam = (ViewGroup.MarginLayoutParams) fullTab.getLayoutParams(); int launchVisibility = isLaunching ? View.VISIBLE : View.GONE; - launchProgress.setVisibility(launchVisibility); - launchTextStatus.setVisibility(launchVisibility); + mLaunchProgress.setVisibility(launchVisibility); + mLaunchTextStatus.setVisibility(launchVisibility); lmainTabParam.bottomMargin = reparam.height; leftView.setLayoutParams(reparam); switchUsrBtn.setEnabled(!isLaunching); logoutBtn.setEnabled(!isLaunching); - versionSelector.setEnabled(!isLaunching); + mVersionSelector.setEnabled(!isLaunching); canBack = !isLaunching; } @Override @@ -473,302 +340,19 @@ public class PojavLauncherActivity extends AppCompatActivity } } - private GameRunnerTask mTask; - public void launchGame(View v) { - if (!canBack && isAssetsProcessing) { - isAssetsProcessing = false; + if (!canBack && mIsAssetsProcessing) { + mIsAssetsProcessing = false; statusIsLaunching(false); } else if (canBack) { v.setEnabled(false); - mTask = new GameRunnerTask(); - mTask.execute(profile.getVersion()); - crashView.resetCrashLog = true; + mTask = new MinecraftDownloaderTask(this); + mTask.execute(mProfile.getVersion()); + mCrashView.resetCrashLog = true; } } - public class GameRunnerTask extends AsyncTask - { - private boolean launchWithError = false; - - @Override - protected void onPreExecute() { - launchProgress.setMax(1); - statusIsLaunching(true); - } - - private JMinecraftVersionList.Version verInfo; - @Override - protected Throwable doInBackground(final String[] p1) { - Throwable throwable = null; - try { - final String downVName = "/" + p1[0] + "/" + p1[0]; - - //Downloading libraries - String minecraftMainJar = Tools.versnDir + downVName + ".jar"; - JAssets assets = null; - try { - //com.pojavdx.dx.mod.Main.debug = true; - - String verJsonDir = Tools.versnDir + downVName + ".json"; - - verInfo = findVersion(p1[0]); - - if (verInfo.url != null && !new File(verJsonDir).exists()) { - publishProgress("1", "Downloading " + p1[0] + " configuration..."); - Tools.downloadFile( - verInfo.url, - verJsonDir - ); - } - - verInfo = Tools.getVersionInfo(p1[0]); - assets = downloadIndex(verInfo.assets, new File(Tools.ASSETS_PATH, "indexes/" + verInfo.assets + ".json")); - - File outLib; - String libPathURL; - - setMax(verInfo.libraries.length + 4 + assets.objects.size()); - for (final DependentLibrary libItem : verInfo.libraries) { - - if (// libItem.name.startsWith("com.google.code.gson:gson") || - // libItem.name.startsWith("com.mojang:realms") || - libItem.name.startsWith("net.java.jinput") || - // libItem.name.startsWith("net.minecraft.launchwrapper") || - - // FIXME lib below! - // libItem.name.startsWith("optifine:launchwrapper-of") || - - // libItem.name.startsWith("org.lwjgl.lwjgl:lwjgl") || - libItem.name.startsWith("org.lwjgl") - // libItem.name.startsWith("tv.twitch") - ) { // Black list - publishProgress("1", "Ignored " + libItem.name); - //Thread.sleep(100); - } else { - - String[] libInfo = libItem.name.split(":"); - String libArtifact = Tools.artifactToPath(libInfo[0], libInfo[1], libInfo[2]); - outLib = new File(Tools.libraries + "/" + libArtifact); - outLib.getParentFile().mkdirs(); - - if (!outLib.exists()) { - publishProgress("1", getString(R.string.mcl_launch_download_lib, libItem.name)); - - boolean skipIfFailed = false; - - if (libItem.downloads == null || libItem.downloads.artifact == null) { - MinecraftLibraryArtifact artifact = new MinecraftLibraryArtifact(); - artifact.url = (libItem.url == null ? "https://libraries.minecraft.net/" : libItem.url) + libArtifact; - libItem.downloads = new DependentLibrary.LibraryDownloads(artifact); - - skipIfFailed = true; - } - try { - libPathURL = libItem.downloads.artifact.url; - Tools.downloadFile( - libPathURL, - outLib.getAbsolutePath() - ); - } catch (Throwable th) { - if (!skipIfFailed) { - throw th; - } else { - th.printStackTrace(); - publishProgress("0", th.getMessage()); - } - } - } - } - } - - publishProgress("1", getString(R.string.mcl_launch_download_client, p1[0])); - File minecraftMainFile = new File(minecraftMainJar); - if (!minecraftMainFile.exists() || minecraftMainFile.length() == 0l) { - try { - Tools.downloadFile( - verInfo.downloads.values().toArray(new MinecraftClientInfo[0])[0].url, - minecraftMainJar - ); - } catch (Throwable th) { - if (verInfo.inheritsFrom != null) { - minecraftMainFile.delete(); - IOUtils.copy(new FileInputStream(new File(Tools.versnDir, verInfo.inheritsFrom + "/" + verInfo.inheritsFrom + ".jar")), new FileOutputStream(minecraftMainFile)); - } else { - throw th; - } - } - } - } catch (Throwable e) { - launchWithError = true; - throw e; - } - - publishProgress("1", getString(R.string.mcl_launch_cleancache)); - // new File(inputPath).delete(); - - for (File f : new File(Tools.versnDir).listFiles()) { - if(f.getName().endsWith(".part")) { - Log.d(Tools.APP_NAME, "Cleaning cache: " + f); - f.delete(); - } - } - - isAssetsProcessing = true; - playButton.post(new Runnable(){ - - @Override - public void run() - { - playButton.setText("Skip"); - playButton.setEnabled(true); - } - }); - publishProgress("1", getString(R.string.mcl_launch_download_assets)); - try { - downloadAssets(assets, verInfo.assets, new File(Tools.ASSETS_PATH)); - } catch (Exception e) { - e.printStackTrace(); - - // Ignore it - launchWithError = false; - } finally { - isAssetsProcessing = false; - } - } catch (Throwable th){ - throwable = th; - } finally { - return throwable; - } - } - private int addProgress = 0; // 34 - - public void zeroProgress() - { - addProgress = 0; - } - - public void setMax(final int value) - { - launchProgress.post(new Runnable(){ - - @Override - public void run() - { - launchProgress.setMax(value); - } - }); - } - - @Override - protected void onProgressUpdate(String... p1) - { - int addedProg = Integer.parseInt(p1[0]); - if (addedProg != -1) { - addProgress = addProgress + addedProg; - launchProgress.setProgress(addProgress); - - launchTextStatus.setText(p1[1]); - } - - if (p1.length < 3) consoleView.putLog(p1[1] + (p1.length < 3 ? "\n" : "")); - } - - @Override - protected void onPostExecute(Throwable p1) - { - playButton.setText("Play"); - playButton.setEnabled(true); - launchProgress.setMax(100); - launchProgress.setProgress(0); - statusIsLaunching(false); - if(p1 != null) { - p1.printStackTrace(); - Tools.showError(PojavLauncherActivity.this, p1); - } - if(!launchWithError) { - crashView.setLastCrash(""); - - try { - /* - List jvmArgs = ManagementFactory.getRuntimeMXBean().getInputArguments(); - jvmArgs.add("-Xms128M"); - jvmArgs.add("-Xmx1G"); - */ - Intent mainIntent = new Intent(PojavLauncherActivity.this, MainActivity.class); - // mainIntent.addFlags(Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT); - mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT); - mainIntent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK); - if (LauncherPreferences.PREF_FREEFORM) { - DisplayMetrics dm = new DisplayMetrics(); - getWindowManager().getDefaultDisplay().getMetrics(dm); - - ActivityOptions options = (ActivityOptions) ActivityOptions.class.getMethod("makeBasic").invoke(null); - Rect freeformRect = new Rect(0, 0, dm.widthPixels / 2, dm.heightPixels / 2); - options.getClass().getDeclaredMethod("setLaunchBounds", Rect.class).invoke(options, freeformRect); - startActivity(mainIntent, options.toBundle()); - } else { - startActivity(mainIntent); - } - } - catch (Throwable e) { - Tools.showError(PojavLauncherActivity.this, e); - } - - /* - FloatingIntent maini = new FloatingIntent(PojavLauncherActivity.this, MainActivity.class); - maini.startFloatingActivity(); - */ - } - - mTask = null; - } - - private Gson gsonss = gson; - public static final String MINECRAFT_RES = "http://resources.download.minecraft.net/"; - - public JAssets downloadIndex(String versionName, File output) throws Exception { - String versionJson = DownloadUtils.downloadString(verInfo.assetIndex != null ? verInfo.assetIndex.url : "http://s3.amazonaws.com/Minecraft.Download/indexes/" + versionName + ".json"); - JAssets version = gsonss.fromJson(versionJson, JAssets.class); - output.getParentFile().mkdirs(); - Tools.write(output.getAbsolutePath(), versionJson.getBytes(Charset.forName("UTF-8"))); - return version; - } - - public void downloadAsset(JAssetInfo asset, File objectsDir) throws IOException, Throwable { - String assetPath = asset.hash.substring(0, 2) + "/" + asset.hash; - File outFile = new File(objectsDir, assetPath); - if (!outFile.exists()) { - DownloadUtils.downloadFile(MINECRAFT_RES + assetPath, outFile); - } - } - - public void downloadAssets(JAssets assets, String assetsVersion, File outputDir) throws IOException, Throwable { - File hasDownloadedFile = new File(outputDir, "downloaded/" + assetsVersion + ".downloaded"); - if (!hasDownloadedFile.exists()) { - System.out.println("Assets begin time: " + System.currentTimeMillis()); - Map assetsObjects = assets.objects; - launchProgress.setMax(assetsObjects.size()); - zeroProgress(); - File objectsDir = new File(outputDir, "objects"); - int downloadedSs = 0; - for (JAssetInfo asset : assetsObjects.values()) { - if (!isAssetsProcessing) { - return; - } - - downloadAsset(asset, objectsDir); - publishProgress("1", getString(R.string.mcl_launch_downloading, assetsObjects.keySet().toArray(new String[0])[downloadedSs])); - downloadedSs++; - } - hasDownloadedFile.getParentFile().mkdirs(); - hasDownloadedFile.createNewFile(); - System.out.println("Assets end time: " + System.currentTimeMillis()); - } - } - } - public void launcherMenu(View view) { AlertDialog.Builder builder = new AlertDialog.Builder(this); diff --git a/app/src/main/java/net/kdt/pojavlaunch/tasks/MinecraftDownloaderTask.java b/app/src/main/java/net/kdt/pojavlaunch/tasks/MinecraftDownloaderTask.java new file mode 100644 index 000000000..5a79fc282 --- /dev/null +++ b/app/src/main/java/net/kdt/pojavlaunch/tasks/MinecraftDownloaderTask.java @@ -0,0 +1,317 @@ +package net.kdt.pojavlaunch.tasks; + +import android.app.*; +import android.content.*; +import android.graphics.*; +import android.os.*; +import android.util.*; +import com.google.gson.*; +import java.io.*; +import java.util.*; +import net.kdt.pojavlaunch.*; +import net.kdt.pojavlaunch.prefs.*; +import net.kdt.pojavlaunch.utils.*; +import net.kdt.pojavlaunch.value.*; +import org.apache.commons.io.*; + +public class MinecraftDownloaderTask extends AsyncTask + { + private BaseLauncherActivity mActivity; + private boolean launchWithError = false; + + public MinecraftDownloaderTask(BaseLauncherActivity activity) { + mActivity = activity; + } + + @Override + protected void onPreExecute() { + mActivity.mLaunchProgress.setMax(1); + mActivity.statusIsLaunching(true); + } + + private JMinecraftVersionList.Version verInfo; + @Override + protected Throwable doInBackground(final String[] p1) { + Throwable throwable = null; + try { + final String downVName = "/" + p1[0] + "/" + p1[0]; + + //Downloading libraries + String minecraftMainJar = Tools.versnDir + downVName + ".jar"; + JAssets assets = null; + try { + //com.pojavdx.dx.mod.Main.debug = true; + + String verJsonDir = Tools.versnDir + downVName + ".json"; + + verInfo = findVersion(p1[0]); + + if (verInfo.url != null && !new File(verJsonDir).exists()) { + publishProgress("1", "Downloading " + p1[0] + " configuration..."); + Tools.downloadFile( + verInfo.url, + verJsonDir + ); + } + + verInfo = Tools.getVersionInfo(p1[0]); + assets = downloadIndex(verInfo.assets, new File(Tools.ASSETS_PATH, "indexes/" + verInfo.assets + ".json")); + + File outLib; + String libPathURL; + + setMax(verInfo.libraries.length + 4 + assets.objects.size()); + for (final DependentLibrary libItem : verInfo.libraries) { + + if (// libItem.name.startsWith("com.google.code.gson:gson") || + // libItem.name.startsWith("com.mojang:realms") || + libItem.name.startsWith("net.java.jinput") || + // libItem.name.startsWith("net.minecraft.launchwrapper") || + + // FIXME lib below! + // libItem.name.startsWith("optifine:launchwrapper-of") || + + // libItem.name.startsWith("org.lwjgl.lwjgl:lwjgl") || + libItem.name.startsWith("org.lwjgl") + // libItem.name.startsWith("tv.twitch") + ) { // Black list + publishProgress("1", "Ignored " + libItem.name); + //Thread.sleep(100); + } else { + + String[] libInfo = libItem.name.split(":"); + String libArtifact = Tools.artifactToPath(libInfo[0], libInfo[1], libInfo[2]); + outLib = new File(Tools.libraries + "/" + libArtifact); + outLib.getParentFile().mkdirs(); + + if (!outLib.exists()) { + publishProgress("1", mActivity.getString(R.string.mcl_launch_download_lib, libItem.name)); + + boolean skipIfFailed = false; + + if (libItem.downloads == null || libItem.downloads.artifact == null) { + MinecraftLibraryArtifact artifact = new MinecraftLibraryArtifact(); + artifact.url = (libItem.url == null ? "https://libraries.minecraft.net/" : libItem.url) + libArtifact; + libItem.downloads = new DependentLibrary.LibraryDownloads(artifact); + + skipIfFailed = true; + } + try { + libPathURL = libItem.downloads.artifact.url; + Tools.downloadFile( + libPathURL, + outLib.getAbsolutePath() + ); + } catch (Throwable th) { + if (!skipIfFailed) { + throw th; + } else { + th.printStackTrace(); + publishProgress("0", th.getMessage()); + } + } + } + } + } + + publishProgress("1", mActivity.getString(R.string.mcl_launch_download_client, p1[0])); + File minecraftMainFile = new File(minecraftMainJar); + if (!minecraftMainFile.exists() || minecraftMainFile.length() == 0l) { + try { + Tools.downloadFile( + verInfo.downloads.values().toArray(new MinecraftClientInfo[0])[0].url, + minecraftMainJar + ); + } catch (Throwable th) { + if (verInfo.inheritsFrom != null) { + minecraftMainFile.delete(); + IOUtils.copy(new FileInputStream(new File(Tools.versnDir, verInfo.inheritsFrom + "/" + verInfo.inheritsFrom + ".jar")), new FileOutputStream(minecraftMainFile)); + } else { + throw th; + } + } + } + } catch (Throwable e) { + launchWithError = true; + throw e; + } + + publishProgress("1", mActivity.getString(R.string.mcl_launch_cleancache)); + // new File(inputPath).delete(); + + for (File f : new File(Tools.versnDir).listFiles()) { + if(f.getName().endsWith(".part")) { + Log.d(Tools.APP_NAME, "Cleaning cache: " + f); + f.delete(); + } + } + + mActivity.mIsAssetsProcessing = true; + mActivity.mPlayButton.post(new Runnable(){ + + @Override + public void run() + { + mActivity.mPlayButton.setText("Skip"); + mActivity.mPlayButton.setEnabled(true); + } + }); + publishProgress("1", mActivity.getString(R.string.mcl_launch_download_assets)); + try { + downloadAssets(assets, verInfo.assets, new File(Tools.ASSETS_PATH)); + } catch (Exception e) { + e.printStackTrace(); + + // Ignore it + launchWithError = false; + } finally { + mActivity.mIsAssetsProcessing = false; + } + } catch (Throwable th){ + throwable = th; + } finally { + return throwable; + } + } + private int addProgress = 0; // 34 + + public void zeroProgress() + { + addProgress = 0; + } + + public void setMax(final int value) + { + mActivity.mLaunchProgress.post(new Runnable(){ + + @Override + public void run() + { + mActivity.mLaunchProgress.setMax(value); + } + }); + } + + @Override + protected void onProgressUpdate(String... p1) + { + int addedProg = Integer.parseInt(p1[0]); + if (addedProg != -1) { + addProgress = addProgress + addedProg; + mActivity.mLaunchProgress.setProgress(addProgress); + + mActivity.mLaunchTextStatus.setText(p1[1]); + } + + if (p1.length < 3) { + mActivity.mConsoleView.putLog(p1[1] + (p1.length < 3 ? "\n" : "")); + } + } + + @Override + protected void onPostExecute(Throwable p1) + { + mActivity.mPlayButton.setText("Play"); + mActivity.mPlayButton.setEnabled(true); + mActivity.mLaunchProgress.setMax(100); + mActivity.mLaunchProgress.setProgress(0); + mActivity.statusIsLaunching(false); + if(p1 != null) { + p1.printStackTrace(); + Tools.showError(mActivity, p1); + } + if(!launchWithError) { + mActivity.mCrashView.setLastCrash(""); + + try { + /* + List jvmArgs = ManagementFactory.getRuntimeMXBean().getInputArguments(); + jvmArgs.add("-Xms128M"); + jvmArgs.add("-Xmx1G"); + */ + Intent mainIntent = new Intent(mActivity, MainActivity.class); + // mainIntent.addFlags(Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT); + mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT); + mainIntent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK); + if (LauncherPreferences.PREF_FREEFORM) { + DisplayMetrics dm = new DisplayMetrics(); + mActivity.getWindowManager().getDefaultDisplay().getMetrics(dm); + + ActivityOptions options = (ActivityOptions) ActivityOptions.class.getMethod("makeBasic").invoke(null); + Rect freeformRect = new Rect(0, 0, dm.widthPixels / 2, dm.heightPixels / 2); + options.getClass().getDeclaredMethod("setLaunchBounds", Rect.class).invoke(options, freeformRect); + mActivity.startActivity(mainIntent, options.toBundle()); + } else { + mActivity.startActivity(mainIntent); + } + } + catch (Throwable e) { + Tools.showError(mActivity, e); + } + + /* + FloatingIntent maini = new FloatingIntent(PojavLauncherActivity.this, MainActivity.class); + maini.startFloatingActivity(); + */ + } + + mActivity.mTask = null; + } + + public static final String MINECRAFT_RES = "http://resources.download.minecraft.net/"; + + public JAssets downloadIndex(String versionName, File output) throws Throwable { + if (!output.exists()) { + output.getParentFile().mkdirs(); + DownloadUtils.downloadFile(verInfo.assetIndex != null ? verInfo.assetIndex.url : "http://s3.amazonaws.com/Minecraft.Download/indexes/" + versionName + ".json", output); + } + + return new Gson().fromJson(Tools.read(output.getAbsolutePath()), JAssets.class); + } + + public void downloadAsset(JAssetInfo asset, File objectsDir) throws IOException, Throwable { + String assetPath = asset.hash.substring(0, 2) + "/" + asset.hash; + File outFile = new File(objectsDir, assetPath); + if (!outFile.exists()) { + DownloadUtils.downloadFile(MINECRAFT_RES + assetPath, outFile); + } + } + + public void downloadAssets(JAssets assets, String assetsVersion, File outputDir) throws IOException, Throwable { + File hasDownloadedFile = new File(outputDir, "downloaded/" + assetsVersion + ".downloaded"); + if (!hasDownloadedFile.exists()) { + System.out.println("Assets begin time: " + System.currentTimeMillis()); + Map assetsObjects = assets.objects; + mActivity.mLaunchProgress.setMax(assetsObjects.size()); + zeroProgress(); + File objectsDir = new File(outputDir, "objects"); + int downloadedSs = 0; + for (JAssetInfo asset : assetsObjects.values()) { + if (!mActivity.mIsAssetsProcessing) { + return; + } + + downloadAsset(asset, objectsDir); + publishProgress("1", mActivity.getString(R.string.mcl_launch_downloading, assetsObjects.keySet().toArray(new String[0])[downloadedSs])); + downloadedSs++; + } + hasDownloadedFile.getParentFile().mkdirs(); + hasDownloadedFile.createNewFile(); + System.out.println("Assets end time: " + System.currentTimeMillis()); + } + } + + + private JMinecraftVersionList.Version findVersion(String version) { + if (mActivity.mVersionList != null) { + for (JMinecraftVersionList.Version valueVer: mActivity.mVersionList.versions) { + if (valueVer.id.equals(version)) { + return valueVer; + } + } + } + + // Custom version, inherits from base. + return Tools.getVersionInfo(version); + } +} diff --git a/app/src/main/java/net/kdt/pojavlaunch/tasks/RefreshVersionListTask.java b/app/src/main/java/net/kdt/pojavlaunch/tasks/RefreshVersionListTask.java new file mode 100644 index 000000000..33da27162 --- /dev/null +++ b/app/src/main/java/net/kdt/pojavlaunch/tasks/RefreshVersionListTask.java @@ -0,0 +1,128 @@ +package net.kdt.pojavlaunch.tasks; + +import android.os.*; +import android.support.v7.widget.*; +import android.view.*; +import android.widget.*; +import android.widget.AdapterView.*; +import com.google.gson.*; +import java.io.*; +import java.util.*; +import net.kdt.pojavlaunch.*; +import net.kdt.pojavlaunch.prefs.*; +import net.kdt.pojavlaunch.utils.*; + +import android.support.v7.widget.PopupMenu; + +public class RefreshVersionListTask extends AsyncTask> +{ + private BaseLauncherActivity mActivity; + + public RefreshVersionListTask(BaseLauncherActivity activity) { + mActivity = activity; + } + + @Override + protected ArrayList doInBackground(Void[] p1) + { + try { + mActivity.mVersionList = new Gson().fromJson(DownloadUtils.downloadString("https://launchermeta.mojang.com/mc/game/version_manifest.json"), JMinecraftVersionList.class); + ArrayList versionStringList = filter(mActivity.mVersionList.versions, new File(Tools.versnDir).listFiles()); + + return versionStringList; + } catch (Exception e){ + e.printStackTrace(); + } + return null; + } + + @Override + protected void onPostExecute(ArrayList result) + { + super.onPostExecute(result); + + final PopupMenu popup = new PopupMenu(mActivity, mActivity.mVersionSelector); + popup.getMenuInflater().inflate(R.menu.menu_versionopt, popup.getMenu()); + + if(result != null && result.size() > 0) { + ArrayAdapter adapter = new ArrayAdapter(mActivity, android.R.layout.simple_spinner_item, result); + adapter.setDropDownViewResource(android.R.layout.simple_list_item_single_choice); + mActivity.mVersionSelector.setAdapter(adapter); + mActivity.mVersionSelector.setSelection(selectAt(result.toArray(new String[0]), mActivity.mProfile.getVersion())); + } else { + mActivity.mVersionSelector.setSelection(selectAt(mActivity.mAvailableVersions, mActivity.mProfile.getVersion())); + } + mActivity.mVersionSelector.setOnItemSelectedListener(new OnItemSelectedListener(){ + + @Override + public void onItemSelected(AdapterView p1, View p2, int p3, long p4) + { + String version = p1.getItemAtPosition(p3).toString(); + mActivity.mProfile.setVersion(version); + + PojavProfile.setCurrentProfile(mActivity, mActivity.mProfile); + if (PojavProfile.isFileType(mActivity)) { + PojavProfile.setCurrentProfile(mActivity, MCProfile.build(mActivity.mProfile)); + } + + mActivity.mTextVersion.setText(mActivity.getString(R.string.mcl_version_msg, version)); + } + + @Override + public void onNothingSelected(AdapterView p1) + { + // TODO: Implement this method + } + }); + mActivity.mVersionSelector.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener(){ + @Override + public boolean onItemLongClick(AdapterView p1, View p2, int p3, long p4) + { + // Implement copy, remove, reinstall,... + popup.show(); + return true; + } + }); + + popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { + public boolean onMenuItemClick(MenuItem item) { + return true; + } + }); + + mActivity.mTextVersion.setText(mActivity.getString(R.string.mcl_version_msg) + mActivity.mVersionSelector.getSelectedItem()); + } + + private ArrayList filter(JMinecraftVersionList.Version[] list1, File[] list2) { + ArrayList output = new ArrayList(); + + for (JMinecraftVersionList.Version value1: list1) { + if ((value1.type.equals("release") && LauncherPreferences.PREF_VERTYPE_RELEASE) || + (value1.type.equals("snapshot") && LauncherPreferences.PREF_VERTYPE_SNAPSHOT) || + (value1.type.equals("old_alpha") && LauncherPreferences.PREF_VERTYPE_OLDALPHA) || + (value1.type.equals("old_beta") && LauncherPreferences.PREF_VERTYPE_OLDBETA)) { + output.add(value1.id); + } + } + + for (File value2: list2) { + if (!output.contains(value2.getName())) { + output.add(value2.getName()); + } + } + + return output; + } + + private int selectAt(String[] strArr, String select) { + int count = 0; + for(String str : strArr){ + if (str.equals(select)) { + return count; + } else { + count++; + } + } + return -1; + } +}