Example #1
0
  private void executeTask(Task t) {
    if (!shouldContinue || t == null) return;
    processTasks(t.getDependTasks());

    HMCLog.log("Executing task: " + t.getInfo());
    for (DoingDoneListener<Task> d : taskListener) d.onDoing(t);
    for (DoingDoneListener<Task> d : t.getTaskListeners()) d.onDoing(t);

    boolean flag = true;
    try {
      t.executeTask();
    } catch (Throwable e) {
      t.setFailReason(e);
      flag = false;
    }
    if (flag) {
      HMCLog.log((t.isAborted() ? "Task aborted: " : "Task finished: ") + t.getInfo());
      for (DoingDoneListener<Task> d : taskListener) d.onDone(t);
      for (DoingDoneListener<Task> d : t.getTaskListeners()) d.onDone(t);
      processTasks(t.getAfterTasks());
    } else {
      HMCLog.err("Task failed: " + t.getInfo(), t.getFailReason());
      for (DoingDoneListener<Task> d : taskListener) d.onFailed(t);
      for (DoingDoneListener<Task> d : t.getTaskListeners()) d.onFailed(t);
    }
  }
Example #2
0
  // <editor-fold defaultstate="collapsed" desc="Game Launch">
  void genLaunchCode(final Consumer<GameLauncher> listener) {
    if (isLaunching) return;
    isLaunching = true;
    HMCLog.log("Start generating launching command...");
    File file = getCurrentProfile().getCanonicalGameDirFile();
    if (!file.exists()) {
      HMCLog.warn("The minecraft path is wrong, please check it yourself.");
      MessageBox.Show(C.i18n("minecraft.wrong_path"));
      return;
    }
    final String name = (String) cboProfiles.getSelectedItem();
    if (StrUtils.isBlank(name) || getCurrentProfile().getSelectedMinecraftVersion() == null) {
      HMCLog.warn("There's no selected version, rechoose a version.");
      MessageBox.Show(C.i18n("minecraft.no_selected_version"));
      return;
    }

    final int index = cboLoginMode.getSelectedIndex();
    if (index < 0 || index >= IAuthenticator.LOGINS.size()) {
      HMCLog.warn("There's no login method.");
      MessageBox.Show(C.i18n("login.methods.no_method"));
      return;
    }
    final IAuthenticator l = IAuthenticator.LOGINS.get(index);
    final LoginInfo li =
        new LoginInfo(
            Settings.getInstance().getUsername(),
            l.isLoggedIn() || l.isHidePasswordBox() ? null : new String(txtPassword.getPassword()));
    Thread t =
        new Thread() {
          @Override
          public void run() {
            Thread.currentThread().setName("Game Launcher");
            DefaultGameLauncher gl =
                new DefaultGameLauncher(
                    getCurrentProfile(), li, l, Settings.getInstance().getDownloadSource());
            gl.failEvent.register(
                (sender, s) -> {
                  if (s != null) MessageBox.Show(s);
                  MainFrame.instance.closeMessage();
                  isLaunching = false;
                  return true;
                });
            gl.successEvent.register(
                (sender, s) -> {
                  isLaunching = false;
                  return true;
                });
            listener.accept(gl);
            gl.makeLaunchCommand();
          }
        };
    t.start();
  }
Example #3
0
  MainFrame() {
    defaultTitle = Main.makeTitle();
    enableShadow = Settings.getInstance().isEnableShadow();
    if (enableShadow) setSize(834, 542);
    else setSize(802, 511);
    setDefaultCloseOperation(3);
    setTitle(Main.makeTitle());
    initComponents();
    selectTab("main");
    loadBackground();

    setLocationRelativeTo(null);

    if (enableShadow)
      try {
        setBackground(new Color(0, 0, 0, 0));
        getRootPane().setBorder(border = new DropShadowBorder(borderColor, 4));
      } catch (Throwable ex) {
        HMCLog.err("Failed to set window transparent.", ex);
        Settings.getInstance().setEnableShadow(false);
        setSize(802, 511);
      }

    ((JPanel) getContentPane()).setOpaque(true);
  }
Example #4
0
  private void closeFiles() {
    // Close file.
    if (file != null)
      try {
        file.close();
        file = null;
      } catch (IOException e) {
        HMCLog.warn("Failed to close file", e);
      }

    // Close connection to server.
    if (stream != null)
      try {
        stream.close();
        stream = null;
      } catch (IOException e) {
        HMCLog.warn("Failed to close stream", e);
      }
  }
