-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathMain.java
More file actions
448 lines (369 loc) · 16.4 KB
/
Main.java
File metadata and controls
448 lines (369 loc) · 16.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
package com.github.balloonupdate.mcpatch.client;
import com.github.balloonupdate.mcpatch.client.config.AppConfig;
import com.github.balloonupdate.mcpatch.client.exceptions.McpatchBusinessException;
import com.github.balloonupdate.mcpatch.client.logging.ConsoleHandler;
import com.github.balloonupdate.mcpatch.client.logging.FileHandler;
import com.github.balloonupdate.mcpatch.client.logging.Log;
import com.github.balloonupdate.mcpatch.client.logging.LogLevel;
import com.github.balloonupdate.mcpatch.client.selfupdate.SelfUpdateManager;
import com.github.balloonupdate.mcpatch.client.selfupdate.SelfUpdateInstaller;
import com.github.balloonupdate.mcpatch.client.ui.McPatchWindow;
import com.github.balloonupdate.mcpatch.client.utils.BytesUtils;
import com.github.balloonupdate.mcpatch.client.utils.DialogUtility;
import com.github.balloonupdate.mcpatch.client.utils.Env;
import com.github.kasuminova.GUI.SetupSwing;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.constructor.Constructor;
import org.yaml.snakeyaml.parser.ParserException;
import java.awt.*;
import java.io.*;
import java.lang.instrument.Instrumentation;
import java.nio.channels.ClosedByInterruptException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;
public class Main {
/**
* 程序的启动方式
*/
public enum StartMethod {
/**
* 作为独立进程启动
*/
Standalone,
/**
* 作为 java agent lib 启动
*/
JavaAgent,
/**
* 由 modloader 启动
*/
ModLoader,
}
public static void main(String[] args) throws Throwable {
// 最开始就执行待处理的更新替换(此时 JAR 锁定最弱)
SelfUpdateInstaller.installPendingUpdate();
boolean graphicsMode = Desktop.isDesktopSupported();
if (args.length > 0 && args[0].equals("windowless"))
graphicsMode = false;
AppMain(graphicsMode, StartMethod.Standalone, true, false);
}
public static void premain(String agentArgs, Instrumentation ins) throws Throwable {
// 最开始就执行待处理的更新替换(此时 JAR 锁定最弱)
SelfUpdateInstaller.installPendingUpdate();
boolean graphicsMode = Desktop.isDesktopSupported();
if (agentArgs != null && agentArgs.equals("windowless"))
graphicsMode = false;
AppMain(graphicsMode, StartMethod.JavaAgent, true, false);
}
public static boolean modloader(boolean enableLogFile, boolean disableTheme) throws Throwable {
boolean graphicsMode = Desktop.isDesktopSupported();
return AppMain(graphicsMode, StartMethod.ModLoader, enableLogFile, disableTheme);
}
/**
* McPatchClient主逻辑
* @param graphicsMode 是否以图形模式启动(桌面环境通常以图形模式启动,安卓环境通常不以图形模式启动)
* @param startMethod 程序的启动方式。
* @param enableLogFile 是否写入日志文件
* @param disableTheme 是否强制禁用主题
* @return 有木有文件更新
*/
static boolean AppMain(boolean graphicsMode, StartMethod startMethod, boolean enableLogFile, boolean disableTheme) throws Throwable {
// 记录有无更新
boolean hasUpdate = false;
McPatchWindow window = null;
try {
// 初始化控制台日志系统
InitConsoleLogging(graphicsMode, enableLogFile);
// 准备各种目录
Path progDir = getProgramDirectory();
Path workDir = getWorkDirectory(progDir);
AppConfig config = new AppConfig(readConfig(progDir.resolve("mcpatch.yml")));
Path baseDir = getUpdateDirectory(workDir, config);
// 初始化文件日志系统
String logFileName = graphicsMode ? "mcpatch.log" : "mcpatch.log.txt";
Path logFilePath = progDir.resolve(logFileName);
if (enableLogFile)
InitFileLogging(logFilePath);
// 非独立进程启动时,使用标签标明日志所属模块
if (startMethod == StartMethod.ModLoader || startMethod == StartMethod.JavaAgent)
Log.setAppIdentifier(true);
// 打印调试信息
PrintEnvironmentInfo(graphicsMode, startMethod, baseDir, workDir);
// 应用主题
if (graphicsMode && !disableTheme && !config.disableTheme)
SetupSwing.init();
// 初始化UI
window = graphicsMode ? new McPatchWindow() : null;
// 初始化窗口
if (window != null) {
window.setTitleText(config.windowTitle);
window.setLabelText("正在连接到更新服务器");
window.setLabelSecondaryText("");
// 弹出窗口
if (!config.silentMode)
window.show();
}
// ========== 客户端自身更新检查 ==========
// 调试信息
Log.debug("clientUpdate 配置: " + (config.clientUpdate != null ? "已加载" : "null"));
if (config.clientUpdate != null) {
Log.debug(" enabled: " + config.clientUpdate.enabled);
Log.debug(" githubRepo: " + config.clientUpdate.githubRepo);
}
if (config.clientUpdate != null && config.clientUpdate.enabled) {
try {
Log.info("正在检查客户端自身更新...");
// 设置系统属性传递配置
if (config.clientUpdate.serverUrl != null && !config.clientUpdate.serverUrl.isEmpty()) {
System.setProperty("mcpatch.selfupdate.server-url", config.clientUpdate.serverUrl);
}
if (config.clientUpdate.channel != null) {
System.setProperty("mcpatch.selfupdate.channel", config.clientUpdate.channel);
}
// 执行自更新检查(显示进度窗口)
SelfUpdateManager.performSelfUpdate(graphicsMode);
} catch (Exception e) {
Log.error("客户端自更新检查失败: " + e.getMessage());
// 自更新失败不影响正常更新流程
}
} else {
Log.debug("客户端自更新未启用,跳过检查");
}
Work work = new Work();
work.window = window;
work.config = config;
work.baseDir = baseDir;
work.progDir = progDir;
work.logFilePath = logFilePath;
work.graphicsMode = graphicsMode;
work.startMethod = startMethod;
try {
// 启动更新任务
hasUpdate = work.run();
} catch (McpatchBusinessException e) {
boolean a = e.getCause() instanceof InterruptedException;
boolean b = e.getCause() instanceof ClosedByInterruptException;
if (!a && !b) {
// 打印异常日志
try {
Log.openIndent("Crash");
Log.error(e.toString());
Log.closeIndent();
} catch (Exception ex) {
System.out.println("------------------------");
System.out.println(ex);
}
// 图形模式下弹框显示错误
if (graphicsMode) {
boolean sp = startMethod == StartMethod.Standalone;
String errMsg = e.getMessage() != null ? e.getMessage() : "<No Exception Message>";
String errMessage = BytesUtils.stringBreak(errMsg, 80, "\n");
String title = "发生错误 " + Env.getVersion();
String content = errMessage + "\n";
content += !sp ? "点击\"是\"显示错误详情并停止启动Minecraft," : "点击\"是\"显示错误详情并退出,";
content += !sp ? "点击\"否\"继续启动Minecraft" : "点击\"否\"直接退出程序";
boolean choice = DialogUtility.confirm(title, content);
if (!sp)
{
if (choice)
{
DialogUtility.error("错误详情 " + Env.getVersion(), e.toString());
throw e;
}
} else {
if (choice)
DialogUtility.error("错误详情 " + Env.getVersion(), e.toString());
throw e;
}
}
} else {
Log.info("更新过程被用户打断!");
}
}
} finally {
if (window != null)
window.destroy();
if (startMethod != Main.StartMethod.Standalone)
Log.info("continue to start Minecraft!");
// if (startMethod == StartMethod.Standalone)
// Runtime.getRuntime().exit(0);
}
return hasUpdate;
}
/**
* 获取Jar文件所在的目录
*/
static Path getProgramDirectory()
{
if (Env.isDevelopment()) {
String devWorkDir = System.getenv("MCPATCH_DEV_WORK_DIR");
String devProgDir = System.getenv("MCPATCH_DEV_PROG_DIR");
// 优先用环境变量里的
if (devWorkDir != null && devProgDir != null) {
return Paths.get(devProgDir);
}
// 然后用test文件夹
Path userDir = Paths.get(System.getProperty("user.dir"));
return userDir.resolve("test");
}
return Env.getJarPath().getParent();
}
/**
* 获取进程的工作目录
*/
static Path getWorkDirectory(Path progDir) {
Path userDir = Paths.get(System.getProperty("user.dir"));
if (Env.isDevelopment()) {
String devWorkDir = System.getenv("MCPATCH_DEV_WORK_DIR");
String devProgDir = System.getenv("MCPATCH_DEV_PROG_DIR");
Path workDir;
// 优先用环境变量里的
if (devWorkDir != null && devProgDir != null) {
workDir = Paths.get(devWorkDir);
} else {
// 同程序文件夹
workDir = progDir;
}
try {
Files.createDirectories(workDir);
return workDir;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return userDir;
}
/**
* 获取需要更新的起始目录
* @param workDir 工作目录
* @param config 配置信息
* @return 更新起始目录
* @throws McpatchBusinessException 当智能搜索搜不到.minecraft目录时
*/
static Path getUpdateDirectory(Path workDir, AppConfig config) throws McpatchBusinessException {
// 开发环境下直接返回工作目录
if (Env.isDevelopment())
return workDir;
// 如果填写了base-path,就使用
if (!config.basePath.equals("")) {
return Env.getJarPath().getParent().resolve(config.basePath);
}
// 如果没有填写,就智能搜索
Path result = searchDotMinecraft(workDir);
// 必须找到才可以
if (result == null) {
String text = "找不到.minecraft目录。" +
"请将软件放到.minecraft目录的同级或者.minecraft目录下(最大7层深度)然后再次尝试运行。" +
"Windows系统下请不要使用右键的“打开方式”选择Java运行,而是要将Java设置成默认打开方式然后双击打开";
throw new McpatchBusinessException(text);
}
return result;
}
/**
* 向上搜索,直到有一个父目录包含 .minecraft 目录
*/
static Path searchDotMinecraft(Path basedir) {
File d = basedir.toFile();
for (int i = 0; i < 7; i++) {
if (d == null || !d.exists()) {
return null;
}
File[] files = d.listFiles();
if (files != null) {
for (File f : files) {
if (f.getName().equals(".minecraft")) {
return d.toPath();
}
}
}
d = d.getParentFile();
}
return null;
}
// 从外部/内部读取配置文件并将内容返回
static Map<String, Object> readConfig(Path external) throws McpatchBusinessException {
try {
// System.out.println("aaa " + external.toFile().getAbsolutePath());
Map<String, Object> result;
Yaml yaml = new Yaml(new Constructor(new LoaderOptions()));
// 如果外部配置文件存在,优先使用
if (Files.exists(external)) {
result = yaml.load(new String(Files.readAllBytes(external)));
}
// 如果内部配置文件存在,则读取内部的
else {
// 开发时必须要有外部配置文件
if (Env.isDevelopment()) {
throw new McpatchBusinessException("找不到配置文件: mcpatch.yml,开发时必须要有配置文件");
}
// 读取内部配置文件
try (JarFile jar = new JarFile(Env.getJarPath().toFile())) {
ZipEntry entry = jar.getJarEntry("mcpatch.yml");
try (InputStream stream = jar.getInputStream(entry)) {
result = yaml.load(stream);
}
}
}
// System.out.println(result);
return result;
//
// if (content.startsWith(":")) {
// try {
// content = new String(Base64.getDecoder().decode(content.substring(1)));
// } catch (IllegalArgumentException e) {
// throw new InvalidConfigFileException();
// }
// }
} catch (ParserException | IOException e) {
throw new McpatchBusinessException(e);
}
}
/**
* 初始化控制台日志系统
*/
static void InitConsoleLogging(boolean graphicsMode, boolean enableLogFile) {
LogLevel level;
if (Env.isDevelopment()) {
// 图形模式或者说禁用了日志文件,这时console就应该显示更详细的日志
if (graphicsMode || !enableLogFile) {
level = LogLevel.Debug;
} else {
level = LogLevel.Info;
}
} else {
// 打包后也要显示详细一点的日志
level = LogLevel.Debug;
}
Log.addHandler(new ConsoleHandler(level));
}
/**
* 初始化文件日志系统
*/
static void InitFileLogging(Path logFilePath) {
Log.addHandler(new FileHandler(LogLevel.All, logFilePath));
}
/**
* 收集并打印环境信息
*/
static void PrintEnvironmentInfo(boolean graphicsMode, StartMethod startMethod, Path baseDir, Path workDir) {
String jvmVersion = System.getProperty("java.version");
String jvmVendor = System.getProperty("java.vendor");
String osName = System.getProperty("os.name");
String osArch = System.getProperty("os.arch");
String osVersion = System.getProperty("os.version");
Log.info("已用内存: " + BytesUtils.convertBytes(Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()));
Log.info("图形模式: " + graphicsMode);
Log.info("启动方式: " + startMethod);
Log.info("基本目录: " + baseDir);
Log.info("工作目录: " + workDir);
Log.info("二进制文件目录: " + (Env.isDevelopment() ? "Dev" : Env.getJarPath()));
Log.info("软件版本: " + Env.getVersion() + " (" + Env.getGitCommit() + ")");
Log.info("虚拟机版本: " + jvmVendor + " (" + jvmVersion + ")");
Log.info("操作系统: " + osName + ", " + osVersion + ", " + osArch);
}
}