Example #5
0
 public void loadBackground() {
   background =
       Utils.searchBackgroundImage(
           Main.getIcon("background.jpg"), Settings.getInstance().getBgpath(), 800, 480);
   if (background != null) {
     if (backgroundLabel == null) {
       backgroundLabel = new JLabel(background);
       backgroundLabel.setBounds(0, 0, 800, 480);
     } else backgroundLabel.setIcon(background);
     centralPanel.add(backgroundLabel, -1);
   } else HMCLog.warn("No Background Image, the background will be white!");
 }
Example #6
0
 @Override
 public boolean executeTask() {
   if (mv == null || assetsDownloadURLs == null) {
     setFailReason(new RuntimeException(C.i18n("assets.not_refreshed")));
     return false;
   }
   progress = 0;
   max = assetsDownloadURLs.size();
   al = new ArrayList<>();
   int hasDownloaded = 0;
   for (int i = 0; i < max; i++) {
     String mark = assetsDownloadURLs.get(i);
     String url = u + mark;
     File location = assetsLocalNames.get(i);
     if (!location.getParentFile().exists()) location.getParentFile().mkdirs();
     if (location.isDirectory()) continue;
     boolean need = true;
     try {
       if (location.exists()) {
         FileInputStream fis = new FileInputStream(location);
         String sha = DigestUtils.sha1Hex(NetUtils.getBytesFromStream(fis));
         IOUtils.closeQuietly(fis);
         if (contents.get(i).eTag.equals(sha)) {
           hasDownloaded++;
           HMCLog.log(
               "File "
                   + assetsLocalNames.get(i)
                   + " has downloaded successfully, skipped downloading.");
           if (ppl != null) ppl.setProgress(this, hasDownloaded, max);
           continue;
         }
       }
     } catch (IOException e) {
       HMCLog.warn("Failed to get hash: " + location, e);
       need = !location.exists();
     }
     if (need) al.add(new FileDownloadTask(url, location).setTag(mark));
   }
   return true;
 }
Example #7
0
 public static ModInfo readModInfo(File f) {
   ModInfo i = new ModInfo();
   i.location = f;
   try {
     try (ZipFile jar = new ZipFile(f)) {
       ZipEntry entry = jar.getEntry("mcmod.info");
       if (entry != null) return getForgeModInfo(f, jar, entry);
       entry = jar.getEntry("litemod.json");
       if (entry != null) return getLiteLoaderModInfo(f, jar, entry);
       return i;
     }
   } catch (IOException ex) {
     HMCLog.warn("File " + f + " is not a jar.", ex);
   } catch (JsonSyntaxException ignore) {
   }
   return i;
 }
Example #8
0
  // <editor-fold defaultstate="collapsed" desc="Loads">
  private void prepareAuths() {
    preaparingAuth = true;
    cboLoginMode.removeAllItems();
    for (IAuthenticator str : IAuthenticator.LOGINS)
      try {
        cboLoginMode.addItem(str.getName());
      } catch (Exception ex) {
        HMCLog.warn("Failed to get login name", ex);
      }
    int loginType = Settings.getInstance().getLoginType();
    if (0 <= loginType && loginType < cboLoginMode.getItemCount()) {
      preaparingAuth = false;

      cboLoginMode.setSelectedIndex(loginType);

      cboLoginModeItemStateChanged(null);
    }
  }
Example #9
0
  // Download file.
  @Override
  public boolean executeTask() {
    for (PreviousResult<String> p : al) this.url = IOUtils.parseURL(p.getResult());

    for (int repeat = 0; repeat < 6; repeat++) {
      if (repeat > 0) HMCLog.warn("Failed to download, repeat: " + repeat);
      try {

        // Open connection to URL.
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setConnectTimeout(5000);
        connection.setRequestProperty("User-Agent", "Hello Minecraft! Launcher");

        // Connect to server.
        connection.connect();

        // Make sure response code is in the 200 range.
        if (connection.getResponseCode() / 100 != 2) {
          setFailReason(
              new NetException(C.i18n("download.not_200") + " " + connection.getResponseCode()));
          return false;
        }

        // Check for valid content length.
        int contentLength = connection.getContentLength();
        if (contentLength < 1) {
          setFailReason(new NetException("The content length is invalid."));
          return false;
        }

        // Set the size for this download if it hasn't been already set.
        if (size == -1) size = contentLength;

        filePath.getParentFile().mkdirs();

        File tempFile = new File(filePath.getAbsolutePath() + ".hmd");
        if (!tempFile.exists()) tempFile.createNewFile();

        // Open file and seek to the end of it.
        file = new RandomAccessFile(tempFile, "rw");
        file.seek(downloaded);

        stream = connection.getInputStream();
        while (true) {
          // Size buffer according to how much of the file is left to download.
          if (!shouldContinue) {
            closeFiles();
            filePath.delete();
            break;
          }

          byte buffer[] = new byte[MAX_BUFFER_SIZE];

          // Read from server into buffer.
          int read = stream.read(buffer);
          if (read == -1) break;

          // Write buffer to file.
          file.write(buffer, 0, read);
          downloaded += read;

          if (ppl != null) ppl.setProgress(this, downloaded, size);
        }
        closeFiles();
        if (aborted) tempFile.delete();
        else tempFile.renameTo(filePath);
        if (ppl != null) ppl.onProgressProviderDone(this);
        return true;
      } catch (Exception e) {
        setFailReason(new NetException(C.i18n("download.failed") + " " + url, e));
      } finally {
        closeFiles();
      }
    }
    return false;
  }
Example #10
0
  public static void main(String[] args) {
    Thread.currentThread().setName("launcher");
    println("*** " + Main.makeTitle() + " ***");

    LogWindow.instance.setTerminateGame(Utils::shutdownForcely);

    boolean showInfo = false;
    String classPath = "";
    String mainClass = "net.minecraft.client.Minecraft";

    ArrayList<String> cmdList = new ArrayList<>();

    for (String s : args)
      if (s.startsWith("-cp=")) classPath = classPath.concat(s.substring("-cp=".length()));
      else if (s.startsWith("-mainClass=")) mainClass = s.substring("-mainClass=".length());
      else if (s.equals("-debug")) showInfo = true;
      else cmdList.add(s);

    String[] cmds = (String[]) cmdList.toArray(new String[cmdList.size()]);

    String[] tokenized = StrUtils.tokenize(classPath, File.pathSeparator);
    int len = tokenized.length;

    if (showInfo) {
      try {
        File logFile = new File("hmclmc.log");
        if (!logFile.exists()) logFile.createNewFile();
        FileOutputStream tc = new FileOutputStream(logFile);
        DoubleOutputStream out = new DoubleOutputStream(tc, System.out);
        System.setOut(new LauncherPrintStream(out));
        DoubleOutputStream err = new DoubleOutputStream(tc, System.err);
        System.setErr(new LauncherPrintStream(err));
      } catch (Exception e) {
        println("Failed to add log file appender.");
        e.printStackTrace();
      }

      println("Arguments: {\n" + StrUtils.parseParams("    ", args, "\n") + "\n}");
      println("Main Class: " + mainClass);
      println("Class Path: {\n" + StrUtils.parseParams("    ", tokenized, "\n") + "\n}");
      SwingUtilities.invokeLater(() -> LogWindow.instance.setVisible(true));
    }

    URL[] urls = new URL[len];

    try {
      for (int j = 0; j < len; j++) urls[j] = new File(tokenized[j]).toURI().toURL();
    } catch (Throwable e) {
      MessageBox.Show(C.i18n("crash.main_class_not_found"));
      println("Failed to get classpath.");
      e.printStackTrace();
      return;
    }

    if (!JdkVersion.isJava64Bit() && Platform.getPlatform() == Platform.BIT_64)
      MessageBox.Show(C.i18n("advice.os64butjdk32"));

    Method minecraftMain;
    try {
      minecraftMain =
          new URLClassLoader(urls).loadClass(mainClass).getMethod("main", String[].class);
    } catch (ClassNotFoundException | NoSuchMethodException | SecurityException t) {
      MessageBox.Show(C.i18n("crash.main_class_not_found"));
      println("Minecraft main class not found.");
      t.printStackTrace();
      return;
    }

    println("*** Launching Game ***");

    try {
      minecraftMain.invoke(null, new Object[] {cmds});
    } catch (Throwable throwable) {
      HMCLog.err("Cought exception!");
      String trace = StrUtils.getStackTrace(throwable);
      final String advice = MinecraftCrashAdvicer.getAdvice(trace);
      MessageBox.Show(C.i18n("crash.minecraft") + ": " + advice);

      LogWindow.instance.log(C.i18n("crash.minecraft"));
      LogWindow.instance.log(advice);
      LogWindow.instance.log(trace);
      LogWindow.instance.setExit(TrueFunction.instance);
      LogWindow.instance.setVisible(true);
    }

    println("*** Game Exited ***");
  }