Compare commits

...
147 Commits
Author SHA1 Message Date
Glavo 9901bf738d fix crash (#1825) 2022-11-05 22:12:44 +08:00
huanghongxun a3d8c6b3b3 feat(skin): introduce new official skins. 2022-11-05 20:22:02 +08:00
huanghongxun 948928f740 feat: update HMCLauncher.exe 2022-11-05 20:11:22 +08:00
Rei Hatada 71e98c035e change (#1824) 2022-11-05 19:51:39 +08:00
Glavo af107b15c0 完善 HiPer 支持 (#1821)
* Display hiper token expiration time

* Automatically download missing files when starting HiPer

* Disable start HiPer when token is empty
2022-11-05 19:36:17 +08:00
Glavo 8687bb9487 修复 MessageDialogPane 总是折叠内容的问题 (#1815)
* fix #1751: Use ScrollPane in message dialog only when needed
close #1777

* Parse segment only if it contains xml tag
2022-11-05 19:28:24 +08:00
huanghongxun a70e53364d fix(multiplayer): force using authlib-injector in multiplayer mode. 2022-10-30 13:45:34 +08:00
zkitefly 11a1c37765 将日志更换至docs.hmcl.net (#1812)
* 将日志更换至docs.hmcl.net,以便更新日志

* 修改链接

* 更换目录
2022-10-30 01:29:51 +08:00
Glavo 68a8944810 改进 HiPer 支持 (#1763)
* Disable start hiper button when token is empty

* Use gsudo start hiper

* Automatically request administrator privileges on Windows and Linux

* Automatically start hiper with sudo on mac

* Update I18N

* Prompt user to chown unwritable files

* Update HiPer file verification failed prompt

* Log other hiper exceptions

* temporarily disable gsudo

* Detect admin rights with 'net session'

* Hide the hint pane when running with administrator privileges

* Prompt user when starting HMCL with sudo

* Fix ClassNotFoundException when no JavaFX

* Update the prompt when the permission cannot be obtained

* Add support for saving multiple HiPer configurations

* update link
close Glavo/HMCL#3

* Detect RISC-V 32

* Save original hiper authorization information

* Add support for importing and exporting license files

* Set initial license file name

* Complement the missing message

* Handling gsudo failure to obtain permission
2022-10-25 21:55:12 +08:00
zkitefly b280b238df 尝试完成 #1780 (#1789) 2022-10-25 21:52:23 +08:00
huanghongxun 0f39aad429 fix(auth): legacy user type for OfflineAccount. 2022-10-25 21:48:55 +08:00
Glavo ff78297ee5 fix IntegrityCheck::performCheck (#1792) 2022-10-23 23:28:22 +08:00
Glavo f75bbdcecc Log HMCL jar path (#1794) 2022-10-23 23:27:42 +08:00
Glavo 694e31a7fe Cache manifest in JarUtils (#1797) 2022-10-23 23:27:21 +08:00
Glavo c113670cda Migrate HMCL_DIRECTORY to the user directory (#1785) 2022-10-09 13:21:02 +08:00
zkitefly 1b3c399335 添加“测试能否联机”按钮 (#1757)
* add

* 修改图标(其实我不知道该弄啥图标好……)

* fix
2022-10-09 11:18:00 +08:00
huanghongxun 45cbe20449 fix: crash when there is an incorrect authlib-injector server url. Closes #1774. 2022-10-08 17:39:04 +08:00
zkiteflyandYuhui Huang 4d606510f6 修改 登录失败 弹窗 (#1782)
* 修改 登录失败 弹窗

* fix

* Update I18N.properties

* Update I18N_zh_CN.properties

* Update I18N_zh.properties

* Update I18N_zh.properties

* Update I18N_zh_CN.properties

* Edit

Co-authored-by: Yuhui Huang <i@huangyuhui.net>
2022-10-08 17:33:07 +08:00
huanghongxun a6639552cf fix: lblCreationWarning not wrapping text. Closes #1783. 2022-10-08 17:31:28 +08:00
zkitefly 2a088ec555 更新多人联机页面 (#1758)
* 更新 multiplayer.error.file_not_found 翻译

* 修改翻译

* 移除标题

* add

* try fix

* try fix

* try fix

* try fix

* try fix

* try

* try

* try

* fix

* fix

* add

* fix

* fix

* add

* fix

* edit
2022-10-08 17:13:55 +08:00
zkitefly 1c46d63367 try (#1768) 2022-10-08 17:12:13 +08:00
zkitefly f2b7fae694 添加“忘记密码”按钮 (#1765) 2022-10-08 17:11:56 +08:00
Glavo 43986676d8 修复中文路径下启动 <= 1.12.2 的版本没有声音的问题 (#1754)
* Use native encoding by default

* Fix the problem that LWJGL fails to load OpenAL under Java 18
2022-10-08 17:10:27 +08:00
Glavo 2649e79d47 fix build fails with Java 19 (#1784) 2022-10-08 17:09:12 +08:00
zkitefly f83d3cd769 Fix https://github.com/huanghongxun/HMCL/issues/1703 (#1753) 2022-09-28 19:14:15 +08:00
zkitefly f124910f94 修改多人联机帮助与提示 (#1733)
* 修改多人联机提示

* text

* 撤回修改

* 1

* 修改帮助

* fix

* try

* Delete try

* Update I18N.properties

* Update I18N_zh.properties

* Update I18N_zh_CN.properties

* Update I18N_zh_CN.properties

* Update I18N_zh.properties

* Update I18N_zh.properties

* Update I18N_zh_CN.properties

* 修改提示框样式

* 修改提示框样式

* fix

* 修改样式

* 修改样式

* 修改提示框样式

* 修改翻译

* 修改翻译

* add

* return

* add

* add

* 去掉图标

* 试图让左边图标为空

* Update MultiplayerPageSkin.java

* ruturn

* add

* add

* Update MultiplayerPageSkin.java

* Update I18N_zh.properties

* Update I18N_zh_CN.properties
2022-09-25 14:25:05 +08:00
zkitefly c1712c3e1e 修改翻译 (#1742) 2022-09-25 14:23:39 +08:00
huanghongxun d817c80629 fix: checkstyle. 2022-09-25 00:31:51 +08:00
huanghongxun 8d830dbf96 fix(microsoft): ok cannot be clicked. Closes #1729. 2022-09-24 23:54:36 +08:00
huanghongxun 0396e96334 feat(multiplayer): update agreement. Closes #1724. 2022-09-24 23:50:48 +08:00
huanghongxun 7b23c7bc79 feat(multiplayer): link to video tutorial. 2022-09-24 23:36:48 +08:00
huanghongxun d3ca50259a fix(modrinth): quilt is already supported. Closes #1746. 2022-09-24 23:16:11 +08:00
huanghongxun 499a65d5fb fix(multiplayer): connection. 2022-09-24 23:03:07 +08:00
huanghongxun 0b61f9856c fix(multiplayer): ui incorrect 2022-09-24 21:55:53 +08:00
huanghongxun c8409dd258 build: update gradle. 2022-09-24 18:38:04 +08:00
huanghongxun e5ea4cd79f feat(multiplayer): broadcast address to local network. 2022-09-24 18:31:22 +08:00
huanghongxun 4d54c7f6ba feat(multiplayer): show token expire time. 2022-09-24 18:31:22 +08:00
Cato : Love the world and myselfandzkitefly 0f4a5c26df 远端配置无法读取,使用本地缓存 (#1740)
* 远端配置无法读取,使用本地缓存

* 远程配置&本地配置确认

* fix err

* fix-err

* fix-err

* fix-err

* fix-err

* restore

* code clean

* fix-err

* add

* fix

* 远端读取异常日志

Co-authored-by: zkitefly <64117916+zkitefly@users.noreply.github.com>
2022-09-24 18:17:34 +08:00
Akira Yamazaki a8b09e2195 修复执行 PreLaunchCommand 时会被阻塞的问题 (#1737) 2022-09-24 16:57:19 +08:00
Cato : Love the world and myself 3ed6e38ad3 新增有效期getValidAt #1727 (#1732)
* 界面标题描述纠正

* 新增有效期getValidAt #1727

* fix err

* fix-err-again

* fix-err

* fix

* fix-4

* rename

* fix

* fix

* code clean
2022-09-24 16:56:19 +08:00
huanghongxun 2028b0ef9c fix(multiplayer): restore LocalServerBroadcaster and impl port forwarding. 2022-09-17 18:36:12 +08:00
zkitefly aa7f9b91c7 修改微软账户重新登录页面提示 (#1710)
* 修改微软账户重新登录页面提示

* 添加忘记添加的

* 修改翻译

* Update I18N_zh.properties

* Update I18N_zh_CN.properties

* Update I18N_zh_CN.properties

* Update I18N_zh.properties
2022-09-17 12:15:56 +08:00
Cato : Love the world and myself d6598310b2 界面标题描述纠正 (#1728) 2022-09-17 12:11:00 +08:00
zkitefly ce6c06987c 修改多人联机提示 (#1725)
* 修改多人联机提示

* 修改

* fix
2022-09-17 12:10:46 +08:00
huanghongxun 90955d7916 fix(ui): ComponentList prefheight wrong. 2022-09-16 02:34:23 +08:00
huanghongxun b3bbd21f1f chore(multiplayer): remove JSTUN. 2022-09-16 01:41:23 +08:00
Cato : Love the world and myselfandYuhui Huang 735a407f0e 缺少字符矫正 / NAT 检测移除 (#1718)
* 缺少字符矫正 / NAT 检测移除

* 错误修复

* 修正nat移除不彻底导致的编译错误

* 授权协议发布

* code-clean

* fix-err

* fix-err-2

* update-in18

* url-fix

Co-authored-by: Yuhui Huang <i@huangyuhui.net>
2022-09-16 01:18:26 +08:00
Glavo 8461b0418c close #1534: open 'java.com' when need to download Java 8 (#1716) 2022-09-15 21:28:02 +08:00
Glavo e46ab8bf9e fix the build errors and checkstyle (#1717) 2022-09-15 21:27:43 +08:00
zkitefly 330548b24e 添加游戏档案创建链接 (#1696)
* Create  获得加入Cato社区网络身份凭证的方法.txt

* Delete 获得加入Cato社区网络身份凭证的方法.txt

* Update CreateMultiplayerRoomDialog.java

* Update CreateMultiplayerRoomDialog.java

* Update MultiplayerPageSkin.java

* add makegameidsettings

* fix

* fix

* fix

* Update CreateAccountPane.java

* Update CreateAccountPane.java

* 听取意见,修改变量名为createProfileLink
2022-09-14 21:46:38 +08:00
Cato : Love the world and myselfandYuhui Huang cf5ccca42d tap/tun二选一,目前优先tun先看效果。 (#1713)
* tap/tun二选一,目前优先tun先看效果。

* 描述修正

* 修正故障描述

Co-authored-by: Yuhui Huang <i@huangyuhui.net>
2022-09-14 21:45:55 +08:00
Cato : Love the world and myself a18bd0729b 配置文件读取失败及证书失效判断 (#1715)
* 配置文件读取失败及证书失效判断

* 描述修正
2022-09-14 21:43:44 +08:00
huanghongxun 662b42c40f fix(multiplayer): get ip from hiper log. 2022-09-12 23:05:13 +08:00
huanghongxun b69c400a08 fix(multiplayer): get ip from hiper log. 2022-09-12 22:45:38 +08:00
huanghongxun f1eb2da57c feat(multiplayer): hiper. 2022-09-12 22:38:36 +08:00
huanghongxun 99be810b5e feat(multiplayer): wip: hiper 2022-09-12 22:38:36 +08:00
zkitefly 03541a6f85 修改 response.errorDescription.contains() 参数 (#1708)
* 添加两个 response.errorDescription.contains()

* 再添加一个qwq

* 删除重复项

* 恢复删除的项

* 修改

* 修改
2022-09-10 21:50:08 +08:00
Chikage0o0 5fe1ef899d fix modrinth modpack install (#1702)
* fix modrinth modpack install

* fix NullPointerException
2022-09-10 21:49:31 +08:00
CNCloud_Casey 6a81f4d240 更新整合包安装的文本介绍 (#1695)
* Update I18N_zh_CN.properties

* Update I18N_zh.properties

* Update I18N_ru.properties

* Update I18N_ja.properties

* Update I18N_es.properties

* Update I18N.properties
2022-09-05 20:11:10 +08:00
zkitefly 3c6aa489e8 添加sh支持 (#1697) 2022-09-05 20:10:49 +08:00
zkitefly ba7043fa92 修改一些提示 (#1699) 2022-09-05 20:10:37 +08:00
huanghongxun bfb6c99484 fix: checkstyle. 2022-09-04 00:26:14 +08:00
huanghongxun a6b26a0cd9 fix(microsoft): show relogin dialog when grant expired. Closes #1691. 2022-09-03 23:35:09 +08:00
huanghongxun 0c7b0f285e fix(microsoft): retry 5 times when socket timeout. Closes #1691. 2022-09-03 23:33:11 +08:00
huanghongxun 5e1ae56740 fix(ui): error dialog overflow. Closes #1677. 2022-09-03 22:44:38 +08:00
huanghongxun b17bac050b fix(ui): not parsing xml. Closes #1678. 2022-09-03 22:28:58 +08:00
huanghongxun b1952a7b37 fix(ui): not wrapping text. Closes #1673. 2022-09-03 22:26:05 +08:00
huanghongxun cc1fc1e4be fix(ui): some text overflow. Closes #1694. 2022-09-03 22:21:38 +08:00
Glavo 6c07924d9b 完善 osx-arm64 原生支持 (#1689)
* Add 1.6~1.18.2 support for osx-arm64

* fix crash on 1.12

* Update I18N
2022-09-03 16:55:27 +08:00
Glavo 835668d781 Update purchase link (#1692) 2022-09-03 16:53:55 +08:00
Glavo 8f7c09d2cc 添加 Linux MIPS64el 平台支持 (#1686)
* Add support for linux-mips64el

* Update PLATFORM.md
2022-09-02 11:37:09 +08:00
Chikage0o0 837939e27c Fix #1684 (#1685)
* 修复生成option.txt与YOSBR模组的冲突

* only search 1 layer
2022-09-02 11:36:58 +08:00
Glavo 058a8e2335 Update JavaVersionConstraint (#1683) 2022-09-01 22:20:16 +08:00
CNCloud_Casey a5af5265be Update README (#1682) 2022-08-31 15:25:29 +08:00
Gamom 8a724587ca 更新错误的翻译键 world.info.player.game_type.adventure (#1674)
* 更新错误的翻译键 world.info.player.game_type.adventure

我不理解 adventure 冒险 为什么会 翻译成极限 ...

* Update I18N_zh.properties
2022-08-31 14:20:56 +08:00
zkitefly bef9c0ad88 Fix #1675 (#1676) 2022-08-31 14:20:39 +08:00
Glavo 8d29775410 添加 Windows on Arm 平台的支持 (#1679)
* Add Minecraft 1.6~1.18.2 support for windows-arm64

* Prompt at startup on non-x86 platforms

* Automatically download JavaFX on windows-arm64

* Update PLATFORM.md
2022-08-31 14:20:27 +08:00
Glavo 620c0e4c73 Automatically download JavaFX on linux-loongarch64_ow (#1670) 2022-08-29 19:28:20 +08:00
Glavo b5c92c1564 Fix stuck on startup when no suitable Java is found (#1671) 2022-08-29 19:27:51 +08:00
huanghongxun 3c3c28aaa5 fix(launch): not escape spaces in exported shell script. Closes #1541. 2022-08-29 00:19:32 +08:00
huanghongxun a80fc34ef1 fix(launch): should not create file when throwing CommandTooLongException. Closes #1606. 2022-08-29 00:03:35 +08:00
huanghongxun 08d7ff138b fix(login): prompt to retry logging in. Closes #1658 #1591 #1544 1608. 2022-08-28 23:57:47 +08:00
huanghongxun 0c172e5d08 fix(crash): incorrect layout for feedbackLabel. Closes #1667. 2022-08-28 21:45:05 +08:00
Glavo bce2d1ea5c Revert ExitWaiter (#1668) 2022-08-28 21:05:43 +08:00
huanghongxun cbc1e26b6f feat(log): hyperlink for log analyzer feedback. Closes #1652. 2022-08-28 17:12:03 +08:00
Yuhui Huang 3b5ddcafa6 fix(quilt): Quilt Hash not enabled. Closes #1657. 2022-08-28 17:03:54 +08:00
Glavo c6a5624708 引导用户下载 Java (#1659)
* Direct users to download Java

* Read JVM options from environment variables
2022-08-28 17:00:15 +08:00
Glavo 23cc568bac Support Microsoft login in dev version (#1651) 2022-08-28 16:59:03 +08:00
Glavo 7ff679c3c8 Revert AdvancedListBox (#1647)
fix #1258, fix #1397, fix #1559, fix #1589, fix #1646
2022-08-28 16:56:52 +08:00
Glavo c873352ee9 更多平台的原生适配 (#1654)
* Add Minecraft 1.13+ support for linux-loongarch64_ow

* Add Minecraft 1.6~1.12.2 support for linux-arm32

* Update documents
2022-08-28 16:56:33 +08:00
Glavo a4164a86af Support path containing unicode characters on Mac OS (#1661) 2022-08-28 16:54:22 +08:00
Glavo c21671e86b 修复通过自动安装更新游戏时的崩溃 (#1662)
* fix game upgrade

* fix #1459: Invalidate the version number cache before saving the version
close #1566
2022-08-28 16:52:26 +08:00
Glavo d9bdc2b1f7 fix #1579: Hide tokens in the exported Minecraft logs (#1665) 2022-08-28 16:51:49 +08:00
huanghongxun 19b6633f4a fix: checkstyle. 2022-08-21 21:29:09 +08:00
huanghongxun 2ad3e7a291 fix(account): Authlib-Injector server may be unknown when in CreateAcountPane tab mode. 2022-08-21 21:26:20 +08:00
huanghongxun 1fa63a528d fix(download): installer items overflow. Closes #1645. 2022-08-21 21:20:10 +08:00
Glavo b80c787b60 为非 x86 平台提供开箱即用的启动支持 (#1610)
* Replace native libraries on non-x86 platforms

* Add support for Linux ARM

* Relax the constraint 'JavaVersionConstraint.VANILLA_X86'

* Fix several hints

* Add OpenGL software renderer option

* Add support for OpenGL software renderer on windows

* Add __GLX_VENDOR_LIBRARY_NAME on Linux

* Catch GLFW error 65543

* Allow users to disable auto completion of native libraries

* fix NPE when violated mandatory constraint

* Add support for Minecraft 1.13

* Add support for Minecraft 1.6~1.12

* Add base support for linux-loongarch64

* Improve warnings on Loongson platform

* Add linux launcher script

* fix typo

* Add support for loongarch64 (old world)
2022-08-21 19:00:05 +08:00
Lonelyxiya c8652012c5 I18N_zh.properties (#1611)
修訂了一些台灣詞彙。來自https://discord.com/channels/815819580840607807/815860830058840064/1003644502478704671
RPMTW的翻譯討論頻道
2022-08-21 18:27:27 +08:00
Glavo e70b43be26 Temporarily rollback HMCLauncher.exe (#1625)
close #1583, close #1577
2022-08-21 18:26:54 +08:00
K1t3AB 2d182807b2 feat(README_cn.md): Added Chinese translation for README.md (#1637)
* feat(README_cn.md): Added Chinese translation for README.md

* edit(README.md): Improved formats for README.md

* fix(README): Roll back to Commit ID to pin lines

* edit(README): Let languages switchers "more like buttons"

* fix(README): Fix errors caused by misunderstanding

* edit(README): Added 8 spaces
2022-08-21 18:26:42 +08:00
huanghongxun 675af3a5aa feat(download): quilt installation. 2022-08-21 18:20:11 +08:00
huanghongxun 4ba4c3e749 feat(quilt): WIP: partially implements quilt installation. 2022-08-20 15:52:22 +08:00
huanghongxun 11e2277c9e feat(account): show little-skin login method by default. Closes #1622. 2022-08-20 14:58:38 +08:00
Yuhui Huang 66642fe621 fix(i18n): line ending of Spanish lang file. 2022-08-08 17:21:19 +08:00
Nekrodamus 3189a22f26 Update I18N_es.properties (#1614)
* Update I18N_es.properties

Updated the Spanish language file to the latest Beta version, using as template the I18N.properties file.

[Completed]

* Update I18N_es.properties

Little fix

* Update I18N_es.properties

More fixes.

* Update I18N_es.properties

Corrected the label for modpacks "Investigaciones" to "Quests".

* Update I18N_es.properties

More fixes

* Update I18N_es.properties

Final fixes

* Update I18N_es.properties

Fixed bug that caused a string not to be translated.

* Update I18N_es.properties

Little fix

* Update I18N_es.properties

Little fix

* Update I18N_es.properties

Little fixes

* Update I18N_es.properties

Little fix

* Update I18N_es.properties

Improved the context of some sentences

* Update I18N_es.properties

Reverted fix

* Update I18N_es.properties

Changes in capitalization

* Update I18N_es.properties

Some fixes...

* Update I18N_es.properties

More corrections...
2022-08-08 17:19:59 +08:00
Tungstend 366e359d83 修复litemod信息获取失败 (#1545)
* 修复Modrinth源加载列表失败,增加Modrinth源获取前置模组功能

* Revert "修复Modrinth源加载列表失败,增加Modrinth源获取前置模组功能"

This reverts commit 1d29c69d92.

* 修复CF源获取模组版本列表不全

* Modrinth源获取类别列表,搜索时增加类别选项

* Update ModrinthRemoteModRepository.java

* Update ModrinthRemoteModRepository.java

* 修复cf源获取前置模组失败

* Revert "Update ModrinthRemoteModRepository.java"

This reverts commit 40b7c1d59d.

* Revert "Revert "Update ModrinthRemoteModRepository.java""

This reverts commit 2027c9ef4c.

* Revert "修复cf源获取前置模组失败"

This reverts commit 4404daf0ea.

* fix conflict

* 修复cf源无法获取前置模组

* fix check style

* Update LiteModMetadata.java
2022-08-08 16:58:55 +08:00
ZekerZhayard f7d8a473aa Fix NoSuchMethodError when compiling with Java 9+ (#1585) 2022-08-08 16:58:14 +08:00
zkitefly 8276bf5d8c 在 README 中添加 Fabric (#1587)
* Create  获得加入Cato社区网络身份凭证的方法.txt

* Delete 获得加入Cato社区网络身份凭证的方法.txt

* Update CreateMultiplayerRoomDialog.java

* Update CreateMultiplayerRoomDialog.java

* Update MultiplayerPageSkin.java

* Update README.md
2022-08-08 16:57:47 +08:00
zkitefly 371150dfa8 添加提示 (#1597)
* Create  获得加入Cato社区网络身份凭证的方法.txt

* Delete 获得加入Cato社区网络身份凭证的方法.txt

* Update CreateMultiplayerRoomDialog.java

* Update CreateMultiplayerRoomDialog.java

* Update MultiplayerPageSkin.java

* text

* text

* now

* now

* 优化下简体,繁体,和英文

* 再优化了下

* fix

* fix

* text

* text

* now
2022-08-08 16:57:31 +08:00
Glavo 38d71fd6bb Add world info page (#1620) 2022-08-08 16:56:03 +08:00
king tsaltedfishandYuhui Huang c627ca96c9 Rewrite badges (#1612)
Co-authored-by: Yuhui Huang <i@huangyuhui.net>
2022-08-08 16:52:58 +08:00
Rovniced 09167bb302 修复curseforge文件名存在中文下载失败 (#1578)
* Update RemoteMod.java

* Update RemoteMod.java

* Update RemoteMod.java
2022-08-08 16:52:02 +08:00
zkitefly a3c24b1b02 因 开黑啦 改名成 KOOK,所以改名 (#1600)
* 修改加入链接的前缀“kaihei.co”->“kook.top”

* 因开黑啦改名成KOOK,所以改名。邀请链接也做相应调整。

* Update bug-report.yml

* Update bug-report.yml

顺便无伤大雅的修改了下这里

* Update config.yml

修改了下这里的英文空格隔离

* Add files via upload

上传新logo

* Delete kaiheila.jpeg

删除旧logo

* Update I18N.properties

修改回原来样式

* Update I18N_zh.properties

修改開黑啦为KOOK
2022-08-08 16:51:38 +08:00
Glavo 9f4a3cf8a8 Disable Microsoft login when auth id is empty 2022-06-19 18:58:38 +08:00
xmdhs 702d27393e replace piston-data.mojang.com 2022-06-17 11:16:33 +08:00
xmdhs 698d3a311d replace piston-meta.mojang.com 2022-06-17 11:16:33 +08:00
Glavo c92f8e3b51 Complete optifine that is not installed automatically 2022-06-16 20:35:14 +08:00
Glavo 7c502ecd01 fix #1311: fix auto complete OptiFine 2022-06-16 20:35:14 +08:00
Glavo a237a31d23 Output the URL in the log when the file is not found 2022-06-16 20:35:14 +08:00
Glavo 5f4fc77258 Use language-independent links 2022-06-15 11:42:16 +08:00
ZekerZhayard 8bd4df68f5 Fix #1543 2022-06-14 12:49:56 +08:00
Glavo 29cff02f3c Update JavaVersionConstraint 2022-06-13 23:30:41 +08:00
Glavo d1bc41e1f1 Detect loongarch 2022-06-13 23:30:41 +08:00
huanghongxun 2fd1bf4c29 fix(i18n): incorrect translation change. 2022-06-05 14:11:04 +08:00
huanghongxun edd89fb040 fix: test. 2022-06-03 23:59:35 +08:00
ByacryaandYuhui Huang 08d6b58c8c feat(i18n): greatly improve en_US translation (#1522)
It seems that the current translation was largely done by Google Translation, so I did some work to improve it.

Some translations can definitely be improved, but I don't have much time at the moment so I will leave it for now.

Co-authored-by: Yuhui Huang <i@huangyuhui.net>
2022-06-03 23:27:27 +08:00
huanghongxun e3fc9f5116 feat: auto find java by default. Closes #1511. 2022-06-03 23:19:47 +08:00
huanghongxun 6dcd808cc8 fix(crash): suggest jdk corruption. Closes #1509. 2022-06-03 23:17:00 +08:00
huanghongxun df6230fc01 fix(install): date deserialization. Closes #1512. 2022-06-03 23:13:40 +08:00
huanghongxun 9f502ae6ae fix(modpack): missing .mrpack extension. Closes #1531. 2022-06-03 22:53:23 +08:00
huanghongxun 2a979d2b15 fix(download): incorrect mcmod url for modpacks. Closes #1525. 2022-06-03 22:47:03 +08:00
huanghongxun ae484e3b67 fix(download): inappropriate translation for "Vanilla+" 2022-06-03 22:47:02 +08:00
Byacrya 7206832edb feat(i18n): correct zh_CN translation
Vanilla+ should be translated to '原版增强' instead of '香草+'.
2022-06-03 21:08:45 +08:00
zkitefly 288b32ed79 I18N.properties (#1526)
* Create  获得加入Cato社区网络身份凭证的方法.txt

* Delete 获得加入Cato社区网络身份凭证的方法.txt

* Update CreateMultiplayerRoomDialog.java

* Update CreateMultiplayerRoomDialog.java

* Update MultiplayerPageSkin.java

* Update I18N_zh_CN.properties

* Update I18N_zh_CN.properties

* Update I18N_zh.properties

* Update I18N_ru.properties

* Update I18N_ja.properties

* Update I18N_es.properties

* Update I18N.properties
2022-06-03 17:01:37 +08:00
zkitefly 53bc3b354f 修改微软账户上传皮肤链接 (#1521)
* Create  获得加入Cato社区网络身份凭证的方法.txt

* Delete 获得加入Cato社区网络身份凭证的方法.txt

* Update CreateMultiplayerRoomDialog.java

* Update CreateMultiplayerRoomDialog.java

* Update MultiplayerPageSkin.java

* Update AccountListItem.java
2022-06-02 20:53:39 +08:00
Tungstend 30565c2b50 修复cf源无法获取前置模组 (#1520)
* 修复Modrinth源加载列表失败,增加Modrinth源获取前置模组功能

* Revert "修复Modrinth源加载列表失败,增加Modrinth源获取前置模组功能"

This reverts commit 1d29c69d92.

* 修复CF源获取模组版本列表不全

* Modrinth源获取类别列表,搜索时增加类别选项

* Update ModrinthRemoteModRepository.java

* Update ModrinthRemoteModRepository.java

* 修复cf源获取前置模组失败

* Revert "Update ModrinthRemoteModRepository.java"

This reverts commit 40b7c1d59d.

* Revert "Revert "Update ModrinthRemoteModRepository.java""

This reverts commit 2027c9ef4c.

* Revert "修复cf源获取前置模组失败"

This reverts commit 4404daf0ea.

* fix conflict

* 修复cf源无法获取前置模组

* fix check style
2022-06-02 14:14:51 +08:00
zkitefly c400c7be9d Account migration link update (#1513)
* Create  获得加入Cato社区网络身份凭证的方法.txt

* Delete 获得加入Cato社区网络身份凭证的方法.txt

* Update CreateMultiplayerRoomDialog.java

* Update CreateMultiplayerRoomDialog.java

* Update MultiplayerPageSkin.java

* Update YggdrasilService.java
2022-06-02 13:04:12 +08:00
zkitefly 7acd9d2491 Update AboutPage.java (#1516)
* Create  获得加入Cato社区网络身份凭证的方法.txt

* Delete 获得加入Cato社区网络身份凭证的方法.txt

* Update CreateMultiplayerRoomDialog.java

* Update CreateMultiplayerRoomDialog.java

* Update MultiplayerPageSkin.java

* Update AboutPage.java
2022-06-02 13:01:30 +08:00
huanghongxun dc26dba1d0 fix(download): category may be null. 2022-05-24 01:17:29 +08:00
huanghongxun 66cbb23a38 fix(java): broken macos java location. 2022-05-24 01:09:10 +08:00
huanghongxun 663fc176d8 feat(java): find java in minecraft runtime directory with any component name. As a new component name "java-runtime-gamma" was added. 2022-05-24 01:02:16 +08:00
Mingye Wang b9ec22677e chore(javaversion): refactor searchPotentialJavaExecutables (#1485)
* chore(javaversion): refactor searchPotentialJavaExecutables

This is a very draft quality PR. I don't even have JDK installed to build it, that's how draft it is.

1. Refactor function to share common steps of the code: system locations, Minecraft launcher runtimes, PATH/HMCL_JRES
2. Modify Minecraft launcher runtimes to include java-runtime-beta

* Update HMCLCore/src/main/java/org/jackhuang/hmcl/util/platform/JavaVersion.java

* Make optional happy

* correct stream-of paren; add macOS bundle exploration

* who needs exploreBundle?

* fix a stupid typo; add debugging tools. It works!
2022-05-23 23:17:32 +08:00
Tungstend 7d55c7f37f Modrinth获取类别列表,搜索时增加类别筛选 (#1501)
* 修复Modrinth源加载列表失败,增加Modrinth源获取前置模组功能

* Revert "修复Modrinth源加载列表失败,增加Modrinth源获取前置模组功能"

This reverts commit 1d29c69d92.

* 修复CF源获取模组版本列表不全

* Modrinth源获取类别列表,搜索时增加类别选项

* Update ModrinthRemoteModRepository.java

* Update ModrinthRemoteModRepository.java
2022-05-23 23:03:33 +08:00
huanghongxun f12882a389 fix(download): should update category list after download soruce changed. 2022-05-23 22:27:30 +08:00
huanghongxun 8cfde9d5c6 feat(download): modrinth moddpack category translations. 2022-05-23 21:57:08 +08:00
huanghongxun 10180a74b6 fix: style. 2022-05-22 15:43:08 +08:00
huanghongxun abd30c397d fix(ui): support reveal file in finder, or just open parent directory in Linux. Closes #1458. 2022-05-22 15:40:47 +08:00
173 changed files with 9096 additions and 4040 deletions

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
[*]
charset = utf-8
end_of_line = crlf
end_of_line = lf
indent_size = 4
indent_style = space
insert_final_newline = false
+5 -5
View File
@@ -1,6 +1,6 @@
name: Bug Feedback
description:
反馈一个 Bug。为了提高反馈效率,请优先在开黑啦或者或 Discord 频道中反馈。若确认是 HMCL 问题,请发布 issue。
反馈一个 Bug。为了提高反馈效率,请优先在 KOOK 或者或 Discord 频道中反馈。若确认是 HMCL 问题,请发布 issue。
body:
- type: markdown
attributes:
@@ -8,16 +8,16 @@ body:
提交前请确保你的启动器版本是**最新的开发版**,可以在启动器设置中更换更新通道至开发版获取更新。
我们发现,对于不经常检查邮箱的人来说,GitHub Issues 的反馈效率太低,时隔几个小时甚至一天的情况很多。
为了改善反馈效率,并将积极为 HMCL 提供问题反馈和建议的人聚集起来,我们希望在这里反馈的人可以在 [开黑啦频道](https://kaihei.co/Kx7n3t)
为了改善反馈效率,并将积极为 HMCL 提供问题反馈和建议的人聚集起来,我们希望在这里反馈的人可以在 [KOOK 频道](https://kook.top/Kx7n3t)
或 [Discord 频道](https://discord.gg/jVvC7HfM6U)中反馈信息,**而不在 GitHub Issues 中反馈问题**。
如果你希望在 QQ 群中反馈问题,请[赞助 HMCL](https://afdian.net/@huanghongxun) 后申请加入群聊,也请将下面的信息表填好直接发在群中,加快我们的沟通速度。
如果你希望在 QQ 群中反馈问题,请[赞助 HMCL](https://hmcl.huangyuhui.net/api/redirect/sponsor) 后申请加入群聊,也请将下面的信息表填好直接发在群中,加快我们的沟通速度。
- type: input
id: hmcl-version
attributes:
label: 启动器版本 Launcher Version
description: 请输入您所使用的的 HMCL 启动器版本。 Please enter the HMCL launcher version you are using.
placeholder: e.g. 3.5.2.218
placeholder: e.g. 3.5.3.211
validations:
required: true
- type: input
@@ -39,7 +39,7 @@ body:
attributes:
label: 游戏版本 Game Version
description: 如果您是在启动通过 HMCL 启动器自动下载的游戏时遇到了问题,请输入您所启动的游戏版本。If you are having trouble launching a game that was automatically downloaded through the HMCL launcher, please enter the version of the game you are launching.
placeholder: e.g. 1.17.1
placeholder: e.g. 1.19
- type: input
id: game-modify
attributes:
+4 -4
View File
@@ -1,8 +1,8 @@
blank_issues_enabled: true
contact_links:
- name: 开黑啦频道
url: https://kaihei.co/Kx7n3t
about: Hello Minecraft! Launcher 的官方开黑啦频道。
- name: KOOK 频道
url: https://kook.top/Kx7n3t
about: Hello Minecraft! Launcher 的官方 KOOK 频道。
- name: Discord 频道
url: https://discord.gg/jVvC7HfM6U
about: Hello Minecraft! Launcher 的官方 Discord 频道。
@@ -11,4 +11,4 @@ contact_links:
about: 前往爱发电赞助 HMCL。赞助后可以申请加入官方 QQ 群反馈问题。
- name: 其他反馈
url: https://github.com/huanghongxun/HMCL/issues/new
about: 通过 Issue 反馈其他问题。
about: 通过 Issue 反馈其他问题。
+5 -1
View File
@@ -39,6 +39,8 @@ jobs:
wget "$DOWNLOAD_BASE_URL/HMCL-$HMCL_VERSION.exe.sha1"
wget "$DOWNLOAD_BASE_URL/HMCL-$HMCL_VERSION.jar"
wget "$DOWNLOAD_BASE_URL/HMCL-$HMCL_VERSION.jar.sha1"
wget "$DOWNLOAD_BASE_URL/HMCL-$HMCL_VERSION.sh"
wget "$DOWNLOAD_BASE_URL/HMCL-$HMCL_VERSION.sh.sha1"
env:
DOWNLOAD_BASE_URL: https://ci.huangyuhui.net/job/HMCL/lastSuccessfulBuild/artifact/HMCL/build/libs
- name: Generate release note
@@ -46,7 +48,7 @@ jobs:
run: |
echo "HMCL v$HMCL_VERSION" >> RELEASE_NOTE
echo "" >> RELEASE_NOTE
echo "The full changelogs can be found on the website: https://hmcl.huangyuhui.net/changelog/dev.html" >> RELEASE_NOTE
echo "The full changelogs can be found on the website: https://docs.hmcl.net/changelog/dev.html" >> RELEASE_NOTE
echo "Notice: changelogs are written in Chinese." >> RELEASE_NOTE
- name: Create release
if: ${{ env.continue == 'true' }}
@@ -58,6 +60,8 @@ jobs:
HMCL-${{ env.HMCL_VERSION }}.exe.sha1
HMCL-${{ env.HMCL_VERSION }}.jar
HMCL-${{ env.HMCL_VERSION }}.jar.sha1
HMCL-${{ env.HMCL_VERSION }}.sh
HMCL-${{ env.HMCL_VERSION }}.sh.sha1
target_commitish: ${{ env.HMCL_COMMIT_SHA }}
name: ${{ env.HMCL_TAG_NAME }}
tag_name: ${{ env.HMCL_TAG_NAME }}
+4
View File
@@ -19,6 +19,10 @@ jobs:
java-package: jdk+fx
- name: Build with Gradle
run: ./gradlew build
env:
MICROSOFT_AUTH_ID: ${{ secrets.MICROSOFT_AUTH_ID }}
MICROSOFT_AUTH_SECRET: ${{ secrets.MICROSOFT_AUTH_SECRET }}
CURSEFORGE_API_KEY: ${{ secrets.CURSEFORGE_API_KEY }}
- name: Get short SHA
run: echo "SHORT_SHA=${GITHUB_SHA::7}" >> $GITHUB_ENV
- name: Upload Artifacts
+4 -2
View File
@@ -47,13 +47,13 @@ val microsoftAuthId = System.getenv("MICROSOFT_AUTH_ID") ?: ""
val microsoftAuthSecret = System.getenv("MICROSOFT_AUTH_SECRET") ?: ""
val curseForgeApiKey = System.getenv("CURSEFORGE_API_KEY") ?: ""
val enableHiPer = System.getenv("ENABLE_HIPER") ?: "false"
version = "$versionRoot.$buildNumber"
dependencies {
implementation(project(":HMCLCore"))
implementation("libs:JFoenix")
implementation("de.javawi.jstun:jstun:0.7.4")
}
fun digest(algorithm: String, bytes: ByteArray) = MessageDigest.getInstance(algorithm).digest(bytes)
@@ -151,6 +151,7 @@ tasks.getByName<com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar>("sha
"Microsoft-Auth-Secret" to microsoftAuthSecret,
"CurseForge-Api-Key" to curseForgeApiKey,
"Build-Channel" to versionType,
"Enable-HiPer" to enableHiPer,
"Class-Path" to "pack200.jar",
"Add-Opens" to listOf(
"java.base/java.lang",
@@ -266,6 +267,7 @@ val makeExecutables = tasks.create("makeExecutables") {
doLast {
createExecutable("exe", "src/main/resources/assets/HMCLauncher.exe")
createExecutable("sh", "src/main/resources/assets/HMCLauncher.sh")
}
}
@@ -19,11 +19,15 @@ package org.jackhuang.hmcl;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.scene.input.Clipboard;
import javafx.scene.input.DataFormat;
import javafx.stage.Stage;
import org.jackhuang.hmcl.setting.ConfigHolder;
import org.jackhuang.hmcl.setting.SambaException;
import org.jackhuang.hmcl.task.Schedulers;
import org.jackhuang.hmcl.task.AsyncTaskExecutor;
import org.jackhuang.hmcl.task.Schedulers;
import org.jackhuang.hmcl.ui.AwtUtils;
import org.jackhuang.hmcl.ui.Controllers;
import org.jackhuang.hmcl.upgrade.UpdateChecker;
@@ -31,14 +35,21 @@ import org.jackhuang.hmcl.upgrade.UpdateHandler;
import org.jackhuang.hmcl.util.CrashReporter;
import org.jackhuang.hmcl.util.Lang;
import org.jackhuang.hmcl.util.StringUtils;
import org.jackhuang.hmcl.util.io.JarUtils;
import org.jackhuang.hmcl.util.platform.Architecture;
import org.jackhuang.hmcl.util.platform.CommandBuilder;
import org.jackhuang.hmcl.util.platform.OperatingSystem;
import java.awt.*;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.net.*;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
@@ -62,7 +73,51 @@ public final class Launcher extends Application {
Main.showWarningAndContinue(i18n("fatal.samba"));
} catch (IOException e) {
LOG.log(Level.SEVERE, "Failed to load config", e);
Main.showErrorAndExit(i18n("fatal.config_loading_failure", Paths.get("").toAbsolutePath().normalize()));
try {
if (OperatingSystem.CURRENT_OS != OperatingSystem.WINDOWS) {
String owner = Files.getOwner(ConfigHolder.configLocation()).getName();
String userName = System.getProperty("user.name");
if (!Files.isWritable(ConfigHolder.configLocation())
&& !userName.equals("root")
&& !userName.equals(owner)) {
ArrayList<String> files = new ArrayList<>();
{
files.add(ConfigHolder.configLocation().toString());
if (Files.exists(Metadata.HMCL_DIRECTORY))
files.add(Metadata.HMCL_DIRECTORY.toString());
Path mcDir = Paths.get(".minecraft").toAbsolutePath().normalize();
if (Files.exists(mcDir))
files.add(mcDir.toString());
}
String command = new CommandBuilder().add("sudo", "chown", "-R", userName).addAll(files).toString();
ButtonType copyAndExit = new ButtonType(i18n("button.copy_and_exit"));
ButtonType res = new Alert(Alert.AlertType.ERROR, i18n("fatal.config_loading_failure.unix", owner, command), copyAndExit, ButtonType.CLOSE)
.showAndWait()
.orElse(null);
if (res == copyAndExit) {
Clipboard.getSystemClipboard()
.setContent(Collections.singletonMap(DataFormat.PLAIN_TEXT, command));
}
System.exit(1);
}
}
} catch (IOException ioe) {
LOG.log(Level.WARNING, "Failed to get file owner", ioe);
}
Main.showErrorAndExit(i18n("fatal.config_loading_failure", Paths.get("").toAbsolutePath().normalize().toString()));
}
if (ConfigHolder.isOwnerChanged()) {
ButtonType res = new Alert(Alert.AlertType.WARNING, i18n("fatal.config_change_owner_root"), ButtonType.YES, ButtonType.NO)
.showAndWait()
.orElse(null);
if (res == ButtonType.NO)
return;
}
if (Metadata.HMCL_DIRECTORY.toAbsolutePath().toString().indexOf('=') >= 0) {
@@ -117,6 +172,7 @@ public final class Launcher extends Application {
LOG.info("Java Home: " + System.getProperty("java.home"));
LOG.info("Current Directory: " + Paths.get("").toAbsolutePath());
LOG.info("HMCL Directory: " + Metadata.HMCL_DIRECTORY);
LOG.info("HMCL Jar Path: " + JarUtils.thisJar().map(it -> it.toAbsolutePath().toString()).orElse("Not Found"));
LOG.info("Memory: " + Runtime.getRuntime().maxMemory() / 1024 / 1024 + "MB");
ManagementFactory.getMemoryPoolMXBeans().stream().filter(bean -> bean.getName().equals("Metaspace")).findAny()
.ifPresent(bean -> LOG.info("Metaspace: " + bean.getUsage().getUsed() / 1024 / 1024 + "MB"));
@@ -17,8 +17,11 @@
*/
package org.jackhuang.hmcl;
import javafx.application.Platform;
import javafx.scene.control.Alert;
import org.jackhuang.hmcl.util.Logging;
import org.jackhuang.hmcl.util.SelfDependencyPatcher;
import org.jackhuang.hmcl.util.platform.Architecture;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
@@ -67,7 +70,6 @@ public final class Main {
checkJavaFX();
Launcher.main(args);
}
@@ -97,7 +99,12 @@ public final class Main {
showErrorAndExit(i18n("fatal.javafx.missing"));
} catch (SelfDependencyPatcher.IncompatibleVersionException e) {
LOG.log(Level.SEVERE, "unable to patch JVM", e);
showErrorAndExit(i18n("fatal.javafx.incompatible"));
if (Architecture.CURRENT_ARCH == Architecture.MIPS64EL
|| Architecture.CURRENT_ARCH == Architecture.LOONGARCH64
|| Architecture.CURRENT_ARCH == Architecture.LOONGARCH64_OW)
showErrorAndExit(i18n("fatal.javafx.incompatible.loongson"));
else
showErrorAndExit(i18n("fatal.javafx.incompatible"));
} catch (CancellationException e) {
LOG.log(Level.SEVERE, "User cancels downloading JavaFX", e);
System.exit(0);
@@ -110,6 +117,15 @@ public final class Main {
static void showErrorAndExit(String message) {
System.err.println(message);
System.err.println("A fatal error has occurred, forcibly exiting.");
try {
if (Platform.isFxApplicationThread()) {
new Alert(Alert.AlertType.ERROR, message).showAndWait();
System.exit(1);
}
} catch (Throwable ignored) {
}
JOptionPane.showMessageDialog(null, message, "Error", JOptionPane.ERROR_MESSAGE);
System.exit(1);
}
@@ -120,6 +136,14 @@ public final class Main {
static void showWarningAndContinue(String message) {
System.err.println(message);
System.err.println("Potential issues have been detected.");
try {
if (Platform.isFxApplicationThread()) {
new Alert(Alert.AlertType.WARNING, message).showAndWait();
return;
}
} catch (Throwable ignored) {
}
JOptionPane.showMessageDialog(null, message, "Warning", JOptionPane.WARNING_MESSAGE);
}
@@ -150,7 +174,8 @@ public final class Main {
tls.init(null, instance.getTrustManagers(), null);
HttpsURLConnection.setDefaultSSLSocketFactory(tls.getSocketFactory());
LOG.info("Added Lets Encrypt root certificates as additional trust");
} catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException | KeyManagementException e) {
} catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException |
KeyManagementException e) {
LOG.log(Level.SEVERE, "Failed to load lets encrypt certificate. Expect problems", e);
}
}
@@ -18,11 +18,9 @@
package org.jackhuang.hmcl;
import org.jackhuang.hmcl.util.io.JarUtils;
import org.jackhuang.hmcl.util.StringUtils;
import org.jackhuang.hmcl.util.platform.OperatingSystem;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* Stores metadata about this application.
@@ -32,7 +30,7 @@ public final class Metadata {
public static final String NAME = "HMCL";
public static final String FULL_NAME = "Hello Minecraft! Launcher";
public static final String VERSION = System.getProperty("hmcl.version.override", JarUtils.thisJar().flatMap(JarUtils::getImplementationVersion).orElse("@develop@"));
public static final String VERSION = System.getProperty("hmcl.version.override", JarUtils.getManifestAttribute("Implementation-Version", "@develop@"));
public static final String TITLE = NAME + " " + VERSION;
public static final String FULL_TITLE = FULL_NAME + " v" + VERSION;
@@ -40,27 +38,14 @@ public final class Metadata {
public static final String UPDATE_URL = System.getProperty("hmcl.update_source.override", "https://hmcl.huangyuhui.net/api/update_link");
public static final String CONTACT_URL = "https://github.com/huanghongxun/HMCL/issues";
public static final String HELP_URL = "https://hmcl.huangyuhui.net/help";
public static final String CHANGELOG_URL = "https://hmcl.huangyuhui.net/changelog/";
public static final String PUBLISH_URL = "http://www.mcbbs.net/thread-142335-1-1.html";
public static final String CHANGELOG_URL = "https://docs.hmcl.net/changelog/";
public static final String PUBLISH_URL = "https://www.mcbbs.net/thread-142335-1-1.html";
public static final String EULA_URL = "https://hmcl.huangyuhui.net/eula";
public static final String BUILD_CHANNEL = JarUtils.thisJar().flatMap(JarUtils::getManifest).map(manifest -> manifest.getMainAttributes().getValue("Build-Channel")).orElse("nightly");
public static final String BUILD_CHANNEL = JarUtils.getManifestAttribute("Build-Channel", "nightly");
public static final Path MINECRAFT_DIRECTORY = OperatingSystem.getWorkingDirectory("minecraft");
public static final Path HMCL_DIRECTORY = getHMCLDirectory();
private static Path getHMCLDirectory() {
String home = System.getProperty("user.home", ".");
if (OperatingSystem.CURRENT_OS == OperatingSystem.LINUX) {
// to fulfill XDG standard.
String xdgCache = System.getenv("XDG_CACHE_HOME");
if (StringUtils.isNotBlank(xdgCache)) {
return Paths.get(xdgCache, "hmcl");
}
return Paths.get(home, ".cache", "hmcl");
}
return OperatingSystem.getWorkingDirectory("hmcl");
}
public static final Path HMCL_DIRECTORY = OperatingSystem.getWorkingDirectory("hmcl");
public static boolean isStable() {
return "stable".equals(BUILD_CHANNEL);
@@ -59,8 +59,13 @@ public final class HMCLGameLauncher extends DefaultLauncher {
private void generateOptionsTxt() {
File optionsFile = new File(repository.getRunDirectory(version.getId()), "options.txt");
File configFolder = new File(repository.getRunDirectory(version.getId()), "config");
if (optionsFile.exists())
return;
if (configFolder.isDirectory())
if (findFiles(configFolder, "options.txt"))
return;
try {
// TODO: Dirty implementation here
if (I18n.getCurrentLocale().getLocale() == Locale.CHINA)
@@ -70,6 +75,20 @@ public final class HMCLGameLauncher extends DefaultLauncher {
}
}
private boolean findFiles(File folder, String fileName) {
File[] fs = folder.listFiles();
if (fs != null) {
for (File f : fs) {
if (f.isDirectory())
if (f.listFiles((dir, name) -> name.equals(fileName)) != null)
return true;
if (f.getName().equals(fileName))
return true;
}
}
return false;
}
@Override
public ManagedProcess launch() throws IOException, InterruptedException {
generateOptionsTxt();
@@ -355,6 +355,7 @@ public class HMCLGameRepository extends DefaultGameRepository {
.setNativesDirType(vs.getNativesDirType())
.setNativesDir(vs.getNativesDir())
.setProcessPriority(vs.getProcessPriority())
.setUseSoftwareRenderer(vs.isUseSoftwareRenderer())
.setUseNativeGLFW(vs.isUseNativeGLFW())
.setUseNativeOpenAL(vs.isUseNativeOpenAL())
.setDaemon(!makeLaunchScript && vs.getLauncherVisibility().isDaemon())
@@ -17,6 +17,7 @@
*/
package org.jackhuang.hmcl.game;
import com.jfoenix.controls.JFXButton;
import javafx.application.Platform;
import javafx.stage.Stage;
import org.jackhuang.hmcl.Launcher;
@@ -26,18 +27,13 @@ import org.jackhuang.hmcl.auth.authlibinjector.AuthlibInjectorDownloadException;
import org.jackhuang.hmcl.download.DefaultDependencyManager;
import org.jackhuang.hmcl.download.DownloadProvider;
import org.jackhuang.hmcl.download.MaintainTask;
import org.jackhuang.hmcl.download.game.GameAssetIndexDownloadTask;
import org.jackhuang.hmcl.download.game.GameVerificationFixTask;
import org.jackhuang.hmcl.download.game.LibraryDownloadException;
import org.jackhuang.hmcl.download.game.*;
import org.jackhuang.hmcl.download.java.JavaRepository;
import org.jackhuang.hmcl.launch.*;
import org.jackhuang.hmcl.mod.ModpackCompletionException;
import org.jackhuang.hmcl.mod.ModpackConfiguration;
import org.jackhuang.hmcl.mod.ModpackProvider;
import org.jackhuang.hmcl.setting.DownloadProviders;
import org.jackhuang.hmcl.setting.LauncherVisibility;
import org.jackhuang.hmcl.setting.Profile;
import org.jackhuang.hmcl.setting.VersionSetting;
import org.jackhuang.hmcl.setting.*;
import org.jackhuang.hmcl.task.*;
import org.jackhuang.hmcl.ui.*;
import org.jackhuang.hmcl.ui.construct.*;
@@ -67,6 +63,7 @@ import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Level;
import static org.jackhuang.hmcl.setting.ConfigHolder.config;
import static org.jackhuang.hmcl.ui.FXUtils.runInFX;
import static org.jackhuang.hmcl.util.Lang.resolveException;
import static org.jackhuang.hmcl.util.Logging.LOG;
import static org.jackhuang.hmcl.util.Pair.pair;
@@ -75,7 +72,7 @@ import static org.jackhuang.hmcl.util.i18n.I18n.i18n;
public final class LauncherHelper {
private final Profile profile;
private final Account account;
private Account account;
private final String selectedVersion;
private File scriptFile;
private final VersionSetting setting;
@@ -94,6 +91,14 @@ public final class LauncherHelper {
private final TaskExecutorDialogPane launchingStepsPane = new TaskExecutorDialogPane(TaskCancellationAction.NORMAL);
public Account getAccount() {
return account;
}
public void setAccount(Account account) {
this.account = account;
}
public void setTestMode() {
launcherVisibility = LauncherVisibility.KEEP;
showLogs = true;
@@ -121,31 +126,25 @@ public final class LauncherHelper {
private void launch0() {
HMCLGameRepository repository = profile.getRepository();
DefaultDependencyManager dependencyManager = profile.getDependency();
Version version = MaintainTask.maintain(repository, repository.getResolvedVersion(selectedVersion));
Optional<String> gameVersion = repository.getGameVersion(version);
AtomicReference<Version> version = new AtomicReference<>(MaintainTask.maintain(repository, repository.getResolvedVersion(selectedVersion)));
Optional<String> gameVersion = repository.getGameVersion(version.get());
boolean integrityCheck = repository.unmarkVersionLaunchedAbnormally(selectedVersion);
CountDownLatch launchingLatch = new CountDownLatch(1);
List<String> javaAgents = new ArrayList<>(0);
AtomicReference<JavaVersion> javaVersionRef = new AtomicReference<>();
getLog4jPatch(version).ifPresent(javaAgents::add);
getLog4jPatch(version.get()).ifPresent(javaAgents::add);
TaskExecutor executor = checkGameState(profile, setting, version)
TaskExecutor executor = checkGameState(profile, setting, version.get())
.thenComposeAsync(javaVersion -> {
javaVersionRef.set(Objects.requireNonNull(javaVersion));
return dependencyManager.checkPatchCompletionAsync(repository.getVersion(selectedVersion), integrityCheck);
})
.thenComposeAsync(Task.allOf(
Task.composeAsync(() -> {
if (setting.isNotCheckGame())
return null;
else
return dependencyManager.checkGameCompletionAsync(version, integrityCheck);
}), Task.composeAsync(() -> {
if (setting.isNotCheckGame()) {
return null;
} else {
version.set(NativePatcher.patchNative(version.get(), gameVersion.orElse(null), javaVersion, setting));
if (setting.isNotCheckGame())
return null;
return Task.allOf(
dependencyManager.checkGameCompletionAsync(version.get(), integrityCheck),
Task.composeAsync(() -> {
try {
ModpackConfiguration<?> configuration = ModpackHelper.readModpackConfiguration(repository.getModpackConfiguration(selectedVersion));
ModpackProvider provider = ModpackHelper.getProviderByType(configuration.getType());
@@ -154,32 +153,45 @@ public final class LauncherHelper {
} catch (IOException e) {
return null;
}
}
}))).withStage("launch.state.dependencies")
}),
Task.composeAsync(() -> {
if (setting.isUseSoftwareRenderer() && OperatingSystem.CURRENT_OS == OperatingSystem.WINDOWS) {
Library lib = NativePatcher.getSoftwareRendererLoader(javaVersion);
if (lib == null)
return null;
File file = dependencyManager.getGameRepository().getLibraryFile(version.get(), lib);
if (file.getAbsolutePath().indexOf('=') >= 0) {
LOG.warning("Invalid character '=' in the libraries directory path, unable to attach software renderer loader");
return null;
}
if (GameLibrariesTask.shouldDownloadLibrary(repository, version.get(), lib, integrityCheck)) {
return new LibraryDownloadTask(dependencyManager, file, lib)
.thenRunAsync(() -> javaAgents.add(file.getAbsolutePath()));
} else {
javaAgents.add(file.getAbsolutePath());
return null;
}
} else {
return null;
}
})
);
}).withStage("launch.state.dependencies")
.thenComposeAsync(() -> {
return gameVersion.map(s -> new GameVerificationFixTask(dependencyManager, s, version)).orElse(null);
return gameVersion.map(s -> new GameVerificationFixTask(dependencyManager, s, version.get())).orElse(null);
})
.thenComposeAsync(Task.supplyAsync(() -> {
try {
return account.logIn();
} catch (CredentialExpiredException e) {
LOG.info("Credential has expired: " + e);
return DialogController.logIn(account);
} catch (AuthenticationException e) {
LOG.warning("Authentication failed, try playing offline: " + e);
return account.playOffline().orElseThrow(() -> e);
}
}).withStage("launch.state.logging_in"))
.thenComposeAsync(() -> logIn(account).withStage("launch.state.logging_in"))
.thenComposeAsync(authInfo -> Task.supplyAsync(() -> {
LaunchOptions launchOptions = repository.getLaunchOptions(selectedVersion, javaVersionRef.get(), profile.getGameDir(), javaAgents, scriptFile != null);
return new HMCLGameLauncher(
repository,
version,
version.get(),
authInfo,
launchOptions,
launcherVisibility == LauncherVisibility.CLOSE
? null // Unnecessary to start listening to game process output when close launcher immediately after game launched.
: new HMCLProcessListener(repository, version, authInfo, launchOptions, launchingLatch, gameVersion.isPresent())
: new HMCLProcessListener(repository, version.get(), authInfo, launchOptions, launchingLatch, gameVersion.isPresent())
);
}).thenComposeAsync(launcher -> { // launcher is prev task's result
if (scriptFile == null) {
@@ -335,40 +347,48 @@ public final class LauncherHelper {
Runnable continueAction = () -> future.complete(JavaVersion.fromCurrentEnvironment());
if (setting.isJavaAutoSelected()) {
JavaVersionConstraint.VersionRanges range = JavaVersionConstraint.findSuitableJavaVersionRange(gameVersion, version);
GameJavaVersion targetJavaVersion;
GameJavaVersion targetJavaVersion = null;
if (range.getMandatory().contains(VersionNumber.asVersion("17.0.1"))) {
targetJavaVersion = GameJavaVersion.JAVA_17;
} else if (range.getMandatory().contains(VersionNumber.asVersion("16.0.1"))) {
targetJavaVersion = GameJavaVersion.JAVA_16;
} else {
String java8Version;
if (OperatingSystem.CURRENT_OS == OperatingSystem.WINDOWS) {
java8Version = "1.8.0_51";
} else if (OperatingSystem.CURRENT_OS == OperatingSystem.LINUX) {
java8Version = "1.8.0_202";
} else if (OperatingSystem.CURRENT_OS == OperatingSystem.OSX) {
java8Version = "1.8.0_74";
if (org.jackhuang.hmcl.util.platform.Platform.isCompatibleWithX86Java()) {
JavaVersionConstraint.VersionRanges range = JavaVersionConstraint.findSuitableJavaVersionRange(gameVersion, version);
if (range.getMandatory().contains(VersionNumber.asVersion("17.0.1"))) {
targetJavaVersion = GameJavaVersion.JAVA_17;
} else if (range.getMandatory().contains(VersionNumber.asVersion("16.0.1"))) {
targetJavaVersion = GameJavaVersion.JAVA_16;
} else {
java8Version = null;
}
String java8Version;
if (java8Version != null && range.getMandatory().contains(VersionNumber.asVersion(java8Version)))
targetJavaVersion = GameJavaVersion.JAVA_8;
else
targetJavaVersion = null;
if (OperatingSystem.CURRENT_OS == OperatingSystem.WINDOWS) {
java8Version = "1.8.0_51";
} else if (OperatingSystem.CURRENT_OS == OperatingSystem.LINUX) {
java8Version = "1.8.0_202";
} else if (OperatingSystem.CURRENT_OS == OperatingSystem.OSX) {
java8Version = "1.8.0_74";
} else {
java8Version = null;
}
if (java8Version != null && range.getMandatory().contains(VersionNumber.asVersion(java8Version)))
targetJavaVersion = GameJavaVersion.JAVA_8;
else
targetJavaVersion = null;
}
}
if (targetJavaVersion != null) {
if (targetJavaVersion == null) {
Controllers.confirm(i18n("launch.failed.no_accepted_java"), i18n("message.warning"), MessageType.WARNING, continueAction, () -> {
future.completeExceptionally(new CancellationException("No accepted java"));
});
} else {
downloadJava(gameVersion.toString(), targetJavaVersion, profile)
.thenAcceptAsync(downloadedJavaVersion -> {
future.complete(downloadedJavaVersion);
})
.exceptionally(throwable -> {
LOG.log(Level.WARNING, "Failed to download java", throwable);
Controllers.dialog(i18n("launch.failed.no_accepted_java"), i18n("message.warning"), MessageType.WARNING, continueAction);
Controllers.confirm(i18n("launch.failed.no_accepted_java"), i18n("message.warning"), MessageType.WARNING, continueAction, () -> {
future.completeExceptionally(new CancellationException("No accepted java"));
});
return null;
});
}
@@ -437,40 +457,25 @@ public final class LauncherHelper {
Controllers.confirm(i18n("launch.advice.require_newer_java_version", gameVersion.toString(), 16), i18n("message.warning"), () -> {
FXUtils.openLink(OPENJDK_DOWNLOAD_LINK);
}, breakAction);
return null;
return Task.fromCompletableFuture(future);
case VANILLA_JAVA_17:
Controllers.confirm(i18n("launch.advice.require_newer_java_version", gameVersion.toString(), 17), i18n("message.warning"), () -> {
FXUtils.openLink(OPENJDK_DOWNLOAD_LINK);
}, breakAction);
return null;
return Task.fromCompletableFuture(future);
case VANILLA_JAVA_8:
Controllers.dialog(i18n("launch.advice.java8_1_13"), i18n("message.error"), MessageType.ERROR, breakAction);
return null;
return Task.fromCompletableFuture(future);
case VANILLA_LINUX_JAVA_8:
if (setting.getNativesDirType() == NativesDirectoryType.VERSION_FOLDER) {
Controllers.dialog(i18n("launch.advice.vanilla_linux_java_8"), i18n("message.error"), MessageType.ERROR, breakAction);
return null;
} else {
break;
}
case VANILLA_X86:
if (setting.getNativesDirType() == NativesDirectoryType.VERSION_FOLDER) {
if (Architecture.SYSTEM_ARCH == Architecture.ARM64) {
if (OperatingSystem.CURRENT_OS == OperatingSystem.OSX
// Windows on ARM introduced translation support for x86-64 after 10.0.21277.
|| (OperatingSystem.CURRENT_OS == OperatingSystem.WINDOWS && OperatingSystem.SYSTEM_BUILD_NUMBER >= 21277)) {
Controllers.dialog(i18n("launch.advice.vanilla_x86.translation"), i18n("message.error"), MessageType.ERROR, breakAction);
return null;
}
}
Controllers.dialog(i18n("launch.advice.vanilla_x86"), i18n("message.error"), MessageType.ERROR, breakAction);
return null;
return Task.fromCompletableFuture(future);
} else {
break;
}
case LAUNCH_WRAPPER:
Controllers.dialog(i18n("launch.advice.java9") + "\n" + i18n("launch.advice.uncorrected"), i18n("message.error"), MessageType.ERROR, breakAction);
return null;
return Task.fromCompletableFuture(future);
}
}
}
@@ -495,7 +500,7 @@ public final class LauncherHelper {
switch (violatedSuggestedConstraint) {
case MODDED_JAVA_7:
Controllers.dialog(i18n("launch.advice.java.modded_java_7"), i18n("message.warning"), MessageType.WARNING, continueAction);
return null;
break;
case MODDED_JAVA_8:
Controllers.dialog(i18n("launch.advice.newer_java"), i18n("message.warning"), MessageType.WARNING, continueAction);
break;
@@ -508,6 +513,14 @@ public final class LauncherHelper {
case MODLAUNCHER_8:
Controllers.dialog(i18n("launch.advice.modlauncher8"), i18n("message.warning"), MessageType.WARNING, continueAction);
break;
case VANILLA_X86:
if (setting.getNativesDirType() == NativesDirectoryType.VERSION_FOLDER
&& org.jackhuang.hmcl.util.platform.Platform.isCompatibleWithX86Java()) {
Controllers.dialog(i18n("launch.advice.vanilla_x86.translation"), i18n("message.warning"), MessageType.WARNING, continueAction);
} else {
continueAction.run();
}
break;
}
}
@@ -555,7 +568,11 @@ public final class LauncherHelper {
JFXHyperlink link = new JFXHyperlink(i18n("download.external_link"));
link.setOnAction(e -> {
FXUtils.openLink(OPENJDK_DOWNLOAD_LINK);
if (javaVersion.getMajorVersion() == JavaVersion.JAVA_8) {
FXUtils.openLink(ORACLEJDK_DOWNLOAD_LINK);
} else {
FXUtils.openLink(OPENJDK_DOWNLOAD_LINK);
}
future.completeExceptionally(new CancellationException());
});
@@ -597,25 +614,55 @@ public final class LauncherHelper {
private static CompletableFuture<JavaVersion> downloadJavaImpl(GameJavaVersion javaVersion, DownloadProvider downloadProvider) {
CompletableFuture<JavaVersion> future = new CompletableFuture<>();
TaskExecutorDialogPane javaDownloadingPane = new TaskExecutorDialogPane(TaskCancellationAction.NORMAL);
TaskExecutor executor = JavaRepository.downloadJava(javaVersion, downloadProvider)
Controllers.taskDialog(JavaRepository.downloadJava(javaVersion, downloadProvider)
.whenComplete(Schedulers.javafx(), (downloadedJava, exception) -> {
if (exception != null) {
future.completeExceptionally(exception);
} else {
future.complete(downloadedJava);
}
})
.executor(false);
javaDownloadingPane.setExecutor(executor, true);
Controllers.dialog(javaDownloadingPane);
executor.start();
}), i18n("download.java"), TaskCancellationAction.NORMAL);
return future;
}
private static Task<AuthInfo> logIn(Account account) {
return Task.composeAsync(() -> {
try {
return Task.completed(account.logIn());
} catch (CredentialExpiredException e) {
LOG.log(Level.INFO, "Credential has expired", e);
return Task.completed(DialogController.logIn(account));
} catch (AuthenticationException e) {
LOG.log(Level.WARNING, "Authentication failed, try skipping refresh", e);
CompletableFuture<Task<AuthInfo>> future = new CompletableFuture<>();
runInFX(() -> {
JFXButton loginOfflineButton = new JFXButton(i18n("account.login.skip"));
loginOfflineButton.setOnAction(event -> {
try {
future.complete(Task.completed(account.playOffline()));
} catch (AuthenticationException e2) {
future.completeExceptionally(e2);
}
});
JFXButton retryButton = new JFXButton(i18n("account.login.retry"));
retryButton.setOnAction(event -> {
future.complete(logIn(account));
});
Controllers.dialog(new MessageDialogPane.Builder(i18n("account.failed.server_disconnected"), i18n("account.failed"), MessageType.ERROR)
.addAction(loginOfflineButton)
.addAction(retryButton)
.addCancel(() ->
future.completeExceptionally(new CancellationException()))
.build());
});
return Task.fromCompletableFuture(future).thenComposeAsync(task -> task);
}
});
}
private static Optional<String> getLog4jPatch(Version version) {
Optional<String> log4jVersion = version.getLibraries().stream()
.filter(it -> it.is("org.apache.logging.log4j", "log4j-core")
@@ -813,7 +860,8 @@ public final class LauncherHelper {
}
private static final String OPENJDK_DOWNLOAD_LINK = "https://docs.microsoft.com/zh-cn/java/openjdk/download";
private static final String ORACLEJDK_DOWNLOAD_LINK = "https://www.java.com/download";
private static final String OPENJDK_DOWNLOAD_LINK = "https://docs.microsoft.com/java/openjdk/download";
public static final Queue<ManagedProcess> PROCESSES = new ConcurrentLinkedQueue<>();
@@ -160,13 +160,13 @@ public final class OAuthServer extends NanoHTTPD implements OAuth.Session {
@Override
public String getClientId() {
return System.getProperty("hmcl.microsoft.auth.id",
JarUtils.thisJar().flatMap(JarUtils::getManifest).map(manifest -> manifest.getMainAttributes().getValue("Microsoft-Auth-Id")).orElse(""));
JarUtils.getManifestAttribute("Microsoft-Auth-Id", ""));
}
@Override
public String getClientSecret() {
return System.getProperty("hmcl.microsoft.auth.secret",
JarUtils.thisJar().flatMap(JarUtils::getManifest).map(manifest -> manifest.getMainAttributes().getValue("Microsoft-Auth-Secret")).orElse(""));
JarUtils.getManifestAttribute("Microsoft-Auth-Secret", ""));
}
@Override
@@ -136,8 +136,8 @@ public final class TexturesLoader {
private final static Map<TextureModel, LoadedTexture> DEFAULT_SKINS = new EnumMap<>(TextureModel.class);
static {
loadDefaultSkin("/assets/img/steve.png", TextureModel.STEVE);
loadDefaultSkin("/assets/img/alex.png", TextureModel.ALEX);
loadDefaultSkin("/assets/img/skin/steve.png", TextureModel.STEVE);
loadDefaultSkin("/assets/img/skin/alex.png", TextureModel.ALEX);
}
private static void loadDefaultSkin(String path, TextureModel model) {
@@ -81,6 +81,7 @@ public final class Accounts {
public static final YggdrasilAccountFactory FACTORY_MOJANG = YggdrasilAccountFactory.MOJANG;
public static final AuthlibInjectorAccountFactory FACTORY_AUTHLIB_INJECTOR = new AuthlibInjectorAccountFactory(AUTHLIB_INJECTOR_DOWNLOADER, Accounts::getOrCreateAuthlibInjectorServer);
public static final MicrosoftAccountFactory FACTORY_MICROSOFT = new MicrosoftAccountFactory(new MicrosoftService(OAUTH_CALLBACK));
public static final BoundAuthlibInjectorAccountFactory FACTORY_LITTLE_SKIN = getAccountFactoryByAuthlibInjectorServer(new AuthlibInjectorServer("https://littleskin.cn/api/yggdrasil/"));
public static final List<AccountFactory<?>> FACTORIES = immutableListOf(FACTORY_OFFLINE, FACTORY_MOJANG, FACTORY_MICROSOFT, FACTORY_AUTHLIB_INJECTOR);
// ==== login type / account factory mapping ====
@@ -96,14 +97,24 @@ public final class Accounts {
}
public static String getLoginType(AccountFactory<?> factory) {
return Optional.ofNullable(factory2type.get(factory))
.orElseThrow(() -> new IllegalArgumentException("Unrecognized account factory"));
String type = factory2type.get(factory);
if (type != null) return type;
if (factory instanceof BoundAuthlibInjectorAccountFactory) {
return factory2type.get(FACTORY_AUTHLIB_INJECTOR);
}
throw new IllegalArgumentException("Unrecognized account factory");
}
public static AccountFactory<?> getAccountFactory(String loginType) {
return Optional.ofNullable(type2factory.get(loginType))
.orElseThrow(() -> new IllegalArgumentException("Unrecognized login type"));
}
public static BoundAuthlibInjectorAccountFactory getAccountFactoryByAuthlibInjectorServer(AuthlibInjectorServer server) {
return new BoundAuthlibInjectorAccountFactory(AUTHLIB_INJECTOR_DOWNLOADER, server);
}
// ====
public static AccountFactory<?> getAccountFactory(Account account) {
@@ -119,10 +130,10 @@ public final class Accounts {
throw new IllegalArgumentException("Failed to determine account type: " + account);
}
private static ObservableList<Account> accounts = observableArrayList(account -> new Observable[] { account });
private static ReadOnlyListWrapper<Account> accountsWrapper = new ReadOnlyListWrapper<>(Accounts.class, "accounts", accounts);
private static final ObservableList<Account> accounts = observableArrayList(account -> new Observable[] { account });
private static final ReadOnlyListWrapper<Account> accountsWrapper = new ReadOnlyListWrapper<>(Accounts.class, "accounts", accounts);
private static ObjectProperty<Account> selectedAccount = new SimpleObjectProperty<Account>(Accounts.class, "selectedAccount") {
private static final ObjectProperty<Account> selectedAccount = new SimpleObjectProperty<Account>(Accounts.class, "selectedAccount") {
{
accounts.addListener(onInvalidating(this::invalidated));
}
@@ -231,6 +242,14 @@ public final class Accounts {
triggerAuthlibInjectorUpdateCheck();
}
Schedulers.io().execute(() -> {
try {
FACTORY_LITTLE_SKIN.getServer().fetchMetadataResponse();
} catch (IOException e) {
LOG.log(Level.WARNING, "Failed to fetch authlib-injector server metdata: " + FACTORY_LITTLE_SKIN.getServer(), e);
}
});
for (AuthlibInjectorServer server : config().getAuthlibInjectorServers()) {
if (selected instanceof AuthlibInjectorAccount && ((AuthlibInjectorAccount) selected).getServer() == server)
continue;
@@ -313,7 +332,7 @@ public final class Accounts {
// ====
// ==== Login type name i18n ===
private static Map<AccountFactory<?>, String> unlocalizedLoginTypeNames = mapOf(
private static final Map<AccountFactory<?>, String> unlocalizedLoginTypeNames = mapOf(
pair(Accounts.FACTORY_OFFLINE, "account.methods.offline"),
pair(Accounts.FACTORY_MOJANG, "account.methods.yggdrasil"),
pair(Accounts.FACTORY_AUTHLIB_INJECTOR, "account.methods.authlib_injector"),
@@ -22,6 +22,7 @@ import com.google.gson.JsonParseException;
import org.jackhuang.hmcl.Metadata;
import org.jackhuang.hmcl.util.InvocationDispatcher;
import org.jackhuang.hmcl.util.Lang;
import org.jackhuang.hmcl.util.StringUtils;
import org.jackhuang.hmcl.util.io.FileUtils;
import org.jackhuang.hmcl.util.platform.OperatingSystem;
@@ -45,6 +46,7 @@ public final class ConfigHolder {
private static Config configInstance;
private static GlobalConfig globalConfigInstance;
private static boolean newlyCreated;
private static boolean ownerChanged = false;
public static Config config() {
if (configInstance == null) {
@@ -60,10 +62,18 @@ public final class ConfigHolder {
return globalConfigInstance;
}
public static Path configLocation() {
return configLocation;
}
public static boolean isNewlyCreated() {
return newlyCreated;
}
public static boolean isOwnerChanged() {
return ownerChanged;
}
public synchronized static void init() throws IOException {
if (configInstance != null) {
throw new IllegalStateException("Configuration is already loaded");
@@ -109,7 +119,7 @@ public final class ConfigHolder {
}
private static Path locateConfig() {
Path exePath = Paths.get("");
Path exePath = Paths.get("").toAbsolutePath();
try {
Path jarPath = Paths.get(ConfigHolder.class.getProtectionDomain().getCodeSource().getLocation()
.toURI()).toAbsolutePath();
@@ -143,6 +153,15 @@ public final class ConfigHolder {
private static Config loadConfig() throws IOException {
if (Files.exists(configLocation)) {
try {
if (OperatingSystem.CURRENT_OS != OperatingSystem.WINDOWS
&& "root".equals(System.getProperty("user.name"))
&& !"root".equals(Files.getOwner(configLocation).getName())) {
ownerChanged = true;
}
} catch (IOException e1) {
LOG.log(Level.WARNING, "Failed to get owner");
}
try {
String content = FileUtils.readText(configLocation);
Config deserialized = Config.fromJson(content);
@@ -189,6 +208,28 @@ public final class ConfigHolder {
// Global Config
private static GlobalConfig loadGlobalConfig() throws IOException {
// Migrate from old directory
if (OperatingSystem.CURRENT_OS == OperatingSystem.LINUX && Files.notExists(GLOBAL_CONFIG_PATH)) {
Path oldHome;
String xdgCache = System.getenv("XDG_CACHE_HOME");
if (StringUtils.isNotBlank(xdgCache)) {
oldHome = Paths.get(xdgCache, "hmcl");
} else {
oldHome = Paths.get(System.getProperty("user.home", "."), ".cache", "hmcl");
}
if (Files.exists(oldHome)) {
Path oldConfigPath = oldHome.resolve("config.json");
if (Files.isRegularFile(oldConfigPath)) {
try {
Files.copy(oldConfigPath, GLOBAL_CONFIG_PATH);
} catch (IOException e) {
LOG.log(Level.WARNING, "Failed to migrate global config", e);
}
}
}
}
if (Files.exists(GLOBAL_CONFIG_PATH)) {
try {
String content = FileUtils.readText(GLOBAL_CONFIG_PATH);
@@ -68,6 +68,8 @@ public class GlobalConfig implements Cloneable, Observable {
private IntegerProperty agreementVersion = new SimpleIntegerProperty();
private IntegerProperty platformPromptVersion = new SimpleIntegerProperty();
private StringProperty multiplayerToken = new SimpleStringProperty();
private BooleanProperty multiplayerRelay = new SimpleBooleanProperty();
@@ -113,6 +115,18 @@ public class GlobalConfig implements Cloneable, Observable {
this.agreementVersion.set(agreementVersion);
}
public int getPlatformPromptVersion() {
return platformPromptVersion.get();
}
public IntegerProperty platformPromptVersionProperty() {
return platformPromptVersion;
}
public void setPlatformPromptVersion(int platformPromptVersion) {
this.platformPromptVersion.set(platformPromptVersion);
}
public boolean isMultiplayerRelay() {
return multiplayerRelay.get();
}
@@ -152,7 +166,9 @@ public class GlobalConfig implements Cloneable, Observable {
public static class Serializer implements JsonSerializer<GlobalConfig>, JsonDeserializer<GlobalConfig> {
private static final Set<String> knownFields = new HashSet<>(Arrays.asList(
"agreementVersion",
"platformPromptVersion",
"multiplayerToken",
"multiplayerRelay",
"multiplayerAgreementVersion"
));
@@ -164,6 +180,7 @@ public class GlobalConfig implements Cloneable, Observable {
JsonObject jsonObject = new JsonObject();
jsonObject.add("agreementVersion", context.serialize(src.getAgreementVersion()));
jsonObject.add("platformPromptVersion", context.serialize(src.getPlatformPromptVersion()));
jsonObject.add("multiplayerToken", context.serialize(src.getMultiplayerToken()));
jsonObject.add("multiplayerRelay", context.serialize(src.isMultiplayerRelay()));
jsonObject.add("multiplayerAgreementVersion", context.serialize(src.getMultiplayerAgreementVersion()));
@@ -182,6 +199,7 @@ public class GlobalConfig implements Cloneable, Observable {
GlobalConfig config = new GlobalConfig();
config.setAgreementVersion(Optional.ofNullable(obj.get("agreementVersion")).map(JsonElement::getAsInt).orElse(0));
config.setPlatformPromptVersion(Optional.ofNullable(obj.get("platformPromptVersion")).map(JsonElement::getAsInt).orElse(0));
config.setMultiplayerToken(Optional.ofNullable(obj.get("multiplayerToken")).map(JsonElement::getAsString).orElse(null));
config.setMultiplayerRelay(Optional.ofNullable(obj.get("multiplayerRelay")).map(JsonElement::getAsBoolean).orElse(false));
config.setMultiplayerAgreementVersion(Optional.ofNullable(obj.get("multiplayerAgreementVersion")).map(JsonElement::getAsInt).orElse(0));
@@ -392,6 +392,20 @@ public final class VersionSetting implements Cloneable {
notCheckGameProperty.set(notCheckGame);
}
private final BooleanProperty notPatchNativesProperty = new SimpleBooleanProperty(this, "notPatchNatives", false);
public BooleanProperty notPatchNativesProperty() {
return notPatchNativesProperty;
}
public boolean isNotPatchNatives() {
return notPatchNativesProperty.get();
}
public void setNotPatchNatives(boolean notPatchNatives) {
notPatchNativesProperty.set(notPatchNatives);
}
private final BooleanProperty showLogsProperty = new SimpleBooleanProperty(this, "showLogs", false);
public BooleanProperty showLogsProperty() {
@@ -540,6 +554,20 @@ public final class VersionSetting implements Cloneable {
processPriorityProperty.set(processPriority);
}
private final BooleanProperty useSoftwareRenderer = new SimpleBooleanProperty(this, "softwareRenderer", false);
public boolean isUseSoftwareRenderer() {
return useSoftwareRenderer.get();
}
public BooleanProperty useSoftwareRendererProperty() {
return useSoftwareRenderer;
}
public void setUseSoftwareRenderer(boolean useSoftwareRenderer) {
this.useSoftwareRenderer.set(useSoftwareRenderer);
}
private final BooleanProperty useNativeGLFW = new SimpleBooleanProperty(this, "nativeGLFW", false);
public boolean isUseNativeGLFW() {
@@ -610,7 +638,7 @@ public final class VersionSetting implements Cloneable {
public Task<JavaVersion> getJavaVersion(VersionNumber gameVersion, Version version, boolean checkJava) {
return Task.runAsync(Schedulers.javafx(), () -> {
if (StringUtils.isBlank(getJava())) {
setJava(StringUtils.isBlank(getJavaDir()) ? "Default" : "Custom");
setJava(StringUtils.isBlank(getJavaDir()) ? "Auto" : "Custom");
}
}).thenSupplyAsync(() -> {
try {
@@ -633,7 +661,7 @@ public final class VersionSetting implements Cloneable {
.collect(Collectors.toList());
if (matchedJava.isEmpty()) {
runInFX(() -> {
setJava("Default");
setJava("Auto");
});
return JavaVersion.fromCurrentEnvironment();
} else {
@@ -670,6 +698,7 @@ public final class VersionSetting implements Cloneable {
noJVMArgsProperty.addListener(listener);
notCheckGameProperty.addListener(listener);
notCheckJVMProperty.addListener(listener);
notPatchNativesProperty.addListener(listener);
showLogsProperty.addListener(listener);
serverIpProperty.addListener(listener);
fullscreenProperty.addListener(listener);
@@ -678,6 +707,7 @@ public final class VersionSetting implements Cloneable {
gameDirTypeProperty.addListener(listener);
gameDirProperty.addListener(listener);
processPriorityProperty.addListener(listener);
useSoftwareRenderer.addListener(listener);
useNativeGLFW.addListener(listener);
useNativeOpenAL.addListener(listener);
launcherVisibilityProperty.addListener(listener);
@@ -706,6 +736,7 @@ public final class VersionSetting implements Cloneable {
versionSetting.setNoJVMArgs(isNoJVMArgs());
versionSetting.setNotCheckGame(isNotCheckGame());
versionSetting.setNotCheckJVM(isNotCheckJVM());
versionSetting.setNotPatchNatives(isNotPatchNatives());
versionSetting.setShowLogs(isShowLogs());
versionSetting.setServerIp(getServerIp());
versionSetting.setFullscreen(isFullscreen());
@@ -714,6 +745,7 @@ public final class VersionSetting implements Cloneable {
versionSetting.setGameDirType(getGameDirType());
versionSetting.setGameDir(getGameDir());
versionSetting.setProcessPriority(getProcessPriority());
versionSetting.setUseSoftwareRenderer(isUseSoftwareRenderer());
versionSetting.setUseNativeGLFW(isUseNativeGLFW());
versionSetting.setUseNativeOpenAL(isUseNativeOpenAL());
versionSetting.setLauncherVisibility(getLauncherVisibility());
@@ -747,10 +779,12 @@ public final class VersionSetting implements Cloneable {
obj.addProperty("noJVMArgs", src.isNoJVMArgs());
obj.addProperty("notCheckGame", src.isNotCheckGame());
obj.addProperty("notCheckJVM", src.isNotCheckJVM());
obj.addProperty("notPatchNatives", src.isNotPatchNatives());
obj.addProperty("showLogs", src.isShowLogs());
obj.addProperty("gameDir", src.getGameDir());
obj.addProperty("launcherVisibility", src.getLauncherVisibility().ordinal());
obj.addProperty("processPriority", src.getProcessPriority().ordinal());
obj.addProperty("useSoftwareRenderer", src.isUseSoftwareRenderer());
obj.addProperty("useNativeGLFW", src.isUseNativeGLFW());
obj.addProperty("useNativeOpenAL", src.isUseNativeOpenAL());
obj.addProperty("gameDirType", src.getGameDirType().ordinal());
@@ -793,9 +827,11 @@ public final class VersionSetting implements Cloneable {
vs.setNoJVMArgs(Optional.ofNullable(obj.get("noJVMArgs")).map(JsonElement::getAsBoolean).orElse(false));
vs.setNotCheckGame(Optional.ofNullable(obj.get("notCheckGame")).map(JsonElement::getAsBoolean).orElse(false));
vs.setNotCheckJVM(Optional.ofNullable(obj.get("notCheckJVM")).map(JsonElement::getAsBoolean).orElse(false));
vs.setNotPatchNatives(Optional.ofNullable(obj.get("notPatchNatives")).map(JsonElement::getAsBoolean).orElse(false));
vs.setShowLogs(Optional.ofNullable(obj.get("showLogs")).map(JsonElement::getAsBoolean).orElse(false));
vs.setLauncherVisibility(LauncherVisibility.values()[Optional.ofNullable(obj.get("launcherVisibility")).map(JsonElement::getAsInt).orElse(LauncherVisibility.HIDE.ordinal())]);
vs.setProcessPriority(ProcessPriority.values()[Optional.ofNullable(obj.get("processPriority")).map(JsonElement::getAsInt).orElse(ProcessPriority.NORMAL.ordinal())]);
vs.setUseSoftwareRenderer(Optional.ofNullable(obj.get("useSoftwareRenderer")).map(JsonElement::getAsBoolean).orElse(false));
vs.setUseNativeGLFW(Optional.ofNullable(obj.get("useNativeGLFW")).map(JsonElement::getAsBoolean).orElse(false));
vs.setUseNativeOpenAL(Optional.ofNullable(obj.get("useNativeOpenAL")).map(JsonElement::getAsBoolean).orElse(false));
vs.setGameDirType(GameDirectoryType.values()[Optional.ofNullable(obj.get("gameDirType")).map(JsonElement::getAsInt).orElse(GameDirectoryType.ROOT_FOLDER.ordinal())]);
@@ -31,7 +31,6 @@ import javafx.stage.Stage;
import javafx.stage.StageStyle;
import org.jackhuang.hmcl.Launcher;
import org.jackhuang.hmcl.Metadata;
import org.jackhuang.hmcl.download.java.JavaRepository;
import org.jackhuang.hmcl.game.ModpackHelper;
import org.jackhuang.hmcl.setting.Accounts;
import org.jackhuang.hmcl.setting.EnumCommonDirectory;
@@ -54,7 +53,9 @@ import org.jackhuang.hmcl.util.Lazy;
import org.jackhuang.hmcl.util.Logging;
import org.jackhuang.hmcl.util.TaskCancellationAction;
import org.jackhuang.hmcl.util.io.FileUtils;
import org.jackhuang.hmcl.util.platform.Architecture;
import org.jackhuang.hmcl.util.platform.JavaVersion;
import org.jackhuang.hmcl.util.platform.OperatingSystem;
import java.io.File;
import java.util.List;
@@ -173,7 +174,7 @@ public final class Controllers {
dialog(i18n("launcher.cache_directory.invalid"));
}
Task.runAsync(JavaVersion::initialize).thenRunAsync(JavaRepository::initialize).start();
Task.runAsync(JavaVersion::initialize).start();
scene = new Scene(decorator.getDecorator());
scene.setFill(Color.TRANSPARENT);
@@ -188,6 +189,19 @@ public final class Controllers {
stage.initStyle(StageStyle.TRANSPARENT);
stage.setScene(scene);
if (!Architecture.SYSTEM_ARCH.isX86() && globalConfig().getPlatformPromptVersion() < 1) {
Runnable continueAction = () -> globalConfig().setPlatformPromptVersion(1);
if (OperatingSystem.CURRENT_OS == OperatingSystem.OSX && Architecture.SYSTEM_ARCH == Architecture.ARM64) {
Controllers.dialog(i18n("fatal.unsupported_platform.osx_arm64"), null, MessageType.INFO, continueAction);
} else if (OperatingSystem.CURRENT_OS == OperatingSystem.WINDOWS && Architecture.SYSTEM_ARCH == Architecture.ARM64) {
Controllers.dialog(i18n("fatal.unsupported_platform.windows_arm64"), null, MessageType.INFO, continueAction);
} else {
Controllers.dialog(i18n("fatal.unsupported_platform"), null, MessageType.WARNING, continueAction);
}
}
if (globalConfig().getAgreementVersion() < 1) {
JFXDialogLayout agreementPane = new JFXDialogLayout();
agreementPane.setHeading(new Label(i18n("launcher.agreement")));
@@ -390,11 +390,19 @@ public final class FXUtils {
try {
Runtime.getRuntime().exec(new String[]{"explorer.exe", "/select,", file.toAbsolutePath().toString()});
} catch (IOException e) {
Logging.LOG.log(Level.SEVERE, "Unable to open " + file + " by executing explorer /select", e);
Logging.LOG.log(Level.SEVERE, "Unable to open " + file + " by executing explorer /select," + file, e);
}
break;
case OSX:
try {
Runtime.getRuntime().exec(new String[]{"/usr/bin/open", "-R", file.toAbsolutePath().toString()});
} catch (IOException e) {
Logging.LOG.log(Level.SEVERE, "Unable to open " + file + " by executing /usr/bin/open -R " + file, e);
}
break;
default:
// Currently unsupported.
// We do not have an universal method to show file in file manager.
openFolder(file.getParent().toFile());
break;
}
}
@@ -702,6 +710,9 @@ public final class FXUtils {
}
public static List<Node> parseSegment(String segment, Consumer<String> hyperlinkAction) {
if (segment.indexOf('<') < 0)
return Collections.singletonList(new Text(segment));
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
@@ -77,7 +77,7 @@ public class GameCrashWindow extends Stage {
private final StringProperty arch = new SimpleStringProperty(Architecture.SYSTEM_ARCH.getDisplayName());
private final TextFlow reasonTextFlow = new TextFlow(new Text(i18n("game.crash.reason.unknown")));
private final BooleanProperty loading = new SimpleBooleanProperty();
private final Label feedbackLabel = new Label(i18n("game.crash.feedback"));
private final TextFlow feedbackTextFlow = new TextFlow();
private final ManagedProcess managedProcess;
private final DefaultGameRepository repository;
@@ -104,6 +104,8 @@ public class GameCrashWindow extends Stage {
this.view = new View();
this.feedbackTextFlow.getChildren().addAll(FXUtils.parseSegment(i18n("game.crash.feedback"), Controllers::onHyperlinkAction));
setScene(new Scene(view, 800, 480));
getScene().getStylesheets().addAll(config().getTheme().getStylesheets(config().getLauncherFontFamily()));
setTitle(i18n("game.crash.title"));
@@ -137,7 +139,7 @@ public class GameCrashWindow extends Stage {
if (exception != null) {
LOG.log(Level.WARNING, "Failed to analyze crash report", exception);
reasonTextFlow.getChildren().setAll(new Text(i18n("game.crash.reason.unknown")));
reasonTextFlow.getChildren().setAll(FXUtils.parseSegment(i18n("game.crash.reason.unknown"), Controllers::onHyperlinkAction));
} else {
List<CrashReportAnalyzer.Result> results = pair.getKey();
Set<String> keywords = pair.getValue();
@@ -177,12 +179,12 @@ public class GameCrashWindow extends Stage {
if (!keywords.isEmpty()) {
reasonTextFlow.getChildren().setAll(new Text(i18n("game.crash.reason.stacktrace", String.join(", ", keywords))));
} else {
reasonTextFlow.getChildren().setAll(new Text(i18n("game.crash.reason.unknown")));
reasonTextFlow.getChildren().setAll(FXUtils.parseSegment(i18n("game.crash.reason.unknown"), Controllers::onHyperlinkAction));
}
feedbackLabel.setVisible(true);
feedbackTextFlow.setVisible(true);
} else {
feedbackLabel.setVisible(false);
feedbackTextFlow.setVisible(false);
reasonTextFlow.getChildren().setAll(segments);
}
}
@@ -350,7 +352,7 @@ public class GameCrashWindow extends Stage {
gameDirPane.setPadding(new Insets(8));
VBox.setVgrow(gameDirPane, Priority.ALWAYS);
gameDirPane.getChildren().setAll(gameDir, javaDir, new VBox(reasonTitle, reasonTextFlow));
gameDirPane.getChildren().setAll(gameDir, javaDir, new VBox(reasonTitle, reasonTextFlow, feedbackTextFlow));
}
HBox toolBar = new HBox();
@@ -368,7 +370,7 @@ public class GameCrashWindow extends Stage {
toolBar.setPadding(new Insets(8));
toolBar.setSpacing(8);
toolBar.getStyleClass().add("jfx-tool-bar");
toolBar.getChildren().setAll(exportGameCrashInfoButton, logButton, feedbackLabel);
toolBar.getChildren().setAll(exportGameCrashInfoButton, logButton);
}
getChildren().setAll(titlePane, infoPane, moddedPane, gameDirPane, toolBar);
@@ -20,6 +20,7 @@ package org.jackhuang.hmcl.ui;
import com.jfoenix.controls.JFXButton;
import javafx.beans.binding.Bindings;
import javafx.beans.property.*;
import javafx.css.PseudoClass;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
@@ -32,9 +33,7 @@ import javafx.scene.control.SkinBase;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.*;
import org.jackhuang.hmcl.download.LibraryAnalyzer;
import org.jackhuang.hmcl.setting.Theme;
import org.jackhuang.hmcl.ui.construct.RipplerContainer;
@@ -59,6 +58,13 @@ public class InstallerItem extends Control {
public final ObjectProperty<EventHandler<? super MouseEvent>> removeAction = new SimpleObjectProperty<>();
public final ObjectProperty<EventHandler<? super MouseEvent>> action = new SimpleObjectProperty<>();
private Style style = Style.LIST_ITEM;
public enum Style {
LIST_ITEM,
CARD,
}
public InstallerItem(LibraryAnalyzer.LibraryType id) {
this(id.getPatchId());
}
@@ -83,12 +89,20 @@ public class InstallerItem extends Control {
case "optifine":
imageUrl = "/assets/img/command.png";
break;
case "quilt":
case "quilt-api":
imageUrl = "/assets/img/quilt.png";
break;
default:
imageUrl = null;
break;
}
}
public void setStyleMode(Style style) {
this.style = style;
}
public void setState(String libraryVersion, boolean incompatibleWithGame, boolean removable) {
this.libraryVersion.set(libraryVersion);
this.incompatibleWithGame.set(incompatibleWithGame);
@@ -111,76 +125,112 @@ public class InstallerItem extends Control {
public final InstallerItem forge = new InstallerItem(FORGE);
public final InstallerItem liteLoader = new InstallerItem(LITELOADER);
public final InstallerItem optiFine = new InstallerItem(OPTIFINE);
public final InstallerItem quilt = new InstallerItem(QUILT);
public final InstallerItem quiltApi = new InstallerItem(QUILT_API);
public InstallerItemGroup() {
forge.incompatibleLibraryName.bind(Bindings.createStringBinding(() -> {
if (fabric.libraryVersion.get() != null) return FABRIC.getPatchId();
if (quilt.libraryVersion.get() != null) return QUILT.getPatchId();
return null;
}, fabric.libraryVersion));
}, fabric.libraryVersion, quilt.libraryVersion));
liteLoader.incompatibleLibraryName.bind(Bindings.createStringBinding(() -> {
if (fabric.libraryVersion.get() != null) return FABRIC.getPatchId();
if (quilt.libraryVersion.get() != null) return QUILT.getPatchId();
return null;
}, fabric.libraryVersion));
}, fabric.libraryVersion, quilt.libraryVersion));
optiFine.incompatibleLibraryName.bind(Bindings.createStringBinding(() -> {
if (fabric.libraryVersion.get() != null) return FABRIC.getPatchId();
if (quilt.libraryVersion.get() != null) return QUILT.getPatchId();
return null;
}, fabric.libraryVersion));
}, fabric.libraryVersion, quilt.libraryVersion));
for (InstallerItem fabric : new InstallerItem[]{fabric, fabricApi}) {
fabric.incompatibleLibraryName.bind(Bindings.createStringBinding(() -> {
if (forge.libraryVersion.get() != null) return FORGE.getPatchId();
if (liteLoader.libraryVersion.get() != null) return LITELOADER.getPatchId();
if (optiFine.libraryVersion.get() != null) return OPTIFINE.getPatchId();
if (forge.libraryVersion.get() != null) return FORGE.getPatchId();
if (quilt.libraryVersion.get() != null) return QUILT.getPatchId();
if (quiltApi.libraryVersion.get() != null) return QUILT_API.getPatchId();
return null;
}, optiFine.libraryVersion, forge.libraryVersion));
}, forge.libraryVersion, liteLoader.libraryVersion, optiFine.libraryVersion, quilt.libraryVersion, quiltApi.libraryVersion));
}
fabricApi.dependencyName.bind(Bindings.createStringBinding(() -> {
if (fabric.libraryVersion.get() == null) return FABRIC.getPatchId();
else return null;
}, fabric.libraryVersion));
for (InstallerItem quilt : new InstallerItem[]{quilt, quiltApi}) {
quilt.incompatibleLibraryName.bind(Bindings.createStringBinding(() -> {
if (fabric.libraryVersion.get() != null) return FABRIC.getPatchId();
if (fabricApi.libraryVersion.get() != null) return FABRIC_API.getPatchId();
if (forge.libraryVersion.get() != null) return FORGE.getPatchId();
if (liteLoader.libraryVersion.get() != null) return LITELOADER.getPatchId();
if (optiFine.libraryVersion.get() != null) return OPTIFINE.getPatchId();
return null;
}, fabric.libraryVersion, fabricApi.libraryVersion, forge.libraryVersion, liteLoader.libraryVersion, optiFine.libraryVersion));
}
quiltApi.dependencyName.bind(Bindings.createStringBinding(() -> {
if (quilt.libraryVersion.get() == null) return QUILT.getPatchId();
else return null;
}, quilt.libraryVersion));
}
public InstallerItem[] getLibraries() {
return new InstallerItem[]{game, forge, liteLoader, optiFine, fabric, fabricApi};
return new InstallerItem[]{game, forge, liteLoader, optiFine, fabric, fabricApi, quilt, quiltApi};
}
}
public static class InstallerItemSkin extends SkinBase<InstallerItem> {
private static final PseudoClass LIST_ITEM = PseudoClass.getPseudoClass("list-item");
private static final PseudoClass CARD = PseudoClass.getPseudoClass("card");
InstallerItemSkin(InstallerItem control) {
super(control);
HBox hbox = new HBox();
hbox.getStyleClass().add("md-list-cell");
hbox.setPadding(new Insets(8));
RipplerContainer container = new RipplerContainer(hbox);
Pane pane;
if (control.style == Style.CARD) {
pane = new VBox();
} else {
pane = new HBox();
}
pane.getStyleClass().add("installer-item");
RipplerContainer container = new RipplerContainer(pane);
getChildren().setAll(container);
hbox.setAlignment(Pos.CENTER_LEFT);
pane.pseudoClassStateChanged(LIST_ITEM, control.style == Style.LIST_ITEM);
pane.pseudoClassStateChanged(CARD, control.style == Style.CARD);
if (control.imageUrl != null) {
ImageView view = new ImageView(new Image(control.imageUrl, 32, 32, true, true));
Node node = FXUtils.limitingSize(view, 32, 32);
node.setMouseTransparent(true);
hbox.getChildren().add(node);
node.getStyleClass().add("installer-item-image");
pane.getChildren().add(node);
if (control.style == Style.CARD) {
VBox.setMargin(node, new Insets(8, 0, 16, 0));
}
}
Label nameLabel = new Label();
nameLabel.getStyleClass().add("installer-item-name");
nameLabel.setMouseTransparent(true);
hbox.getChildren().add(nameLabel);
nameLabel.setPrefWidth(80);
pane.getChildren().add(nameLabel);
nameLabel.textProperty().set(I18n.hasKey("install.installer." + control.id) ? i18n("install.installer." + control.id) : control.id);
HBox.setMargin(nameLabel, new Insets(0, 4, 0, 4));
Label label = new Label();
label.setMouseTransparent(true);
hbox.getChildren().add(label);
label.setMaxWidth(Double.MAX_VALUE);
HBox.setHgrow(label, Priority.ALWAYS);
label.textProperty().bind(Bindings.createStringBinding(() -> {
Label statusLabel = new Label();
statusLabel.getStyleClass().add("installer-item-status");
statusLabel.setMouseTransparent(true);
pane.getChildren().add(statusLabel);
HBox.setHgrow(statusLabel, Priority.ALWAYS);
statusLabel.textProperty().bind(Bindings.createStringBinding(() -> {
String incompatibleWith = control.incompatibleLibraryName.get();
String version = control.libraryVersion.get();
if (control.incompatibleWithGame.get()) {
@@ -193,8 +243,13 @@ public class InstallerItem extends Control {
return i18n("install.installer.version", version);
}
}, control.incompatibleLibraryName, control.incompatibleWithGame, control.libraryVersion));
BorderPane.setMargin(label, new Insets(0, 0, 0, 8));
BorderPane.setAlignment(label, Pos.CENTER_LEFT);
BorderPane.setMargin(statusLabel, new Insets(0, 0, 0, 8));
BorderPane.setAlignment(statusLabel, Pos.CENTER_LEFT);
HBox buttonsContainer = new HBox();
buttonsContainer.setSpacing(8);
buttonsContainer.setAlignment(Pos.CENTER);
pane.getChildren().add(buttonsContainer);
JFXButton closeButton = new JFXButton();
closeButton.setGraphic(SVG.close(Theme.blackFillBinding(), -1, -1));
@@ -202,7 +257,7 @@ public class InstallerItem extends Control {
closeButton.visibleProperty().bind(control.removable);
closeButton.managedProperty().bind(closeButton.visibleProperty());
closeButton.onMouseClickedProperty().bind(control.removeAction);
hbox.getChildren().add(closeButton);
buttonsContainer.getChildren().add(closeButton);
JFXButton arrowButton = new JFXButton();
arrowButton.graphicProperty().bind(Bindings.createObjectBinding(() -> control.upgradable.get()
@@ -215,16 +270,16 @@ public class InstallerItem extends Control {
control.installable, control.incompatibleLibraryName));
arrowButton.managedProperty().bind(arrowButton.visibleProperty());
arrowButton.onMouseClickedProperty().bind(control.action);
hbox.getChildren().add(arrowButton);
buttonsContainer.getChildren().add(arrowButton);
FXUtils.onChangeAndOperate(arrowButton.visibleProperty(), clickable -> {
if (clickable) {
container.onMouseClickedProperty().bind(control.action);
hbox.setCursor(Cursor.HAND);
pane.setCursor(Cursor.HAND);
} else {
container.onMouseClickedProperty().unbind();
container.onMouseClickedProperty().set(null);
hbox.setCursor(Cursor.DEFAULT);
pane.setCursor(Cursor.DEFAULT);
}
});
}
@@ -36,6 +36,7 @@ import javafx.scene.layout.*;
import javafx.stage.Stage;
import org.jackhuang.hmcl.game.LauncherHelper;
import org.jackhuang.hmcl.util.Log4jLevel;
import org.jackhuang.hmcl.util.Logging;
import org.jackhuang.hmcl.util.platform.OperatingSystem;
import javax.swing.*;
@@ -99,7 +100,7 @@ public final class LogWindow extends Stage {
}
public void logLine(String line, Log4jLevel level) {
Log log = new Log(parseEscapeSequence(line), level);
Log log = new Log(Logging.filterForbiddenToken(parseEscapeSequence(line)), level);
logs.add(log);
if (levelShownMap.get(level).get())
impl.listView.getItems().add(log);
@@ -156,7 +156,7 @@ public class AccountListItem extends RadioButton {
return null;
}
if (account instanceof MicrosoftAccount) {
FXUtils.openLink("https://www.minecraft.net/profile/skin");
FXUtils.openLink("https://www.minecraft.net/msaprofile/mygames/editskin");
return null;
}
if (!(account instanceof YggdrasilAccount)) {
@@ -45,8 +45,10 @@ import org.jackhuang.hmcl.util.javafx.BindingMapping;
import org.jackhuang.hmcl.util.javafx.MappedObservableList;
import java.net.URI;
import java.util.logging.Level;
import static org.jackhuang.hmcl.ui.versions.VersionPage.wrap;
import static org.jackhuang.hmcl.util.Logging.LOG;
import static org.jackhuang.hmcl.util.i18n.I18n.i18n;
import static org.jackhuang.hmcl.util.javafx.ExtendedProperties.createSelectedItemPropertyFor;
@@ -122,6 +124,14 @@ public class AccountListPage extends DecoratorAnimatedPage implements DecoratorP
microsoftItem.setOnAction(e -> Controllers.dialog(new CreateAccountPane(Accounts.FACTORY_MICROSOFT)));
boxMethods.getChildren().add(microsoftItem);
AdvancedListItem littleSkinItem = new AdvancedListItem();
littleSkinItem.getStyleClass().add("navigation-drawer-item");
littleSkinItem.setActionButtonVisible(false);
littleSkinItem.setTitle(i18n("account.methods.little_skin"));
littleSkinItem.setLeftGraphic(wrap(SVG::server));
littleSkinItem.setOnAction(e -> Controllers.dialog(new CreateAccountPane(Accounts.FACTORY_LITTLE_SKIN)));
boxMethods.getChildren().add(littleSkinItem);
VBox boxAuthServers = new VBox();
authServerItems = MappedObservableList.create(skinnable.authServersProperty(), server -> {
AdvancedListItem item = new AdvancedListItem();
@@ -140,7 +150,13 @@ public class AccountListPage extends DecoratorAnimatedPage implements DecoratorP
ObservableValue<String> title = BindingMapping.of(server, AuthlibInjectorServer::getName);
item.titleProperty().bind(title);
item.subtitleProperty().set(URI.create(server.getUrl()).getHost());
String host = "";
try {
host = URI.create(server.getUrl()).getHost();
} catch (IllegalArgumentException e) {
LOG.log(Level.WARNING, "Unparsable authlib-injector server url " + server.getUrl(), e);
}
item.subtitleProperty().set(host);
Tooltip tooltip = new Tooltip();
tooltip.textProperty().bind(Bindings.format("%s (%s)", title, server.getUrl()));
FXUtils.installFastTooltip(item, tooltip);
@@ -22,6 +22,7 @@ import com.jfoenix.controls.JFXDialogLayout;
import com.jfoenix.controls.JFXTextField;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.StackPane;
import org.jackhuang.hmcl.auth.authlibinjector.AuthlibInjectorServer;
import org.jackhuang.hmcl.task.Schedulers;
@@ -67,6 +68,7 @@ public class AddAuthlibInjectorServerPane extends StackPane implements DialogAwa
loadFXML(this, "/assets/fxml/authlib-injector-server-add.fxml");
root.setContent(addServerPane, ContainerAnimations.NONE.getAnimationProducer());
lblCreationWarning.maxWidthProperty().bind(((FlowPane) lblCreationWarning.getParent()).widthProperty());
btnAddNext.disableProperty().bind(txtServerUrl.textProperty().isEmpty());
nextPane.hideSpinner();
@@ -40,6 +40,7 @@ import org.jackhuang.hmcl.auth.CharacterSelector;
import org.jackhuang.hmcl.auth.NoSelectedCharacterException;
import org.jackhuang.hmcl.auth.authlibinjector.AuthlibInjectorAccountFactory;
import org.jackhuang.hmcl.auth.authlibinjector.AuthlibInjectorServer;
import org.jackhuang.hmcl.auth.authlibinjector.BoundAuthlibInjectorAccountFactory;
import org.jackhuang.hmcl.auth.microsoft.MicrosoftAccountFactory;
import org.jackhuang.hmcl.auth.offline.OfflineAccountFactory;
import org.jackhuang.hmcl.auth.yggdrasil.GameProfile;
@@ -194,9 +195,8 @@ public class CreateAccountPane extends JFXDialogLayout implements DialogAware {
setPrefWidth(560);
}
public CreateAccountPane(AuthlibInjectorServer authserver) {
this(Accounts.FACTORY_AUTHLIB_INJECTOR);
((AccountDetailsInputPane) detailsPane).selectAuthServer(authserver);
public CreateAccountPane(AuthlibInjectorServer authServer) {
this(Accounts.getAccountFactoryByAuthlibInjectorServer(authServer));
}
private void onAccept() {
@@ -267,40 +267,54 @@ public class CreateAccountPane extends JFXDialogLayout implements DialogAware {
}
if (factory == Accounts.FACTORY_MICROSOFT) {
VBox vbox = new VBox(8);
HintPane hintPane = new HintPane(MessageDialogPane.MessageType.INFO);
FXUtils.onChangeAndOperate(deviceCode, deviceCode -> {
if (deviceCode != null) {
FXUtils.copyText(deviceCode.getUserCode());
hintPane.setSegment(i18n("account.methods.microsoft.manual", deviceCode.getUserCode(), deviceCode.getVerificationUri()));
} else {
hintPane.setSegment(i18n("account.methods.microsoft.hint"));
}
});
hintPane.setOnMouseClicked(e -> {
if (deviceCode.get() != null) {
FXUtils.copyText(deviceCode.get().getUserCode());
}
});
if (!Accounts.OAUTH_CALLBACK.getClientId().isEmpty()) {
HintPane hintPane = new HintPane(MessageDialogPane.MessageType.INFO);
FXUtils.onChangeAndOperate(deviceCode, deviceCode -> {
if (deviceCode != null) {
FXUtils.copyText(deviceCode.getUserCode());
hintPane.setSegment(i18n("account.methods.microsoft.manual", deviceCode.getUserCode(), deviceCode.getVerificationUri()));
} else {
hintPane.setSegment(i18n("account.methods.microsoft.hint"));
}
});
hintPane.setOnMouseClicked(e -> {
if (deviceCode.get() != null) {
FXUtils.copyText(deviceCode.get().getUserCode());
}
});
holder.add(Accounts.OAUTH_CALLBACK.onGrantDeviceCode.registerWeak(value -> {
runInFX(() -> deviceCode.set(value));
}));
HBox box = new HBox(8);
JFXHyperlink birthLink = new JFXHyperlink(i18n("account.methods.microsoft.birth"));
birthLink.setOnAction(e -> FXUtils.openLink("https://support.microsoft.com/account-billing/837badbc-999e-54d2-2617-d19206b9540a"));
JFXHyperlink profileLink = new JFXHyperlink(i18n("account.methods.microsoft.profile"));
profileLink.setOnAction(e -> FXUtils.openLink("https://account.live.com/editprof.aspx"));
JFXHyperlink purchaseLink = new JFXHyperlink(i18n("account.methods.yggdrasil.purchase"));
JFXHyperlink deauthorizeLink = new JFXHyperlink(i18n("account.methods.microsoft.deauthorize"));
deauthorizeLink.setOnAction(e -> FXUtils.openLink("https://account.live.com/consent/Edit?client_id=000000004C794E0A"));
purchaseLink.setOnAction(e -> FXUtils.openLink(YggdrasilService.PURCHASE_URL));
box.getChildren().setAll(profileLink, birthLink, purchaseLink, deauthorizeLink);
GridPane.setColumnSpan(box, 2);
holder.add(Accounts.OAUTH_CALLBACK.onGrantDeviceCode.registerWeak(value -> {
runInFX(() -> deviceCode.set(value));
}));
FlowPane box = new FlowPane();
box.setHgap(8);
JFXHyperlink birthLink = new JFXHyperlink(i18n("account.methods.microsoft.birth"));
birthLink.setOnAction(e -> FXUtils.openLink("https://support.microsoft.com/account-billing/837badbc-999e-54d2-2617-d19206b9540a"));
JFXHyperlink profileLink = new JFXHyperlink(i18n("account.methods.microsoft.profile"));
profileLink.setOnAction(e -> FXUtils.openLink("https://account.live.com/editprof.aspx"));
JFXHyperlink purchaseLink = new JFXHyperlink(i18n("account.methods.yggdrasil.purchase"));
JFXHyperlink deauthorizeLink = new JFXHyperlink(i18n("account.methods.microsoft.deauthorize"));
deauthorizeLink.setOnAction(e -> FXUtils.openLink("https://account.live.com/consent/Edit?client_id=000000004C794E0A"));
JFXHyperlink forgotpasswordLink = new JFXHyperlink(i18n("account.methods.forgot_password"));
forgotpasswordLink.setOnAction(e -> FXUtils.openLink("https://www.minecraft.net/password/forgot"));
JFXHyperlink createProfileLink = new JFXHyperlink(i18n("account.methods.microsoft.makegameidsettings"));
createProfileLink.setOnAction(e -> FXUtils.openLink("https://www.minecraft.net/msaprofile/mygames/editprofile"));
purchaseLink.setOnAction(e -> FXUtils.openLink(YggdrasilService.PURCHASE_URL));
box.getChildren().setAll(profileLink, birthLink, purchaseLink, deauthorizeLink, createProfileLink);
GridPane.setColumnSpan(box, 2);
vbox.getChildren().setAll(hintPane, box);
vbox.getChildren().setAll(hintPane, box);
btnAccept.setDisable(false);
} else {
HintPane hintPane = new HintPane(MessageDialogPane.MessageType.WARNING);
hintPane.setText(i18n("account.methods.microsoft.snapshot"));
vbox.getChildren().setAll(hintPane);
btnAccept.setDisable(true);
}
detailsPane = vbox;
btnAccept.setDisable(false);
} else if (factory == Accounts.FACTORY_MOJANG) {
VBox vbox = new VBox(8);
HintPane hintPane = new HintPane(MessageDialogPane.MessageType.WARNING);
@@ -329,7 +343,7 @@ public class CreateAccountPane extends JFXDialogLayout implements DialogAware {
private static class AccountDetailsInputPane extends GridPane {
// ==== authlib-injector hyperlinks ====
private static final String[] ALLOWED_LINKS = { "register" };
private static final String[] ALLOWED_LINKS = { "homepage", "register" };
private static List<Hyperlink> createHyperlinks(AuthlibInjectorServer server) {
if (server == null) {
@@ -351,12 +365,13 @@ public class CreateAccountPane extends JFXDialogLayout implements DialogAware {
}
// =====
private AccountFactory<?> factory;
private final AccountFactory<?> factory;
private @Nullable AuthlibInjectorServer server;
private @Nullable JFXComboBox<AuthlibInjectorServer> cboServers;
private @Nullable JFXTextField txtUsername;
private @Nullable JFXPasswordField txtPassword;
private @Nullable JFXTextField txtUUID;
private BooleanBinding valid;
private final BooleanBinding valid;
public AccountDetailsInputPane(AccountFactory<?> factory, Runnable onAction) {
this.factory = factory;
@@ -374,7 +389,28 @@ public class CreateAccountPane extends JFXDialogLayout implements DialogAware {
int rowIndex = 0;
if (factory instanceof AuthlibInjectorAccountFactory) {
if (factory instanceof BoundAuthlibInjectorAccountFactory) {
this.server = ((BoundAuthlibInjectorAccountFactory) factory).getServer();
Label lblServers = new Label(i18n("account.injector.server"));
setHalignment(lblServers, HPos.LEFT);
add(lblServers, 0, rowIndex);
Label lblServerName = new Label(this.server.getName());
lblServerName.setMaxWidth(Double.MAX_VALUE);
HBox.setHgrow(lblServerName, Priority.ALWAYS);
HBox linksContainer = new HBox();
linksContainer.setAlignment(Pos.CENTER);
linksContainer.getChildren().setAll(createHyperlinks(this.server));
linksContainer.setMinWidth(USE_PREF_SIZE);
HBox boxServers = new HBox(lblServerName, linksContainer);
boxServers.setAlignment(Pos.CENTER_LEFT);
add(boxServers, 1, rowIndex);
rowIndex++;
} else if (factory instanceof AuthlibInjectorAccountFactory) {
Label lblServers = new Label(i18n("account.injector.server"));
setHalignment(lblServers, HPos.LEFT);
add(lblServers, 0, rowIndex);
@@ -397,7 +433,10 @@ public class CreateAccountPane extends JFXDialogLayout implements DialogAware {
HBox linksContainer = new HBox();
linksContainer.setAlignment(Pos.CENTER);
onChangeAndOperate(cboServers.valueProperty(), server -> linksContainer.getChildren().setAll(createHyperlinks(server)));
onChangeAndOperate(cboServers.valueProperty(), server -> {
this.server = server;
linksContainer.getChildren().setAll(createHyperlinks(server));
});
linksContainer.setMinWidth(USE_PREF_SIZE);
JFXButton btnAddServer = new JFXButton();
@@ -542,11 +581,8 @@ public class CreateAccountPane extends JFXDialogLayout implements DialogAware {
private boolean requiresEmailAsUsername() {
if (factory instanceof YggdrasilAccountFactory) {
return true;
} else if ((factory instanceof AuthlibInjectorAccountFactory) && cboServers != null) {
AuthlibInjectorServer server = cboServers.getValue();
if (server != null && !server.isNonEmailLogin()) {
return true;
}
} else if ((factory instanceof AuthlibInjectorAccountFactory) && this.server != null) {
return !server.isNonEmailLogin();
}
return false;
}
@@ -563,7 +599,7 @@ public class CreateAccountPane extends JFXDialogLayout implements DialogAware {
}
public @Nullable AuthlibInjectorServer getAuthServer() {
return cboServers == null ? null : cboServers.getValue();
return this.server;
}
public @Nullable String getUsername() {
@@ -578,10 +614,6 @@ public class CreateAccountPane extends JFXDialogLayout implements DialogAware {
return valid;
}
public void selectAuthServer(AuthlibInjectorServer authserver) {
cboServers.getSelectionModel().select(authserver);
}
public void focus() {
if (txtUsername != null) {
txtUsername.requestFocus();
@@ -48,9 +48,9 @@ public class OAuthAccountLoginDialog extends DialogPane {
FXUtils.onChangeAndOperate(deviceCode, deviceCode -> {
if (deviceCode != null) {
FXUtils.copyText(deviceCode.getUserCode());
hintPane.setSegment(i18n("account.methods.microsoft.manual", deviceCode.getUserCode(), deviceCode.getVerificationUri()));
hintPane.setSegment(i18n("account.login.refresh.microsoft.manual", deviceCode.getUserCode(), deviceCode.getVerificationUri()));
} else {
hintPane.setSegment(i18n("account.methods.microsoft.hint"));
hintPane.setSegment(i18n("account.login.refresh.microsoft.hint"));
}
});
hintPane.setOnMouseClicked(e -> {
@@ -61,7 +61,7 @@ public class OAuthAccountLoginDialog extends DialogPane {
HBox box = new HBox(8);
JFXHyperlink birthLink = new JFXHyperlink(i18n("account.methods.microsoft.birth"));
birthLink.setOnAction(e -> FXUtils.openLink("https://support.microsoft.com/zh-cn/account-billing/如何更改-microsoft-帐户上的出生日期-837badbc-999e-54d2-2617-d19206b9540a"));
birthLink.setOnAction(e -> FXUtils.openLink("https://support.microsoft.com/account-billing/how-to-change-a-birth-date-on-a-microsoft-account-837badbc-999e-54d2-2617-d19206b9540a"));
JFXHyperlink profileLink = new JFXHyperlink(i18n("account.methods.microsoft.profile"));
profileLink.setOnAction(e -> FXUtils.openLink("https://account.live.com/editprof.aspx"));
JFXHyperlink purchaseLink = new JFXHyperlink(i18n("account.methods.yggdrasil.purchase"));
@@ -19,26 +19,37 @@ package org.jackhuang.hmcl.ui.construct;
import javafx.collections.ObservableList;
import javafx.scene.Node;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import org.jackhuang.hmcl.ui.FXUtils;
import java.util.function.Consumer;
public class AdvancedListBox extends VBox {
public class AdvancedListBox extends ScrollPane {
private final VBox container = new VBox();
{
getStyleClass().add("advanced-list-box-content");
setContent(container);
FXUtils.smoothScrolling(this);
setFitToHeight(true);
setFitToWidth(true);
setHbarPolicy(ScrollBarPolicy.NEVER);
container.getStyleClass().add("advanced-list-box-content");
}
public AdvancedListBox add(Node child) {
if (child instanceof Pane || child instanceof AdvancedListItem)
getChildren().add(child);
container.getChildren().add(child);
else {
StackPane pane = new StackPane();
pane.getStyleClass().add("advanced-list-box-item");
pane.getChildren().setAll(child);
getChildren().add(pane);
container.getChildren().add(pane);
}
return this;
}
@@ -53,27 +64,27 @@ public class AdvancedListBox extends VBox {
public AdvancedListBox add(int index, Node child) {
if (child instanceof Pane || child instanceof AdvancedListItem)
getChildren().add(index, child);
container.getChildren().add(index, child);
else {
StackPane pane = new StackPane();
pane.getStyleClass().add("advanced-list-box-item");
pane.getChildren().setAll(child);
getChildren().add(index, pane);
container.getChildren().add(index, pane);
}
return this;
}
public AdvancedListBox remove(Node child) {
getChildren().remove(indexOf(child));
container.getChildren().remove(indexOf(child));
return this;
}
public int indexOf(Node child) {
if (child instanceof Pane) {
return getChildren().indexOf(child);
return container.getChildren().indexOf(child);
} else {
for (int i = 0; i < getChildren().size(); ++i) {
Node node = getChildren().get(i);
for (int i = 0; i < container.getChildren().size(); ++i) {
Node node = container.getChildren().get(i);
if (node instanceof StackPane) {
ObservableList<Node> list = ((StackPane) node).getChildren();
if (list.size() == 1 && list.get(0) == child)
@@ -88,7 +99,11 @@ public class AdvancedListBox extends VBox {
return add(new ClassTitle(category));
}
public void setSpacing(double spacing) {
container.setSpacing(spacing);
}
public void clear() {
getChildren().clear();
container.getChildren().clear();
}
}
@@ -28,11 +28,11 @@ import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.css.PseudoClass;
import javafx.geometry.Insets;
import javafx.geometry.Orientation;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.Control;
import javafx.scene.control.Label;
import javafx.scene.control.SkinBase;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
@@ -115,12 +115,17 @@ public class ComponentList extends Control {
expanded = true;
}
@Override
public Orientation getContentBias() {
return Orientation.HORIZONTAL;
}
@Override
protected javafx.scene.control.Skin<?> createDefaultSkin() {
return new Skin(this);
}
protected static class Skin extends SkinBase<ComponentList> {
protected static class Skin extends ControlSkinBase<ComponentList> {
private static final PseudoClass PSEUDO_CLASS_FIRST = PseudoClass.getPseudoClass("first");
private static final PseudoClass PSEUDO_CLASS_LAST = PseudoClass.getPseudoClass("last");
@@ -166,7 +171,7 @@ public class ComponentList extends Control {
VBox vbox = new VBox();
vbox.setFillWidth(true);
Bindings.bindContent(vbox.getChildren(), list);
getChildren().setAll(vbox);
node = vbox;
}
}
@@ -0,0 +1,55 @@
/*
* Hello Minecraft! Launcher
* Copyright (C) 2022 huangyuhui <huanghongxun2008@126.com> and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.jackhuang.hmcl.ui.construct;
import javafx.scene.Node;
import javafx.scene.control.Control;
import javafx.scene.control.Skin;
import java.util.Objects;
public abstract class ControlSkinBase<C extends Control> implements Skin<C> {
private final C control;
protected Node node;
/**
* Constructor for all SkinBase instances.
*
* @param control The control for which this Skin should attach to.
*/
protected ControlSkinBase(C control) {
this.control = control;
}
@Override
public C getSkinnable() {
return control;
}
@Override
public Node getNode() {
Objects.requireNonNull(node);
return node;
}
@Override
public void dispose() {
}
}
@@ -34,7 +34,7 @@ import static org.jackhuang.hmcl.util.i18n.I18n.i18n;
public class DialogPane extends JFXDialogLayout {
private final StringProperty title = new SimpleStringProperty();
private final BooleanProperty valid = new SimpleBooleanProperty();
private final BooleanProperty valid = new SimpleBooleanProperty(true);
protected final SpinnerPane acceptPane = new SpinnerPane();
protected final JFXButton cancelButton = new JFXButton();
protected final Label warningLabel = new Label();
@@ -0,0 +1,57 @@
/*
* Hello Minecraft! Launcher
* Copyright (C) 2020 huangyuhui <huanghongxun2008@126.com> and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.jackhuang.hmcl.ui.construct;
import com.jfoenix.validation.base.ValidatorBase;
import javafx.beans.NamedArg;
import javafx.scene.control.TextInputControl;
import org.jackhuang.hmcl.util.Lang;
import org.jackhuang.hmcl.util.StringUtils;
public class DoubleValidator extends ValidatorBase {
private final boolean nullable;
public DoubleValidator() {
this(false);
}
public DoubleValidator(@NamedArg("nullable") boolean nullable) {
this.nullable = nullable;
}
public DoubleValidator(@NamedArg("message") String message, @NamedArg("nullable") boolean nullable) {
super(message);
this.nullable = nullable;
}
@Override
protected void eval() {
if (srcControl.get() instanceof TextInputControl) {
evalTextInputField();
}
}
private void evalTextInputField() {
TextInputControl textField = ((TextInputControl) srcControl.get());
if (StringUtils.isBlank(textField.getText()))
hasErrors.set(!nullable);
else
hasErrors.set(Lang.toDoubleOrNull(textField.getText()) == null);
}
}
@@ -23,8 +23,12 @@ import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.control.ButtonBase;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.text.TextFlow;
import org.jackhuang.hmcl.setting.Theme;
import org.jackhuang.hmcl.ui.Controllers;
import org.jackhuang.hmcl.ui.FXUtils;
@@ -69,7 +73,17 @@ public final class MessageDialogPane extends StackPane {
public MessageDialogPane(@NotNull String text, @Nullable String title, @NotNull MessageType type) {
FXUtils.loadFXML(this, "/assets/fxml/message-dialog.fxml");
content.getChildren().setAll(FXUtils.segmentToTextFlow(text, Controllers::onHyperlinkAction));
EnhancedTextFlow textFlow = new EnhancedTextFlow();
textFlow.getChildren().setAll(FXUtils.parseSegment(text, Controllers::onHyperlinkAction));
if (textFlow.computePrefHeight(400.0) <= 350.0)
content.getChildren().setAll(textFlow);
else {
ScrollPane scrollPane = new ScrollPane(textFlow);
VBox.setVgrow(scrollPane, Priority.ALWAYS);
scrollPane.setFitToWidth(true);
content.getChildren().setAll(scrollPane);
}
if (title != null)
this.title.setText(title);
@@ -114,6 +128,13 @@ public final class MessageDialogPane extends StackPane {
return cancelButton;
}
private static final class EnhancedTextFlow extends TextFlow {
@Override
public double computePrefHeight(double width) {
return super.computePrefHeight(width);
}
}
public static class Builder {
private final MessageDialogPane dialog;
@@ -123,10 +144,11 @@ public final class MessageDialogPane extends StackPane {
public Builder addAction(Node actionNode) {
dialog.addButton(actionNode);
actionNode.getStyleClass().add("dialog-accept");
return this;
}
public Builder ok(Runnable ok) {
public Builder ok(@Nullable Runnable ok) {
JFXButton btnOk = new JFXButton(i18n("button.ok"));
btnOk.getStyleClass().add("dialog-accept");
if (ok != null) {
@@ -137,7 +159,22 @@ public final class MessageDialogPane extends StackPane {
return this;
}
public Builder yesOrNo(Runnable yes, Runnable no) {
public Builder addCancel(@Nullable Runnable cancel) {
return addCancel(i18n("button.cancel"), cancel);
}
public Builder addCancel(String cancelText, @Nullable Runnable cancel) {
JFXButton btnCancel = new JFXButton(cancelText);
btnCancel.getStyleClass().add("dialog-cancel");
if (cancel != null) {
btnCancel.setOnAction(e -> cancel.run());
}
dialog.addButton(btnCancel);
dialog.setCancelButton(btnCancel);
return this;
}
public Builder yesOrNo(@Nullable Runnable yes, @Nullable Runnable no) {
JFXButton btnYes = new JFXButton(i18n("button.yes"));
btnYes.getStyleClass().add("dialog-accept");
if (yes != null) {
@@ -145,27 +182,14 @@ public final class MessageDialogPane extends StackPane {
}
dialog.addButton(btnYes);
JFXButton btnNo = new JFXButton(i18n("button.no"));
btnNo.getStyleClass().add("dialog-cancel");
if (no != null) {
btnNo.setOnAction(e -> no.run());
}
dialog.addButton(btnNo);
dialog.setCancelButton(btnNo);
addCancel(i18n("button.no"), no);
return this;
}
public Builder actionOrCancel(ButtonBase actionButton, Runnable cancel) {
dialog.addButton(actionButton);
JFXButton btnCancel = new JFXButton(i18n("button.cancel"));
btnCancel.getStyleClass().add("dialog-cancel");
if (cancel != null) {
btnCancel.setOnAction(e -> cancel.run());
}
dialog.addButton(btnCancel);
dialog.setCancelButton(btnCancel);
addCancel(cancel);
return this;
}
@@ -28,7 +28,6 @@ import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.control.Toggle;
import javafx.scene.control.ToggleGroup;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
@@ -165,19 +164,12 @@ public class MultiFileItem<T> extends VBox {
pane.setLeft(left);
if (StringUtils.isNotBlank(subtitle)) {
Optional<String> shortSubtitle = StringUtils.truncate(subtitle);
Label right;
if (shortSubtitle.isPresent()) {
right = new Label(shortSubtitle.get());
right.setTooltip(new Tooltip(subtitle));
} else {
right = new Label(subtitle);
}
BorderPane.setAlignment(right, Pos.CENTER_RIGHT);
right.setWrapText(true);
right.getStyleClass().add("subtitle-label");
right.setStyle("-fx-font-size: 10;");
pane.setRight(right);
Label center = new Label(subtitle);
BorderPane.setAlignment(center, Pos.CENTER_RIGHT);
center.setWrapText(true);
center.getStyleClass().add("subtitle-label");
center.setStyle("-fx-font-size: 10;");
pane.setCenter(center);
}
return pane;
@@ -50,8 +50,9 @@ public class OptionToggleButton extends StackPane {
titleLabel.textProperty().bind(title);
Label subtitleLabel = new Label();
subtitleLabel.setMouseTransparent(true);
subtitleLabel.setWrapText(true);
subtitleLabel.textProperty().bind(subtitle);
pane.setLeft(left);
pane.setCenter(left);
left.setAlignment(Pos.CENTER_LEFT);
JFXToggleButton toggleButton = new JFXToggleButton();
@@ -0,0 +1,62 @@
/*
* Hello Minecraft! Launcher
* Copyright (C) 2022 huangyuhui <huanghongxun2008@126.com> and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.jackhuang.hmcl.ui.construct;
import com.jfoenix.validation.base.ValidatorBase;
import javafx.beans.NamedArg;
import javafx.scene.control.TextInputControl;
import org.jackhuang.hmcl.util.StringUtils;
import java.util.regex.Pattern;
import static org.jackhuang.hmcl.util.i18n.I18n.i18n;
public class ServerAddressValidator extends ValidatorBase {
private final boolean nullable;
public ServerAddressValidator() {
this(false);
}
public ServerAddressValidator(@NamedArg("nullable") boolean nullable) {
this(i18n("input.url"), nullable);
}
public ServerAddressValidator(@NamedArg("message") String message, @NamedArg("nullable") boolean nullable) {
super(message);
this.nullable = nullable;
}
@Override
protected void eval() {
if (srcControl.get() instanceof TextInputControl) {
evalTextInputField();
}
}
private static final Pattern PATTERN = Pattern.compile("[-a-zA-Z0-9@:%._+~#=]{1,256}(:\\d+)?");
private void evalTextInputField() {
TextInputControl textField = ((TextInputControl) srcControl.get());
if (StringUtils.isBlank(textField.getText()))
hasErrors.set(!nullable);
else
hasErrors.set(!PATTERN.matcher(textField.getText()).matches());
}
}
@@ -34,6 +34,7 @@ import org.jackhuang.hmcl.download.forge.ForgeNewInstallTask;
import org.jackhuang.hmcl.download.forge.ForgeOldInstallTask;
import org.jackhuang.hmcl.download.game.GameAssetDownloadTask;
import org.jackhuang.hmcl.download.game.GameInstallTask;
import org.jackhuang.hmcl.download.java.JavaDownloadTask;
import org.jackhuang.hmcl.download.liteloader.LiteLoaderInstallTask;
import org.jackhuang.hmcl.download.optifine.OptiFineInstallTask;
import org.jackhuang.hmcl.game.HMCLModpackInstallTask;
@@ -148,6 +149,8 @@ public final class TaskListPane extends StackPane {
task.setName(i18n("modpack.export"));
} else if (task instanceof MinecraftInstanceTask) {
task.setName(i18n("modpack.scan"));
} else if (task instanceof JavaDownloadTask) {
task.setName(i18n("download.java"));
}
Platform.runLater(() -> {
@@ -243,6 +246,7 @@ public final class TaskListPane extends StackPane {
case "hmcl.install.optifine": message = i18n("install.installer.install", i18n("install.installer.optifine") + " " + stageValue); break;
case "hmcl.install.fabric": message = i18n("install.installer.install", i18n("install.installer.fabric") + " " + stageValue); break;
case "hmcl.install.fabric-api": message = i18n("install.installer.install", i18n("install.installer.fabric-api") + " " + stageValue); break;
case "hmcl.install.quilt": message = i18n("install.installer.install", i18n("install.installer.quilt") + " " + stageValue); break;
default: message = i18n(stageKey); break;
}
// @formatter:on
@@ -1,3 +1,20 @@
/*
* Hello Minecraft! Launcher
* Copyright (C) 2022 huangyuhui <huanghongxun2008@126.com> and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.jackhuang.hmcl.ui.construct;
import com.jfoenix.validation.base.ValidatorBase;
@@ -91,9 +91,11 @@ class AdditionalInstallersPage extends InstallersPage {
String optiFine = analyzer.getVersion(OPTIFINE).orElse(null);
String fabric = analyzer.getVersion(FABRIC).orElse(null);
String fabricApi = analyzer.getVersion(FABRIC_API).orElse(null);
String quilt = analyzer.getVersion(QUILT).orElse(null);
String quiltApi = analyzer.getVersion(QUILT_API).orElse(null);
InstallerItem[] libraries = group.getLibraries();
String[] versions = new String[]{game, forge, liteLoader, optiFine, fabric, fabricApi};
String[] versions = new String[]{game, forge, liteLoader, optiFine, fabric, fabricApi, quilt, quiltApi};
String currentGameVersion = Lang.nonNull(getVersion("game"), game);
@@ -29,14 +29,13 @@ import javafx.scene.control.Label;
import javafx.scene.control.Skin;
import javafx.scene.control.SkinBase;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import org.jackhuang.hmcl.download.DownloadProvider;
import org.jackhuang.hmcl.download.RemoteVersion;
import org.jackhuang.hmcl.game.HMCLGameRepository;
import org.jackhuang.hmcl.ui.Controllers;
import org.jackhuang.hmcl.ui.InstallerItem;
import org.jackhuang.hmcl.ui.construct.ComponentList;
import org.jackhuang.hmcl.ui.construct.MessageDialogPane;
import org.jackhuang.hmcl.ui.construct.RequiredValidator;
import org.jackhuang.hmcl.ui.construct.Validator;
@@ -67,6 +66,10 @@ public class InstallersPage extends Control implements WizardPage {
group.game.installable.setValue(false);
for (InstallerItem item : group.getLibraries()) {
item.setStyleMode(InstallerItem.Style.CARD);
}
for (InstallerItem library : group.getLibraries()) {
String libraryId = library.getLibraryId();
if (libraryId.equals("game")) continue;
@@ -140,22 +143,23 @@ public class InstallersPage extends Control implements WizardPage {
BorderPane root = new BorderPane();
root.setPadding(new Insets(16));
ComponentList list = new ComponentList();
list.getStyleClass().add("no-padding");
root.setCenter(list);
{
HBox versionNamePane = new HBox(8);
versionNamePane.getStyleClass().add("card-non-transparent");
versionNamePane.setStyle("-fx-padding: 20 8 20 16");
versionNamePane.setAlignment(Pos.CENTER_LEFT);
versionNamePane.setPadding(new Insets(20, 8, 20, 16));
control.txtName.setMaxWidth(300);
versionNamePane.getChildren().setAll(new Label(i18n("archive.name")), control.txtName);
list.getContent().add(versionNamePane);
root.setTop(versionNamePane);
}
{
VBox libraryPane = new VBox(control.group.getLibraries());
list.getContent().add(libraryPane);
FlowPane libraryPane = new FlowPane(control.group.getLibraries());
BorderPane.setMargin(libraryPane, new Insets(16, 0, 16, 0));
libraryPane.setVgap(16);
libraryPane.setHgap(16);
root.setCenter(libraryPane);
}
@@ -23,6 +23,7 @@ import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.scene.layout.StackPane;
import javafx.stage.FileChooser;
import org.jackhuang.hmcl.game.ModpackHelper;
import org.jackhuang.hmcl.mod.server.ServerModpackManifest;
import org.jackhuang.hmcl.task.FileDownloadTask;
import org.jackhuang.hmcl.task.GetTask;
@@ -33,7 +34,6 @@ import org.jackhuang.hmcl.ui.wizard.WizardController;
import org.jackhuang.hmcl.ui.wizard.WizardPage;
import org.jackhuang.hmcl.util.TaskCancellationAction;
import org.jackhuang.hmcl.util.gson.JsonUtils;
import org.jackhuang.hmcl.util.io.FileUtils;
import java.io.File;
import java.io.IOException;
@@ -67,7 +67,7 @@ public final class ModpackSelectionPage extends StackPane implements WizardPage
Platform.runLater(controller::onNext);
}
FXUtils.applyDragListener(this, it -> "zip".equals(FileUtils.getExtension(it)), modpacks -> {
FXUtils.applyDragListener(this, ModpackHelper::isFileModpackByExtension, modpacks -> {
File modpack = modpacks.get(0);
controller.getSettings().put(MODPACK_FILE, modpack);
controller.onNext();
@@ -78,7 +78,7 @@ public final class ModpackSelectionPage extends StackPane implements WizardPage
private void onChooseLocalFile() {
FileChooser chooser = new FileChooser();
chooser.setTitle(i18n("modpack.choose"));
chooser.getExtensionFilters().add(new FileChooser.ExtensionFilter(i18n("modpack"), "*.zip"));
chooser.getExtensionFilters().add(new FileChooser.ExtensionFilter(i18n("modpack"), "*.zip", "*.mrpack"));
File selectedFile = chooser.showOpenDialog(Controllers.getStage());
if (selectedFile == null) {
Platform.runLater(controller::onEnd);
@@ -96,7 +96,7 @@ public class AboutPage extends StackPane {
noin.setImage(new Image("/assets/img/noin.png", 32, 32, false, true));
noin.setTitle(i18n("about.thanks_to.noin"));
noin.setSubtitle(i18n("about.thanks_to.noin.statement"));
noin.setExternalLink("https://mcer.cn/");
noin.setExternalLink("https://mcer.cn/cato");
IconedTwoLineListItem contributors = new IconedTwoLineListItem();
contributors.setImage(new Image("/assets/img/github.png", 32, 32, false, true));
@@ -121,13 +121,13 @@ public class AboutPage extends StackPane {
discord.setSubtitle(i18n("about.community.discord.statement"));
discord.setExternalLink("https://discord.gg/jVvC7HfM6U");
IconedTwoLineListItem kaiheila = new IconedTwoLineListItem();
kaiheila.setImage(new Image("/assets/img/kaiheila.jpeg", 32, 32, false, true));
kaiheila.setTitle(i18n("about.community.kaiheila"));
kaiheila.setSubtitle(i18n("about.community.kaiheila.statement"));
kaiheila.setExternalLink("https://kaihei.co/Kx7n3t");
IconedTwoLineListItem kookapp = new IconedTwoLineListItem();
kookapp.setImage(new Image("/assets/img/kookapp.png", 32, 32, false, true));
kookapp.setTitle(i18n("about.community.kookapp"));
kookapp.setSubtitle(i18n("about.community.kookapp.statement"));
kookapp.setExternalLink("https://kook.top/Kx7n3t");
community.getContent().setAll(users, discord, kaiheila);
community.getContent().setAll(users, discord, kookapp);
}
ComponentList dep = new ComponentList();
@@ -53,10 +53,9 @@ public class DownloadSettingsPage extends StackPane {
getChildren().setAll(scrollPane);
{
ComponentList downloadSource = new ComponentList();
VBox downloadSource = new VBox(8);
downloadSource.getStyleClass().add("card-non-transparent");
{
VBox pane = new VBox(8);
VBox chooseWrapper = new VBox();
chooseWrapper.setPadding(new Insets(8, 0, 8, 0));
@@ -75,7 +74,7 @@ public class DownloadSettingsPage extends StackPane {
JFXComboBox<String> cboVersionListSource = new JFXComboBox<>();
cboVersionListSource.setConverter(stringConverter(key -> i18n("download.provider." + key)));
versionListSourcePane.setRight(cboVersionListSource);
FXUtils.setLimitWidth(cboVersionListSource, 420);
FXUtils.setLimitWidth(cboVersionListSource, 400);
cboVersionListSource.getItems().setAll(DownloadProviders.providersById.keySet());
selectedItemPropertyFor(cboVersionListSource).bindBidirectional(config().versionListSourceProperty());
@@ -91,31 +90,28 @@ public class DownloadSettingsPage extends StackPane {
JFXComboBox<String> cboDownloadSource = new JFXComboBox<>();
cboDownloadSource.setConverter(stringConverter(key -> i18n("download.provider." + key)));
downloadSourcePane.setRight(cboDownloadSource);
downloadSourcePane.setCenter(cboDownloadSource);
FXUtils.setLimitWidth(cboDownloadSource, 420);
cboDownloadSource.getItems().setAll(DownloadProviders.rawProviders.keySet());
selectedItemPropertyFor(cboDownloadSource).bindBidirectional(config().downloadTypeProperty());
}
pane.getChildren().setAll(chooseWrapper, versionListSourcePane, downloadSourcePane);
downloadSource.getContent().add(pane);
downloadSource.getChildren().setAll(chooseWrapper, versionListSourcePane, downloadSourcePane);
}
content.getChildren().addAll(ComponentList.createComponentListTitle(i18n("settings.launcher.version_list_source")), downloadSource);
}
{
ComponentList downloadThreads = new ComponentList();
VBox downloadThreads = new VBox(16);
downloadThreads.getStyleClass().add("card-non-transparent");
{
VBox pane = new VBox(16);
pane.setPadding(new Insets(8, 0, 8, 0));
{
JFXCheckBox chkAutoDownloadThreads = new JFXCheckBox(i18n("settings.launcher.download.threads.auto"));
VBox.setMargin(chkAutoDownloadThreads, new Insets(8, 0, 0, 0));
chkAutoDownloadThreads.selectedProperty().bindBidirectional(config().autoDownloadThreadsProperty());
pane.getChildren().add(chkAutoDownloadThreads);
downloadThreads.getChildren().add(chkAutoDownloadThreads);
chkAutoDownloadThreads.selectedProperty().addListener((a, b, newValue) -> {
if (newValue) {
@@ -150,7 +146,7 @@ public class DownloadSettingsPage extends StackPane {
});
hbox.getChildren().setAll(label, slider, threadsField);
pane.getChildren().add(hbox);
downloadThreads.getChildren().add(hbox);
}
{
@@ -158,26 +154,22 @@ public class DownloadSettingsPage extends StackPane {
VBox.setMargin(hintPane, new Insets(0, 0, 0, 30));
hintPane.disableProperty().bind(config().autoDownloadThreadsProperty());
hintPane.setText(i18n("settings.launcher.download.threads.hint"));
pane.getChildren().add(hintPane);
downloadThreads.getChildren().add(hintPane);
}
downloadThreads.getContent().add(pane);
}
content.getChildren().addAll(ComponentList.createComponentListTitle(i18n("download")), downloadThreads);
}
{
ComponentList proxyList = new ComponentList();
VBox proxyWrapper = new VBox();
proxyWrapper.setPadding(new Insets(8, 0, 8, 0));
proxyWrapper.setSpacing(10);
VBox proxyList = new VBox(10);
proxyList.getStyleClass().add("card-non-transparent");
VBox proxyPane = new VBox();
{
JFXCheckBox chkDisableProxy = new JFXCheckBox(i18n("settings.launcher.proxy.disable"));
proxyWrapper.getChildren().add(chkDisableProxy);
VBox.setMargin(chkDisableProxy, new Insets(8, 0, 0, 0));
proxyList.getChildren().add(chkDisableProxy);
reversedSelectedPropertyFor(chkDisableProxy).bindBidirectional(config().hasProxyProperty());
proxyPane.disableProperty().bind(chkDisableProxy.selectedProperty());
}
@@ -310,9 +302,8 @@ public class DownloadSettingsPage extends StackPane {
proxyPane.getChildren().add(authPane);
}
proxyWrapper.getChildren().add(proxyPane);
proxyList.getChildren().add(proxyPane);
}
proxyList.getContent().add(proxyWrapper);
content.getChildren().addAll(ComponentList.createComponentListTitle(i18n("settings.launcher.proxy")), proxyList);
}
@@ -34,6 +34,8 @@ import org.jackhuang.hmcl.ui.SVG;
import org.jackhuang.hmcl.ui.account.AccountAdvancedListItem;
import org.jackhuang.hmcl.ui.construct.AdvancedListBox;
import org.jackhuang.hmcl.ui.construct.AdvancedListItem;
import org.jackhuang.hmcl.ui.construct.JFXHyperlink;
import org.jackhuang.hmcl.ui.construct.MessageDialogPane;
import org.jackhuang.hmcl.ui.decorator.DecoratorAnimatedPage;
import org.jackhuang.hmcl.ui.decorator.DecoratorPage;
import org.jackhuang.hmcl.ui.download.ModpackInstallWizardProvider;
@@ -42,6 +44,7 @@ import org.jackhuang.hmcl.ui.versions.Versions;
import org.jackhuang.hmcl.upgrade.UpdateChecker;
import org.jackhuang.hmcl.util.TaskCancellationAction;
import org.jackhuang.hmcl.util.io.CompressingUtils;
import org.jackhuang.hmcl.util.io.JarUtils;
import org.jackhuang.hmcl.util.versioning.VersionNumber;
import java.io.File;
@@ -153,7 +156,18 @@ public class RootPage extends DecoratorAnimatedPage implements DecoratorPage {
multiplayerItem.setLeftGraphic(wrap(SVG::lan));
multiplayerItem.setActionButtonVisible(false);
multiplayerItem.setTitle(i18n("multiplayer"));
multiplayerItem.setOnAction(e -> Controllers.navigate(Controllers.getMultiplayerPage()));
if ("true".equalsIgnoreCase(JarUtils.getManifestAttribute("Enable-HiPer", "")))
multiplayerItem.setOnAction(e -> Controllers.navigate(Controllers.getMultiplayerPage()));
else {
JFXHyperlink link = new JFXHyperlink(i18n("multiplayer.hint.details"));
link.setOnAction(e -> FXUtils.openLink("https://hmcl.huangyuhui.net/api/redirect/multiplayer-migrate"));
multiplayerItem.setOnAction(e ->
Controllers.dialog(
new MessageDialogPane.Builder(i18n("multiplayer.hint"), null, MessageDialogPane.MessageType.INFO)
.addAction(link)
.ok(null)
.build()));
}
// sixth item in left sidebar
AdvancedListItem launcherSettingsItem = new AdvancedListItem();
@@ -1,153 +0,0 @@
/*
* Hello Minecraft! Launcher
* Copyright (C) 2022 huangyuhui <huanghongxun2008@126.com> and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.jackhuang.hmcl.ui.multiplayer;
import com.jfoenix.controls.JFXCheckBox;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import org.jackhuang.hmcl.auth.Account;
import org.jackhuang.hmcl.setting.Accounts;
import org.jackhuang.hmcl.ui.FXUtils;
import org.jackhuang.hmcl.ui.construct.*;
import org.jackhuang.hmcl.util.FutureCallback;
import java.util.Objects;
import java.util.Optional;
import static org.jackhuang.hmcl.ui.FXUtils.runInFX;
import static org.jackhuang.hmcl.util.i18n.I18n.i18n;
public class CreateMultiplayerRoomDialog extends DialogPane implements DialogAware {
private final FutureCallback<CreationRequest> callback;
private final LocalServerDetector lanServerDetectorThread;
private final BooleanProperty allowAllJoinRequests = new SimpleBooleanProperty(true);
private LocalServerDetector.PingResponse server;
CreateMultiplayerRoomDialog(FutureCallback<CreationRequest> callback) {
this.callback = callback;
setTitle(i18n("multiplayer.session.create"));
GridPane body = new GridPane();
body.setMaxWidth(500);
body.getColumnConstraints().addAll(new ColumnConstraints(), FXUtils.getColumnHgrowing());
body.setVgap(8);
body.setHgap(16);
body.setDisable(true);
setBody(body);
HintPane hintPane = new HintPane(MessageDialogPane.MessageType.INFO);
hintPane.setText(i18n("multiplayer.session.create.hint"));
GridPane.setColumnSpan(hintPane, 2);
body.addRow(0, hintPane);
Label nameField = new Label();
nameField.setText(Optional.ofNullable(Accounts.getSelectedAccount())
.map(Account::getUsername)
.map(username -> i18n("multiplayer.session.name.format", username))
.orElse(""));
body.addRow(1, new Label(i18n("multiplayer.session.create.name")), nameField);
Label portLabel = new Label(i18n("multiplayer.nat.testing"));
portLabel.setText(i18n("multiplayer.nat.testing"));
body.addRow(2, new Label(i18n("multiplayer.session.create.port")), portLabel);
JFXCheckBox allowAllJoinRequestsCheckBox = new JFXCheckBox(i18n("multiplayer.session.create.join.allow"));
allowAllJoinRequestsCheckBox.selectedProperty().bindBidirectional(allowAllJoinRequests);
GridPane.setColumnSpan(allowAllJoinRequestsCheckBox, 2);
body.addRow(3, allowAllJoinRequestsCheckBox);
setValid(false);
JFXHyperlink noinLink = new JFXHyperlink();
noinLink.setText("mcer.cn");
noinLink.setOnAction(e -> FXUtils.openLink("https://mcer.cn/circle/cato"));
setActions(warningLabel, noinLink, acceptPane, cancelButton);
lanServerDetectorThread = new LocalServerDetector(3);
lanServerDetectorThread.onDetectedLanServer().register(event -> {
runInFX(() -> {
if (event.getLanServer() != null && event.getLanServer().isValid()) {
nameField.setText(event.getLanServer().getMotd());
portLabel.setText(event.getLanServer().getAd().toString());
setValid(true);
} else {
nameField.setText("");
portLabel.setText("");
onFailure(i18n("multiplayer.session.create.port.error"));
setValid(false);
}
server = event.getLanServer();
body.setDisable(false);
getProgressBar().setVisible(false);
});
});
}
@Override
protected void onAccept() {
setLoading();
callback.call(new CreationRequest(
Objects.requireNonNull(server),
allowAllJoinRequests.get()
), () -> {
runInFX(this::onSuccess);
}, msg -> {
runInFX(() -> onFailure(msg));
});
}
@Override
public void onDialogShown() {
getProgressBar().setVisible(true);
getProgressBar().setProgress(ProgressIndicator.INDETERMINATE_PROGRESS);
lanServerDetectorThread.start();
}
@Override
public void onDialogClosed() {
lanServerDetectorThread.interrupt();
}
public static class CreationRequest {
private final LocalServerDetector.PingResponse server;
private final boolean allowAllJoinRequests;
public CreationRequest(LocalServerDetector.PingResponse server, boolean allowAllJoinRequests) {
this.server = server;
this.allowAllJoinRequests = allowAllJoinRequests;
}
public LocalServerDetector.PingResponse getServer() {
return server;
}
public boolean isAllowAllJoinRequests() {
return allowAllJoinRequests;
}
}
}
@@ -1,6 +1,6 @@
/*
* Hello Minecraft! Launcher
* Copyright (C) 2021 huangyuhui <huanghongxun2008@126.com> and contributors
* Copyright (C) 2022 huangyuhui <huanghongxun2008@126.com> and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -17,31 +17,110 @@
*/
package org.jackhuang.hmcl.ui.multiplayer;
import org.jackhuang.hmcl.event.Event;
import org.jackhuang.hmcl.event.EventManager;
import org.jackhuang.hmcl.util.Lang;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.*;
import java.nio.channels.UnresolvedAddressException;
import java.nio.charset.StandardCharsets;
import java.util.logging.Level;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.jackhuang.hmcl.util.Logging.LOG;
import static org.jackhuang.hmcl.util.i18n.I18n.i18n;
public class LocalServerBroadcaster implements Runnable {
private final int port;
private final MultiplayerManager.CatoSession session;
public class LocalServerBroadcaster implements AutoCloseable {
private final String address;
private final ThreadGroup threadGroup = new ThreadGroup("JoinSession");
public LocalServerBroadcaster(int port, MultiplayerManager.CatoSession session) {
this.port = port;
this.session = session;
private final EventManager<Event> onExit = new EventManager<>();
private boolean running = true;
public LocalServerBroadcaster(String address) {
this.address = address;
}
public int getPort() {
return port;
private Thread newThread(Runnable task, String name) {
Thread thread = new Thread(threadGroup, task, name);
thread.setDaemon(true);
return thread;
}
@Override
public void run() {
public void close() {
running = false;
threadGroup.interrupt();
}
public String getAddress() {
return address;
}
public EventManager<Event> onExit() {
return onExit;
}
public static final Pattern ADDRESS_PATTERN = Pattern.compile("^\\s*(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}):(\\d{1,5})\\s*$");
public void start() {
Thread forwardPortThread = newThread(this::forwardPort, "ForwardPort");
forwardPortThread.start();
}
private void forwardPort() {
try {
Matcher matcher = ADDRESS_PATTERN.matcher(address);
if (!matcher.find()) {
throw new MalformedURLException();
}
try (Socket forwardingSocket = new Socket();
ServerSocket serverSocket = new ServerSocket()) {
forwardingSocket.setSoTimeout(30000);
forwardingSocket.connect(new InetSocketAddress(matcher.group(1), Lang.parseInt(matcher.group(2), 0)));
serverSocket.bind(null);
Thread broadcastMOTDThread = newThread(() -> broadcastMOTD(serverSocket.getLocalPort()), "BroadcastMOTD");
broadcastMOTDThread.start();
LOG.log(Level.INFO, "Listening " + serverSocket.getLocalSocketAddress());
while (running) {
Socket forwardedSocket = serverSocket.accept();
LOG.log(Level.INFO, "Accepting client");
newThread(() -> forwardTraffic(forwardingSocket, forwardedSocket), "Forward S->D").start();
newThread(() -> forwardTraffic(forwardedSocket, forwardingSocket), "Forward D->S").start();
}
}
} catch (IOException | UnresolvedAddressException e) {
LOG.log(Level.WARNING, "Error in forwarding port", e);
} finally {
close();
onExit.fireEvent(new Event(this));
}
}
private void forwardTraffic(Socket src, Socket dest) {
try (InputStream is = src.getInputStream(); OutputStream os = dest.getOutputStream()) {
byte[] buf = new byte[1024];
while (true) {
int len = is.read(buf, 0, buf.length);
if (len < 0) break;
LOG.log(Level.INFO, "Forwarding buffer " + len);
os.write(buf, 0, len);
}
} catch (IOException e) {
LOG.log(Level.WARNING, "Disconnected", e);
}
}
private void broadcastMOTD(int port) {
DatagramSocket socket;
InetAddress broadcastAddress;
try {
@@ -52,9 +131,9 @@ public class LocalServerBroadcaster implements Runnable {
return;
}
while (session.isRunning()) {
while (running) {
try {
byte[] data = String.format("[MOTD]%s[/MOTD][AD]%d[/AD]", i18n("multiplayer.session.name.motd", session.getName()), port).getBytes(StandardCharsets.UTF_8);
byte[] data = String.format("[MOTD]%s[/MOTD][AD]%d[/AD]", i18n("multiplayer.session.name.motd"), port).getBytes(StandardCharsets.UTF_8);
DatagramPacket packet = new DatagramPacket(data, 0, data.length, broadcastAddress, 4445);
socket.send(packet);
LOG.finest("Broadcast server 0.0.0.0:" + port);
@@ -1,141 +0,0 @@
/*
* Hello Minecraft! Launcher
* Copyright (C) 2021 huangyuhui <huanghongxun2008@126.com> and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.jackhuang.hmcl.ui.multiplayer;
import org.jackhuang.hmcl.event.Event;
import org.jackhuang.hmcl.event.EventManager;
import org.jackhuang.hmcl.util.Lang;
import org.jackhuang.hmcl.util.StringUtils;
import java.io.IOException;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.logging.Level;
import static org.jackhuang.hmcl.util.Logging.LOG;
public class LocalServerDetector extends Thread {
private final EventManager<DetectedLanServerEvent> onDetectedLanServer = new EventManager<>();
private final int retry;
public LocalServerDetector(int retry) {
this.retry = retry;
setName("LocalServerDetector");
setDaemon(true);
}
public EventManager<DetectedLanServerEvent> onDetectedLanServer() {
return onDetectedLanServer;
}
@Override
public void run() {
MulticastSocket socket;
InetAddress broadcastAddress;
try {
socket = new MulticastSocket(4445);
socket.setSoTimeout(5000);
socket.joinGroup(broadcastAddress = InetAddress.getByName("224.0.2.60"));
} catch (IOException e) {
LOG.log(Level.WARNING, "Failed to create datagram socket", e);
return;
}
byte[] buf = new byte[1024];
int tried = 0;
while (!isInterrupted()) {
DatagramPacket packet = new DatagramPacket(buf, 1024);
try {
socket.receive(packet);
} catch (SocketTimeoutException e) {
if (tried++ > retry) {
onDetectedLanServer.fireEvent(new DetectedLanServerEvent(this, null));
break;
}
continue;
} catch (IOException e) {
LOG.log(Level.WARNING, "Failed to detect lan server", e);
break;
}
String response = new String(packet.getData(), packet.getOffset(), packet.getLength(), StandardCharsets.UTF_8);
LOG.fine("Local server " + packet.getAddress() + ":" + packet.getPort() + " broadcast message: " + response);
onDetectedLanServer.fireEvent(new DetectedLanServerEvent(this, PingResponse.parsePingResponse(response)));
break;
}
try {
socket.leaveGroup(broadcastAddress);
} catch (IOException e) {
LOG.log(Level.WARNING, "Failed to leave multicast listening group", e);
}
socket.close();
}
public static class DetectedLanServerEvent extends Event {
private final PingResponse lanServer;
public DetectedLanServerEvent(Object source, PingResponse lanServer) {
super(source);
this.lanServer = lanServer;
}
public PingResponse getLanServer() {
return lanServer;
}
}
public static class PingResponse {
private final String motd;
private final Integer ad;
public PingResponse(String motd, Integer ad) {
this.motd = motd;
this.ad = ad;
}
public String getMotd() {
return motd;
}
public Integer getAd() {
return ad;
}
public boolean isValid() {
return ad != null;
}
public static PingResponse parsePingResponse(String message) {
return new PingResponse(
StringUtils.substringBefore(
StringUtils.substringAfter(message, "[MOTD]"),
"[/MOTD]"),
Lang.toIntOrNull(StringUtils.substringBefore(
StringUtils.substringAfter(message, "[AD]"),
"[/AD]"))
);
}
}
}
@@ -1,154 +0,0 @@
/*
* Hello Minecraft! Launcher
* Copyright (C) 2021 huangyuhui <huanghongxun2008@126.com> and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.jackhuang.hmcl.ui.multiplayer;
import org.jackhuang.hmcl.event.Event;
import org.jackhuang.hmcl.util.gson.JsonSubtype;
import org.jackhuang.hmcl.util.gson.JsonType;
public final class MultiplayerChannel {
private MultiplayerChannel() {
}
@JsonType(
property = "type",
subtypes = {
@JsonSubtype(clazz = HandshakeRequest.class, name = "handshake"),
@JsonSubtype(clazz = JoinRequest.class, name = "join"),
@JsonSubtype(clazz = KeepAliveRequest.class, name = "keepalive")
}
)
public static class Request {
}
public static class HandshakeRequest extends Request {
}
public static class JoinRequest extends Request {
private final String clientVersion;
private final String username;
public JoinRequest(String clientVersion, String username) {
this.clientVersion = clientVersion;
this.username = username;
}
public String getClientVersion() {
return clientVersion;
}
public String getUsername() {
return username;
}
}
public static class KeepAliveRequest extends Request {
private final long timestamp;
public KeepAliveRequest(long timestamp) {
this.timestamp = timestamp;
}
public long getTimestamp() {
return timestamp;
}
}
@JsonType(
property = "type",
subtypes = {
@JsonSubtype(clazz = HandshakeResponse.class, name = "handshake"),
@JsonSubtype(clazz = JoinResponse.class, name = "join"),
@JsonSubtype(clazz = KeepAliveResponse.class, name = "keepalive"),
@JsonSubtype(clazz = KickResponse.class, name = "kick")
}
)
public static class Response {
}
public static class HandshakeResponse extends Response {
}
public static class JoinResponse extends Response {
private final String sessionName;
private final int port;
public JoinResponse(String sessionName, int port) {
this.sessionName = sessionName;
this.port = port;
}
public String getSessionName() {
return sessionName;
}
public int getPort() {
return port;
}
}
public static class KeepAliveResponse extends Response {
private final long timestamp;
public KeepAliveResponse(long timestamp) {
this.timestamp = timestamp;
}
public long getTimestamp() {
return timestamp;
}
}
public static class KickResponse extends Response {
private final String msg;
public KickResponse(String msg) {
this.msg = msg;
}
public String getMsg() {
return msg;
}
public static final String VERSION_NOT_MATCHED = "version_not_matched";
public static final String KICKED = "kicked";
public static final String JOIN_ACEEPTANCE_TIMEOUT = "join_acceptance_timeout";
}
public static class CatoClient extends Event {
private final String username;
public CatoClient(Object source, String username) {
super(source);
this.username = username;
}
public String getUsername() {
return username;
}
}
public static String verifyJson(String jsonString) {
if (jsonString.indexOf('\r') >= 0 || jsonString.indexOf('\n') >= 0) {
throw new IllegalArgumentException();
}
return jsonString;
}
}
@@ -1,227 +0,0 @@
/*
* Hello Minecraft! Launcher
* Copyright (C) 2021 huangyuhui <huanghongxun2008@126.com> and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.jackhuang.hmcl.ui.multiplayer;
import com.google.gson.JsonParseException;
import org.jackhuang.hmcl.event.Event;
import org.jackhuang.hmcl.event.EventManager;
import org.jackhuang.hmcl.util.Lang;
import org.jackhuang.hmcl.util.gson.JsonUtils;
import java.io.*;
import java.net.ConnectException;
import java.net.InetAddress;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.TimerTask;
import java.util.logging.Level;
import static org.jackhuang.hmcl.ui.multiplayer.MultiplayerChannel.*;
import static org.jackhuang.hmcl.util.Logging.LOG;
public class MultiplayerClient extends Thread {
private final String id;
private final int port;
private int gamePort;
private boolean connected = false;
private final EventManager<ConnectedEvent> onConnected = new EventManager<>();
private final EventManager<Event> onDisconnected = new EventManager<>();
private final EventManager<KickEvent> onKicked = new EventManager<>();
private final EventManager<Event> onHandshake = new EventManager<>();
public MultiplayerClient(String id, int port) {
this.id = id;
this.port = port;
setName("MultiplayerClient");
setDaemon(true);
}
public synchronized void setGamePort(int gamePort) {
this.gamePort = gamePort;
}
public synchronized int getGamePort() {
return gamePort;
}
public EventManager<ConnectedEvent> onConnected() {
return onConnected;
}
public EventManager<Event> onDisconnected() {
return onDisconnected;
}
public EventManager<KickEvent> onKicked() {
return onKicked;
}
public EventManager<Event> onHandshake() {
return onHandshake;
}
@Override
public void run() {
LOG.info("Connecting to 127.0.0.1:" + port);
for (int i = 0; i < 5; i++) {
KeepAliveThread keepAliveThread = null;
try (Socket socket = new Socket(InetAddress.getLoopbackAddress(), port);
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8))) {
MultiplayerServer.Endpoint endpoint = new MultiplayerServer.Endpoint(socket, writer);
socket.setSoTimeout(30000);
LOG.info("Connected to 127.0.0.1:" + port);
endpoint.write(new HandshakeRequest());
endpoint.write(new JoinRequest(MultiplayerManager.CATO_VERSION, id));
LOG.fine("Sent join request with id=" + id);
keepAliveThread = new KeepAliveThread(endpoint);
keepAliveThread.start();
TimerTask task = Lang.setTimeout(() -> {
// If after 15 seconds, we didn't receive the HandshakeResponse,
// We fail to establish the connection with server.
try {
LOG.log(Level.WARNING, "Socket connection timeout, closing socket");
socket.close();
} catch (IOException e) {
LOG.log(Level.WARNING, "Failed to close socket", e);
}
}, 25 * 1000);
String line;
while ((line = reader.readLine()) != null) {
if (isInterrupted()) {
return;
}
LOG.fine("Message from server:" + line);
Response response = JsonUtils.fromNonNullJson(line, Response.class);
if (response instanceof JoinResponse) {
JoinResponse joinResponse = JsonUtils.fromNonNullJson(line, JoinResponse.class);
setGamePort(joinResponse.getPort());
connected = true;
onConnected.fireEvent(new ConnectedEvent(this, joinResponse.getSessionName(), joinResponse.getPort()));
LOG.fine("Received join response with port " + joinResponse.getPort());
} else if (response instanceof KickResponse) {
LOG.fine("Kicked by the server");
onKicked.fireEvent(new KickEvent(this, ((KickResponse) response).getMsg()));
return;
} else if (response instanceof KeepAliveResponse) {
} else if (response instanceof HandshakeResponse) {
LOG.fine("Established connection with server");
onHandshake.fireEvent(new Event(this));
task.cancel();
} else {
LOG.log(Level.WARNING, "Unrecognized packet from server:" + line);
}
}
} catch (ConnectException e) {
LOG.info("Failed to connect to 127.0.0.1:" + port + ", tried " + i + " time(s)");
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
LOG.warning("MultiplayerClient interrupted");
return;
}
continue;
} catch (IOException | JsonParseException e) {
e.printStackTrace();
} finally {
if (keepAliveThread != null) {
keepAliveThread.interrupt();
}
}
}
LOG.info("Lost connection to 127.0.0.1:" + port);
onDisconnected.fireEvent(new Event(this));
}
public boolean isConnected() {
return connected;
}
private static class KeepAliveThread extends Thread {
private final MultiplayerServer.Endpoint endpoint;
public KeepAliveThread(MultiplayerServer.Endpoint endpoint) {
this.endpoint = endpoint;
}
@Override
public void run() {
while (!isInterrupted()) {
try {
endpoint.write(new KeepAliveRequest(System.currentTimeMillis()));
} catch (IOException e) {
LOG.log(Level.WARNING, "Failed to send keep alive packet", e);
break;
}
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
break;
}
}
}
}
public static class ConnectedEvent extends Event {
private final String sessionName;
private final int port;
public ConnectedEvent(Object source, String sessionName, int port) {
super(source);
this.sessionName = sessionName;
this.port = port;
}
public String getSessionName() {
return sessionName;
}
public int getPort() {
return port;
}
}
public static class KickEvent extends Event {
private final String reason;
public KickEvent(Object source, String reason) {
super(source);
this.reason = reason;
}
public String getReason() {
return reason;
}
}
}
@@ -18,474 +18,442 @@
package org.jackhuang.hmcl.ui.multiplayer;
import com.google.gson.JsonParseException;
import com.google.gson.annotations.SerializedName;
import javafx.application.Platform;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.BooleanBinding;
import org.jackhuang.hmcl.Metadata;
import org.jackhuang.hmcl.event.Event;
import org.jackhuang.hmcl.event.EventManager;
import org.jackhuang.hmcl.setting.ConfigHolder;
import org.jackhuang.hmcl.task.FileDownloadTask;
import org.jackhuang.hmcl.task.Task;
import org.jackhuang.hmcl.ui.Controllers;
import org.jackhuang.hmcl.ui.FXUtils;
import org.jackhuang.hmcl.util.Lang;
import org.jackhuang.hmcl.util.StringUtils;
import org.jackhuang.hmcl.util.io.ChecksumMismatchException;
import org.jackhuang.hmcl.util.*;
import org.jackhuang.hmcl.util.gson.JsonUtils;
import org.jackhuang.hmcl.util.io.FileUtils;
import org.jackhuang.hmcl.util.io.HttpRequest;
import org.jackhuang.hmcl.util.io.NetworkUtils;
import org.jackhuang.hmcl.util.platform.Architecture;
import org.jackhuang.hmcl.util.platform.CommandBuilder;
import org.jackhuang.hmcl.util.platform.ManagedProcess;
import org.jackhuang.hmcl.util.platform.OperatingSystem;
import org.jetbrains.annotations.Nullable;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.*;
import java.nio.file.attribute.PosixFilePermission;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import java.util.concurrent.TimeUnit;
import java.util.function.BiFunction;
import java.util.logging.Level;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.jackhuang.hmcl.util.Lang.wrap;
import static org.jackhuang.hmcl.setting.ConfigHolder.globalConfig;
import static org.jackhuang.hmcl.util.Lang.*;
import static org.jackhuang.hmcl.util.Logging.LOG;
import static org.jackhuang.hmcl.util.Pair.pair;
import static org.jackhuang.hmcl.util.i18n.I18n.i18n;
import static org.jackhuang.hmcl.util.io.ChecksumMismatchException.verifyChecksum;
/**
* Cato Management.
*/
public final class MultiplayerManager {
static final String CATO_VERSION = "1.2.2";
private static final String CATO_DOWNLOAD_URL = "https://gitcode.net/to/cato/-/raw/master/client/";
private static final String CATO_HASH_URL = CATO_DOWNLOAD_URL + "cato-all-files.sha1";
private static final String CATO_PATH = getCatoPath();
public static final int CATO_AGREEMENT_VERSION = 2;
// static final String HIPER_VERSION = "1.2.2";
private static final String HIPER_DOWNLOAD_URL = "https://gitcode.net/to/hiper/-/raw/master/";
private static final String HIPER_PACKAGES_URL = HIPER_DOWNLOAD_URL + "packages.sha1";
private static final String HIPER_POINTS_URL = "https://cert.mcer.cn/point.yml";
private static final Path HIPER_TEMP_CONFIG_PATH = Metadata.HMCL_DIRECTORY.resolve("hiper.yml");
private static final Path HIPER_CONFIG_DIR = Metadata.HMCL_DIRECTORY.resolve("hiper-config");
public static final Path HIPER_PATH = getHiperLocalDirectory().resolve(getHiperFileName());
public static final int HIPER_AGREEMENT_VERSION = 3;
private static final String REMOTE_ADDRESS = "127.0.0.1";
private static final String LOCAL_ADDRESS = "0.0.0.0";
private static final Map<Architecture, String> archMap = mapOf(
pair(Architecture.ARM32, "arm-7"),
pair(Architecture.ARM64, "arm64"),
pair(Architecture.X86, "386"),
pair(Architecture.X86_64, "amd64"),
pair(Architecture.LOONGARCH64, "loong64"),
pair(Architecture.MIPS, "mips"),
pair(Architecture.MIPS64, "mips64"),
pair(Architecture.MIPS64EL, "mips64le"),
pair(Architecture.PPC64LE, "ppc64le"),
pair(Architecture.RISCV64, "riscv64"),
pair(Architecture.MIPSEL, "mipsle")
);
private static final Map<OperatingSystem, String> osMap = mapOf(
pair(OperatingSystem.LINUX, "linux"),
pair(OperatingSystem.WINDOWS, "windows"),
pair(OperatingSystem.OSX, "darwin")
);
private static final String HIPER_TARGET_NAME = String.format("%s-%s",
osMap.getOrDefault(OperatingSystem.CURRENT_OS, "windows"),
archMap.getOrDefault(Architecture.SYSTEM_ARCH, "amd64"));
private static final String GSUDO_VERSION = "1.7.1";
private static final String GSUDO_TARGET_ARCH = Architecture.SYSTEM_ARCH == Architecture.X86_64 ? "amd64" : "x86";
private static final String GSUDO_FILE_NAME = "gsudo.exe";
private static final String GSUDO_DOWNLOAD_URL = "https://gitcode.net/glavo/gsudo-release/-/raw/75c952ea3afe8792b0db4fe9bab87d41b21e5895/" + GSUDO_TARGET_ARCH + "/" + GSUDO_FILE_NAME;
private static final Path GSUDO_LOCAL_FILE = Metadata.HMCL_DIRECTORY.resolve("libraries").resolve("gsudo").resolve("gsudo").resolve(GSUDO_VERSION).resolve(GSUDO_TARGET_ARCH).resolve(GSUDO_FILE_NAME);
private static final boolean USE_GSUDO;
static final boolean IS_ADMINISTRATOR;
static final BooleanBinding tokenInvalid = Bindings.createBooleanBinding(
() -> {
String token = globalConfig().multiplayerTokenProperty().getValue();
return token == null || token.isEmpty() || !StringUtils.isAlphabeticOrNumber(token);
},
globalConfig().multiplayerTokenProperty());
private static final DateFormat HIPER_VALID_TIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
static {
boolean isAdministrator = false;
if (OperatingSystem.CURRENT_OS == OperatingSystem.WINDOWS) {
try {
Process process = Runtime.getRuntime().exec(new String[]{"net.exe", "session"});
if (!process.waitFor(1, TimeUnit.SECONDS)) {
process.destroy();
} else {
isAdministrator = process.exitValue() == 0;
}
} catch (Throwable ignored) {
}
USE_GSUDO = !isAdministrator && OperatingSystem.SYSTEM_BUILD_NUMBER >= 10000;
} else {
isAdministrator = "root".equals(System.getProperty("user.name"));
USE_GSUDO = false;
}
IS_ADMINISTRATOR = isAdministrator;
}
private static CompletableFuture<Map<String, String>> HASH;
private MultiplayerManager() {
}
private static CompletableFuture<Map<String, String>> getCatoHash() {
public static Path getConfigPath(String token) {
return HIPER_CONFIG_DIR.resolve(Hex.encodeHex(DigestUtils.digest("SHA-1", token)) + ".yml");
}
public static void clearConfiguration() {
try {
Files.deleteIfExists(HIPER_TEMP_CONFIG_PATH);
Files.deleteIfExists(getConfigPath(ConfigHolder.globalConfig().getMultiplayerToken()));
} catch (IOException e) {
LOG.log(Level.WARNING, "Failed to delete config", e);
}
}
private static CompletableFuture<Map<String, String>> getPackagesHash() {
FXUtils.checkFxUserThread();
if (HASH == null) {
HASH = CompletableFuture.supplyAsync(wrap(() -> {
String hashList = HttpRequest.GET(CATO_HASH_URL).getString();
String hashList = HttpRequest.GET(HIPER_PACKAGES_URL).getString();
Map<String, String> hashes = new HashMap<>();
for (String line : hashList.split("\n")) {
String[] items = line.trim().split(" ");
String[] items = line.trim().split(" {2}");
if (items.length == 2 && items[0].length() == 40) {
hashes.put(items[1], items[0]);
} else {
LOG.warning("Failed to parse cato hash file, hash line " + line);
LOG.warning("Failed to parse Hiper packages.sha1 file, line: " + line);
}
}
if (USE_GSUDO) {
hashes.put(GSUDO_FILE_NAME, HttpRequest.GET(GSUDO_DOWNLOAD_URL + ".sha1").getString().trim());
}
return hashes;
}));
}
return HASH;
}
public static Task<Void> downloadCato() {
return Task.fromCompletableFuture(getCatoHash()).thenComposeAsync(catoHashes ->
new FileDownloadTask(
NetworkUtils.toURL(CATO_DOWNLOAD_URL + getCatoFileName()),
getCatoExecutable().toFile(),
catoHashes.get(getCatoFileName()) == null ? null : new FileDownloadTask.IntegrityCheck("SHA-1", catoHashes.get(getCatoFileName()))
).thenRunAsync(() -> {
if (OperatingSystem.CURRENT_OS == OperatingSystem.LINUX || OperatingSystem.CURRENT_OS == OperatingSystem.OSX) {
Set<PosixFilePermission> perm = Files.getPosixFilePermissions(getCatoExecutable());
perm.add(PosixFilePermission.OWNER_EXECUTE);
Files.setPosixFilePermissions(getCatoExecutable(), perm);
}
}));
}
public static Task<Void> downloadHiper() {
return Task.fromCompletableFuture(getPackagesHash()).thenComposeAsync(packagesHash -> {
public static Path getCatoExecutable() {
return Metadata.HMCL_DIRECTORY.resolve("libraries").resolve(CATO_PATH);
}
BiFunction<String, String, FileDownloadTask> getFileDownloadTask = (String remotePath, String localFileName) -> {
String hash = packagesHash.get(remotePath);
return new FileDownloadTask(
NetworkUtils.toURL(String.format("%s%s", HIPER_DOWNLOAD_URL, remotePath)),
getHiperLocalDirectory().resolve(localFileName).toFile(),
hash == null ? null : new FileDownloadTask.IntegrityCheck("SHA-1", hash));
};
private static CompletableFuture<CatoSession> startCato(String token, State state) {
return getCatoHash().thenApplyAsync(wrap(catoHashes -> {
Path exe = getCatoExecutable();
if (!Files.isRegularFile(exe)) {
throw new CatoNotExistsException(exe);
}
if (!isPortAvailable(3478)) {
throw new CatoAlreadyStartedException();
}
try {
String hash = catoHashes.get(getCatoFileName());
if (hash != null) {
ChecksumMismatchException.verifyChecksum(exe, "SHA-1", hash);
List<Task<?>> tasks;
if (OperatingSystem.CURRENT_OS == OperatingSystem.WINDOWS) {
if (!packagesHash.containsKey(String.format("%s/hiper.exe", HIPER_TARGET_NAME))) {
throw new HiperUnsupportedPlatformException();
}
tasks = new ArrayList<>(4);
tasks.add(getFileDownloadTask.apply(String.format("%s/hiper.exe", HIPER_TARGET_NAME), "hiper.exe"));
tasks.add(getFileDownloadTask.apply(String.format("%s/wintun.dll", HIPER_TARGET_NAME), "wintun.dll"));
// tasks.add(getFileDownloadTask.apply("tap-windows-9.21.2.exe", "tap-windows-9.21.2.exe"));
if (USE_GSUDO)
tasks.add(new FileDownloadTask(
NetworkUtils.toURL(GSUDO_DOWNLOAD_URL),
GSUDO_LOCAL_FILE.toFile(),
new FileDownloadTask.IntegrityCheck("SHA-1", packagesHash.get(GSUDO_FILE_NAME))
));
} else {
if (!packagesHash.containsKey(String.format("%s/hiper", HIPER_TARGET_NAME))) {
throw new HiperUnsupportedPlatformException();
}
tasks = Collections.singletonList(getFileDownloadTask.apply(String.format("%s/hiper", HIPER_TARGET_NAME), "hiper"));
}
return Task.allOf(tasks).thenRunAsync(() -> {
if (OperatingSystem.CURRENT_OS == OperatingSystem.LINUX || OperatingSystem.CURRENT_OS == OperatingSystem.OSX) {
Set<PosixFilePermission> perm = Files.getPosixFilePermissions(HIPER_PATH);
perm.add(PosixFilePermission.OWNER_EXECUTE);
Files.setPosixFilePermissions(HIPER_PATH, perm);
}
});
});
}
public static void downloadHiperConfig(String token, Path configPath) throws IOException {
String certFileContent = HttpRequest.GET(String.format("https://cert.mcer.cn/%s.yml", token)).getString();
if (!certFileContent.equals("")) {
FileUtils.writeText(configPath, certFileContent);
}
}
public static CompletableFuture<HiperSession> startHiper(String token) {
return getPackagesHash().thenComposeAsync(packagesHash -> {
CompletableFuture<Void> future = new CompletableFuture<>();
try {
if (OperatingSystem.CURRENT_OS == OperatingSystem.WINDOWS) {
verifyChecksum(getHiperLocalDirectory().resolve("hiper.exe"), "SHA-1", packagesHash.get(String.format("%s/hiper.exe", HIPER_TARGET_NAME)));
verifyChecksum(getHiperLocalDirectory().resolve("wintun.dll"), "SHA-1", packagesHash.get(String.format("%s/wintun.dll", HIPER_TARGET_NAME)));
// verifyChecksumAndDeleteIfNotMatched(getHiperLocalDirectory().resolve("tap-windows-9.21.2.exe"), packagesHash.get("tap-windows-9.21.2.exe"));
if (USE_GSUDO)
verifyChecksum(GSUDO_LOCAL_FILE, "SHA-1", packagesHash.get(GSUDO_FILE_NAME));
} else {
verifyChecksum(getHiperLocalDirectory().resolve("hiper"), "SHA-1", packagesHash.get(String.format("%s/hiper", HIPER_TARGET_NAME)));
}
future.complete(null);
} catch (IOException e) {
Files.deleteIfExists(exe);
throw e;
LOG.log(Level.WARNING, "Failed to verify HiPer files", e);
Platform.runLater(() -> Controllers.taskDialog(MultiplayerManager.downloadHiper()
.whenComplete(exception -> {
if (exception == null)
future.complete(null);
else
future.completeExceptionally(exception);
}), i18n("multiplayer.download"), TaskCancellationAction.NORMAL));
}
return future;
}).thenApplyAsync(wrap(ignored -> {
Path configPath = getConfigPath(token);
Files.createDirectories(configPath.getParent());
// 下载 HiPer 配置文件
Logging.registerForbiddenToken(token, "<hiper token>");
try {
downloadHiperConfig(token, configPath);
} catch (IOException e) {
LOG.log(Level.WARNING, "configuration file cloud cache token has been not available, try to use the local configuration file", e);
}
if (Files.exists(configPath)) {
Files.copy(configPath, HIPER_TEMP_CONFIG_PATH, StandardCopyOption.REPLACE_EXISTING);
try (BufferedWriter output = Files.newBufferedWriter(HIPER_TEMP_CONFIG_PATH, StandardOpenOption.WRITE, StandardOpenOption.APPEND)) {
output.write("\n");
output.write("logging:\n");
output.write(" format: json\n");
output.write(" file_path: '" + Metadata.HMCL_DIRECTORY.resolve("logs").resolve("hiper.log").toString().replace("'", "''") + "'\n");
}
}
String[] commands = new String[]{HIPER_PATH.toString(), "-config", HIPER_TEMP_CONFIG_PATH.toString()};
if (!IS_ADMINISTRATOR) {
switch (OperatingSystem.CURRENT_OS) {
case WINDOWS:
if (USE_GSUDO)
commands = new String[]{GSUDO_LOCAL_FILE.toString(), HIPER_PATH.toString(), "-config", HIPER_TEMP_CONFIG_PATH.toString()};
break;
case LINUX:
String askpass = System.getProperty("hmcl.askpass", System.getenv("HMCL_ASKPASS"));
if ("user".equalsIgnoreCase(askpass))
commands = new String[]{"sudo", "-A", HIPER_PATH.toString(), "-config", HIPER_TEMP_CONFIG_PATH.toString()};
else if ("false".equalsIgnoreCase(askpass))
commands = new String[]{"sudo", "--non-interactive", HIPER_PATH.toString(), "-config", HIPER_TEMP_CONFIG_PATH.toString()};
else {
if (Files.exists(Paths.get("/usr/bin/pkexec")))
commands = new String[]{"/usr/bin/pkexec", HIPER_PATH.toString(), "-config", HIPER_TEMP_CONFIG_PATH.toString()};
else
commands = new String[]{"sudo", "--non-interactive", HIPER_PATH.toString(), "-config", HIPER_TEMP_CONFIG_PATH.toString()};
}
break;
case OSX:
commands = new String[]{"sudo", "--non-interactive", HIPER_PATH.toString(), "-config", HIPER_TEMP_CONFIG_PATH.toString()};
break;
}
}
String[] commands = StringUtils.isBlank(token)
? new String[]{exe.toString()}
: new String[]{exe.toString(), "-auth.token", token};
Process process = new ProcessBuilder()
.command(commands)
.start();
return new CatoSession(state, process, Arrays.asList(commands));
return new HiperSession(process, Arrays.asList(commands));
}));
}
public static CompletableFuture<CatoSession> joinSession(String token, String peer, Mode mode, int remotePort, int localPort, JoinSessionHandler handler) throws IncompatibleCatoVersionException {
LOG.info(String.format("Joining session (token=%s,peer=%s,mode=%s,remotePort=%d,localPort=%d)", token, peer, mode, remotePort, localPort));
return startCato(token, State.SLAVE).thenComposeAsync(wrap(session -> {
CompletableFuture<CatoSession> future = new CompletableFuture<>();
session.forwardPort(peer, LOCAL_ADDRESS, localPort, REMOTE_ADDRESS, remotePort, mode);
Consumer<CatoExitEvent> onExit = event -> {
boolean ready = session.isReady();
switch (event.getExitCode()) {
case 1:
if (!ready) {
future.completeExceptionally(new CatoExitTimeoutException());
}
break;
}
future.completeExceptionally(new CatoExitException(event.getExitCode(), ready));
};
session.onExit.register(onExit);
TimerTask peerConnectionTimeoutTask = Lang.setTimeout(() -> {
future.completeExceptionally(new PeerConnectionTimeoutException());
session.stop();
}, 15 * 1000);
session.onPeerConnected.register(event -> {
peerConnectionTimeoutTask.cancel();
MultiplayerClient client = new MultiplayerClient(session.getId(), localPort);
session.addRelatedThread(client);
session.setClient(client);
TimerTask task = Lang.setTimeout(() -> {
Platform.runLater(() -> future.completeExceptionally(new JoinRequestTimeoutException()));
session.stop();
}, 30 * 1000);
client.onConnected().register(connectedEvent -> {
try {
int port = findAvailablePort();
session.forwardPort(peer, LOCAL_ADDRESS, port, REMOTE_ADDRESS, connectedEvent.getPort(), mode);
session.addRelatedThread(Lang.thread(new LocalServerBroadcaster(port, session), "LocalServerBroadcaster", true));
session.setName(connectedEvent.getSessionName());
client.setGamePort(port);
Platform.runLater(() -> {
session.onExit.unregister(onExit);
future.complete(session);
});
} catch (IOException e) {
session.stop();
Platform.runLater(() -> future.completeExceptionally(e));
}
task.cancel();
});
client.onKicked().register(kickedEvent -> {
session.stop();
task.cancel();
Platform.runLater(() -> {
future.completeExceptionally(new KickedException(kickedEvent.getReason()));
});
});
client.onDisconnected().register(disconnectedEvent -> {
Platform.runLater(() -> {
if (!client.isConnected()) {
// We fail to establish connection with server
future.completeExceptionally(new ConnectionErrorException());
}
});
});
client.onHandshake().register(handshakeEvent -> {
if (handler != null) {
handler.onWaitingForJoinResponse();
}
});
client.start();
});
return future;
}));
}
public static CompletableFuture<CatoSession> createSession(String token, String sessionName, int gamePort, boolean allowAllJoinRequests) {
LOG.info(String.format("Creating session (token=%s,sessionName=%s,gamePort=%d)", token, sessionName, gamePort));
return startCato(token, State.MASTER).thenComposeAsync(wrap(session -> {
CompletableFuture<CatoSession> future = new CompletableFuture<>();
MultiplayerServer server = new MultiplayerServer(sessionName, gamePort, allowAllJoinRequests);
server.startServer();
session.setName(sessionName);
session.allowForwardingAddress(REMOTE_ADDRESS, server.getPort());
session.allowForwardingAddress(REMOTE_ADDRESS, gamePort);
session.showAllowedAddress();
Consumer<CatoExitEvent> onExit = event -> {
boolean ready = session.isReady();
switch (event.getExitCode()) {
case 1:
if (!ready) {
future.completeExceptionally(new CatoExitTimeoutException());
}
break;
}
future.completeExceptionally(new CatoExitException(event.getExitCode(), ready));
};
session.onExit.register(onExit);
session.setServer(server);
session.addRelatedThread(server);
TimerTask peerConnectionTimeoutTask = Lang.setTimeout(() -> {
future.completeExceptionally(new PeerConnectionTimeoutException());
session.stop();
}, 15 * 1000);
session.onPeerConnected.register(event -> {
peerConnectionTimeoutTask.cancel();
Platform.runLater(() -> {
session.onExit.unregister(onExit);
future.complete(session);
});
});
return future;
}));
}
public static final Pattern INVITATION_CODE_PATTERN = Pattern.compile("^(?<id>.*?)#(?<port>\\d{2,5})$");
public static Invitation parseInvitationCode(String invitationCode) throws JsonParseException {
Matcher matcher = INVITATION_CODE_PATTERN.matcher(invitationCode);
if (!matcher.find()) throw new IllegalArgumentException("Invalid invitation code");
return new Invitation(matcher.group("id"), Integer.parseInt(matcher.group("port")));
}
public static int findAvailablePort() throws IOException {
try (ServerSocket socket = new ServerSocket(0)) {
return socket.getLocalPort();
public static String getHiperFileName() {
if (OperatingSystem.CURRENT_OS == OperatingSystem.WINDOWS) {
return "hiper.exe";
} else {
return "hiper";
}
}
public static boolean isPortAvailable(int port) {
try (ServerSocket socket = new ServerSocket(port)) {
return true;
} catch (IOException e) {
return false;
}
public static Path getHiperLocalDirectory() {
return Metadata.HMCL_DIRECTORY.resolve("libraries").resolve("hiper").resolve("hiper").resolve("binary");
}
private static String getCatoFileName() {
switch (OperatingSystem.CURRENT_OS) {
case WINDOWS:
if (Architecture.SYSTEM_ARCH == Architecture.X86_64) {
return "cato-client-windows-amd64.exe";
} else if (Architecture.SYSTEM_ARCH == Architecture.ARM64) {
return "cato-client-windows-arm64.exe";
} else if (Architecture.SYSTEM_ARCH == Architecture.X86) {
return "cato-client-windows-i386.exe";
} else {
return "";
}
case OSX:
if (Architecture.SYSTEM_ARCH == Architecture.X86_64) {
return "cato-client-darwin-amd64";
} else if (Architecture.SYSTEM_ARCH == Architecture.ARM64) {
return "cato-client-darwin-arm64";
} else {
return "";
}
case LINUX:
if (Architecture.SYSTEM_ARCH == Architecture.X86_64) {
return "cato-client-linux-amd64";
} else if (Architecture.SYSTEM_ARCH == Architecture.ARM32) {
return "cato-client-linux-arm7";
} else if (Architecture.SYSTEM_ARCH == Architecture.ARM64) {
return "cato-client-linux-arm64";
} else {
return "";
}
default:
return "";
}
}
public static String getCatoPath() {
String name = getCatoFileName();
if (StringUtils.isBlank(name)) return "";
return "cato/cato/" + MultiplayerManager.CATO_VERSION + "/" + name;
}
public static class CatoSession extends ManagedProcess {
private final EventManager<CatoExitEvent> onExit = new EventManager<>();
private final EventManager<CatoIdEvent> onIdGenerated = new EventManager<>();
private final EventManager<Event> onPeerConnected = new EventManager<>();
private String name;
private final State type;
private String id;
private boolean peerConnected = false;
private MultiplayerClient client;
private MultiplayerServer server;
public static class HiperSession extends ManagedProcess {
private final EventManager<HiperExitEvent> onExit = new EventManager<>();
private final EventManager<HiperIPEvent> onIPAllocated = new EventManager<>();
private final EventManager<HiperShowValidUntilEvent> onValidUntil = new EventManager<>();
private final BufferedWriter writer;
private int error = 0;
CatoSession(State type, Process process, List<String> commands) {
HiperSession(Process process, List<String> commands) {
super(process, commands);
Runtime.getRuntime().addShutdownHook(new Thread(this::stop));
LOG.info("Started cato with command: " + new CommandBuilder().addAll(commands));
LOG.info("Started hiper with command: " + new CommandBuilder().addAll(commands));
this.type = type;
addRelatedThread(Lang.thread(this::waitFor, "CatoExitWaiter", true));
pumpInputStream(this::checkCatoLog);
pumpErrorStream(this::checkCatoLog);
addRelatedThread(Lang.thread(this::waitFor, "HiperExitWaiter", true));
pumpInputStream(this::onLog);
pumpErrorStream(this::onLog);
writer = new BufferedWriter(new OutputStreamWriter(process.getOutputStream(), StandardCharsets.UTF_8));
}
public synchronized MultiplayerClient getClient() {
return client;
}
private void onLog(String log) {
if (!log.startsWith("{")) {
LOG.warning("[HiPer] " + log);
public synchronized CatoSession setClient(MultiplayerClient client) {
this.client = client;
return this;
}
public MultiplayerServer getServer() {
return server;
}
public CatoSession setServer(MultiplayerServer server) {
this.server = server;
return this;
}
private void checkCatoLog(String log) {
LOG.info("Cato: " + log);
if (id == null) {
Matcher matcher = TEMP_TOKEN_PATTERN.matcher(log);
if (matcher.find()) {
id = matcher.group("id");
onIdGenerated.fireEvent(new CatoIdEvent(this, id));
if (log.startsWith("failed to load config"))
error = HiperExitEvent.INVALID_CONFIGURATION;
else if (log.startsWith("sudo: ") || log.startsWith("Error getting authority") || log.startsWith("Error: An error occurred trying to start process"))
error = HiperExitEvent.NO_SUDO_PRIVILEGES;
else if (log.startsWith("Failed to write to log, can't rename log file")) {
error = HiperExitEvent.NO_SUDO_PRIVILEGES;
stop();
}
return;
}
if (!peerConnected) {
Matcher matcher = PEER_CONNECTED_PATTERN.matcher(log);
if (matcher.find()) {
peerConnected = true;
onPeerConnected.fireEvent(new Event(this));
try {
Map<?, ?> logJson = JsonUtils.fromNonNullJson(log, Map.class);
String msg = "";
if (logJson.containsKey("msg")) {
msg = tryCast(logJson.get("msg"), String.class).orElse("");
if (msg.contains("Failed to get a tun/tap device")) {
error = HiperExitEvent.FAILED_GET_DEVICE;
}
if (msg.contains("Failed to load certificate from config")) {
error = HiperExitEvent.FAILED_LOAD_CONFIG;
}
if (msg.contains("Validity of client certificate")) {
Optional<String> validUntil = tryCast(logJson.get("valid"), String.class);
if (validUntil.isPresent()) {
try {
synchronized (HIPER_VALID_TIME_FORMAT) {
Date date = HIPER_VALID_TIME_FORMAT.parse(validUntil.get());
onValidUntil.fireEvent(new HiperShowValidUntilEvent(this, date));
}
} catch (JsonParseException | ParseException e) {
LOG.log(Level.WARNING, "Failed to parse certification expire time string: " + validUntil.get());
}
}
}
}
if (logJson.containsKey("network")) {
Map<?, ?> network = tryCast(logJson.get("network"), Map.class).orElse(Collections.emptyMap());
if (network.containsKey("IP") && msg.contains("Main HostMap created")) {
Optional<String> ip = tryCast(network.get("IP"), String.class);
ip.ifPresent(s -> onIPAllocated.fireEvent(new HiperIPEvent(this, s)));
}
}
} catch (JsonParseException e) {
LOG.log(Level.WARNING, "Failed to parse hiper log: " + log, e);
}
}
private void waitFor() {
try {
int exitCode = getProcess().waitFor();
LOG.info("cato exited with exitcode " + exitCode);
onExit.fireEvent(new CatoExitEvent(this, exitCode));
LOG.info("Hiper exited with exitcode " + exitCode);
if (error != 0) {
onExit.fireEvent(new HiperExitEvent(this, error));
} else {
onExit.fireEvent(new HiperExitEvent(this, exitCode));
}
} catch (InterruptedException e) {
onExit.fireEvent(new CatoExitEvent(this, CatoExitEvent.EXIT_CODE_INTERRUPTED));
onExit.fireEvent(new HiperExitEvent(this, HiperExitEvent.INTERRUPTED));
} finally {
try {
if (writer != null)
writer.close();
} catch (IOException e) {
LOG.log(Level.WARNING, "Failed to close cato stdin writer", e);
LOG.log(Level.WARNING, "Failed to close Hiper stdin writer", e);
}
}
destroyRelatedThreads();
}
public boolean isReady() {
return id != null;
}
public synchronized String getName() {
return name;
}
public synchronized void setName(String name) {
this.name = name;
}
public State getType() {
return type;
}
@Nullable
public String getId() {
return id;
}
public String generateInvitationCode(int serverPort) {
if (id == null) {
throw new IllegalStateException("id not generated");
@Override
public void stop() {
try {
writer.write("quit\n");
writer.flush();
} catch (IOException e) {
LOG.log(Level.WARNING, "Failed to quit HiPer", e);
}
return id + "#" + serverPort;
try {
getProcess().waitFor(1, TimeUnit.SECONDS);
} catch (InterruptedException ignored) {
}
super.stop();
}
public synchronized void invokeCommand(String command) throws IOException {
LOG.info("Invoking cato: " + command);
writer.write(command);
writer.newLine();
writer.flush();
}
public void forwardPort(String peerId, String localAddress, int localPort, String remoteAddress, int remotePort, Mode mode) throws IOException {
invokeCommand(String.format("net add %s %s:%d %s:%d %s", peerId, localAddress, localPort, remoteAddress, remotePort, mode.getName()));
}
public void allowForwardingAddress(String address, int port) throws IOException {
invokeCommand(String.format("ufw net open %s:%d", address, port));
}
public void showAllowedAddress() throws IOException {
invokeCommand("ufw net whitelist");
}
public EventManager<CatoExitEvent> onExit() {
public EventManager<HiperExitEvent> onExit() {
return onExit;
}
public EventManager<CatoIdEvent> onIdGenerated() {
return onIdGenerated;
public EventManager<HiperIPEvent> onIPAllocated() {
return onIPAllocated;
}
public EventManager<Event> onPeerConnected() {
return onPeerConnected;
public EventManager<HiperShowValidUntilEvent> onValidUntil() {
return onValidUntil;
}
private static final Pattern TEMP_TOKEN_PATTERN = Pattern.compile("id\\((?<id>\\w+)\\)");
private static final Pattern PEER_CONNECTED_PATTERN = Pattern.compile("Connected to main net");
private static final Pattern LOG_PATTERN = Pattern.compile("(\\[\\d+])\\s+(\\w+)\\s+(\\w+-{0,1}\\w+):\\s(.*)");
}
public static class CatoExitEvent extends Event {
public static class HiperExitEvent extends Event {
private final int exitCode;
public CatoExitEvent(Object source, int exitCode) {
public HiperExitEvent(Object source, int exitCode) {
super(source);
this.exitCode = exitCode;
}
@@ -494,85 +462,45 @@ public final class MultiplayerManager {
return exitCode;
}
public static final int EXIT_CODE_INTERRUPTED = -1;
public static final int EXIT_CODE_SESSION_EXPIRED = 10;
public static final int INTERRUPTED = -1;
public static final int INVALID_CONFIGURATION = -2;
public static final int CERTIFICATE_EXPIRED = -3;
public static final int FAILED_GET_DEVICE = -4;
public static final int FAILED_LOAD_CONFIG = -5;
public static final int NO_SUDO_PRIVILEGES = -6;
}
public static class CatoIdEvent extends Event {
private final String id;
public static class HiperIPEvent extends Event {
private final String ip;
public CatoIdEvent(Object source, String id) {
public HiperIPEvent(Object source, String ip) {
super(source);
this.id = id;
this.ip = ip;
}
public String getId() {
return id;
public String getIP() {
return ip;
}
}
enum State {
DISCONNECTED,
CONNECTING,
MASTER,
SLAVE
}
public static class HiperShowValidUntilEvent extends Event {
private final Date validAt;
public static class Invitation {
private final String id;
@SerializedName("p")
private final int channelPort;
public Invitation(String id, int channelPort) {
this.id = id;
this.channelPort = channelPort;
public HiperShowValidUntilEvent(Object source, Date validAt) {
super(source);
this.validAt = validAt;
}
public String getId() {
return id;
}
public int getChannelPort() {
return channelPort;
public Date getValidUntil() {
return validAt;
}
}
public interface JoinSessionHandler {
void onWaitingForJoinResponse();
}
public static class IncompatibleCatoVersionException extends Exception {
private final String expected;
private final String actual;
public IncompatibleCatoVersionException(String expected, String actual) {
this.expected = expected;
this.actual = actual;
}
public String getExpected() {
return expected;
}
public String getActual() {
return actual;
}
}
public enum Mode {
P2P,
BRIDGE;
String getName() {
return name().toLowerCase(Locale.ROOT);
}
}
public static class CatoExitException extends RuntimeException {
public static class HiperExitException extends RuntimeException {
private final int exitCode;
private final boolean ready;
public CatoExitException(int exitCode, boolean ready) {
public HiperExitException(int exitCode, boolean ready) {
this.exitCode = exitCode;
this.ready = ready;
}
@@ -586,13 +514,13 @@ public final class MultiplayerManager {
}
}
public static class CatoExitTimeoutException extends RuntimeException {
public static class HiperExitTimeoutException extends RuntimeException {
}
public static class CatoSessionExpiredException extends RuntimeException {
public static class HiperSessionExpiredException extends HiperInvalidConfigurationException {
}
public static class CatoAlreadyStartedException extends RuntimeException {
public static class HiperInvalidConfigurationException extends RuntimeException {
}
public static class JoinRequestTimeoutException extends RuntimeException {
@@ -616,15 +544,10 @@ public final class MultiplayerManager {
}
}
public static class CatoNotExistsException extends RuntimeException {
private final Path file;
public CatoNotExistsException(Path file) {
this.file = file;
}
public Path getFile() {
return file;
}
public static class HiperInvalidTokenException extends RuntimeException {
}
public static class HiperUnsupportedPlatformException extends RuntimeException {
}
}
@@ -0,0 +1,36 @@
/*
* Hello Minecraft! Launcher
* Copyright (C) 2022 huangyuhui <huanghongxun2008@126.com> and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.jackhuang.hmcl.ui.multiplayer;
import org.jackhuang.hmcl.auth.authlibinjector.AuthlibInjectorArtifactProvider;
import org.jackhuang.hmcl.auth.offline.OfflineAccount;
import org.jackhuang.hmcl.auth.offline.Skin;
import java.util.UUID;
public class MultiplayerOfflineAccount extends OfflineAccount {
public MultiplayerOfflineAccount(AuthlibInjectorArtifactProvider downloader, String username, UUID uuid, Skin skin) {
super(downloader, username, uuid, skin);
}
@Override
protected boolean loadAuthlibInjector(Skin skin) {
return true;
}
}
@@ -19,40 +19,39 @@ package org.jackhuang.hmcl.ui.multiplayer;
import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXDialogLayout;
import de.javawi.jstun.test.DiscoveryInfo;
import de.javawi.jstun.test.DiscoveryTest;
import javafx.application.Platform;
import javafx.beans.property.*;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.Label;
import javafx.scene.control.Skin;
import org.jackhuang.hmcl.auth.Account;
import org.jackhuang.hmcl.auth.offline.OfflineAccount;
import org.jackhuang.hmcl.event.Event;
import org.jackhuang.hmcl.setting.DownloadProviders;
import org.jackhuang.hmcl.setting.Profile;
import org.jackhuang.hmcl.setting.Profiles;
import org.jackhuang.hmcl.task.Schedulers;
import org.jackhuang.hmcl.task.Task;
import org.jackhuang.hmcl.task.TaskExecutor;
import org.jackhuang.hmcl.ui.Controllers;
import org.jackhuang.hmcl.ui.FXUtils;
import org.jackhuang.hmcl.ui.construct.*;
import org.jackhuang.hmcl.ui.decorator.DecoratorAnimatedPage;
import org.jackhuang.hmcl.ui.decorator.DecoratorPage;
import org.jackhuang.hmcl.ui.versions.Versions;
import org.jackhuang.hmcl.util.HMCLService;
import org.jackhuang.hmcl.util.Result;
import org.jackhuang.hmcl.util.StringUtils;
import org.jackhuang.hmcl.util.TaskCancellationAction;
import org.jackhuang.hmcl.util.io.ChecksumMismatchException;
import org.jetbrains.annotations.Nullable;
import org.jackhuang.hmcl.util.io.FileUtils;
import org.jackhuang.hmcl.util.platform.CommandBuilder;
import org.jackhuang.hmcl.util.platform.OperatingSystem;
import org.jackhuang.hmcl.util.platform.SystemUtils;
import java.io.File;
import java.util.Date;
import java.util.concurrent.CancellationException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.logging.Level;
import static org.jackhuang.hmcl.setting.ConfigHolder.globalConfig;
import static org.jackhuang.hmcl.ui.FXUtils.runInFX;
import static org.jackhuang.hmcl.ui.multiplayer.MultiplayerChannel.KickResponse.*;
import static org.jackhuang.hmcl.util.Lang.resolveException;
import static org.jackhuang.hmcl.util.Logging.LOG;
import static org.jackhuang.hmcl.util.i18n.I18n.i18n;
@@ -60,24 +59,24 @@ import static org.jackhuang.hmcl.util.i18n.I18n.i18n;
public class MultiplayerPage extends DecoratorAnimatedPage implements DecoratorPage, PageAware {
private final ReadOnlyObjectWrapper<State> state = new ReadOnlyObjectWrapper<>(State.fromTitle(i18n("multiplayer")));
private final ObjectProperty<MultiplayerManager.State> multiplayerState = new SimpleObjectProperty<>(MultiplayerManager.State.DISCONNECTED);
private final ReadOnlyStringWrapper token = new ReadOnlyStringWrapper();
private final ReadOnlyObjectWrapper<@Nullable Result<DiscoveryInfo>> natState = new ReadOnlyObjectWrapper<>();
private final ReadOnlyIntegerWrapper gamePort = new ReadOnlyIntegerWrapper(-1);
private final ReadOnlyObjectWrapper<MultiplayerManager.CatoSession> session = new ReadOnlyObjectWrapper<>();
private final ObservableList<MultiplayerChannel.CatoClient> clients = FXCollections.observableArrayList();
private final ReadOnlyObjectWrapper<MultiplayerManager.HiperSession> session = new ReadOnlyObjectWrapper<>();
private final IntegerProperty port = new SimpleIntegerProperty();
private final StringProperty address = new SimpleStringProperty();
private final ReadOnlyObjectWrapper<Date> expireTime = new ReadOnlyObjectWrapper<>();
private Consumer<MultiplayerManager.CatoExitEvent> onExit;
private Consumer<MultiplayerManager.CatoIdEvent> onIdGenerated;
private Consumer<Event> onPeerConnected;
private Consumer<MultiplayerManager.HiperExitEvent> onExit;
private Consumer<MultiplayerManager.HiperIPEvent> onIPAllocated;
private Consumer<MultiplayerManager.HiperShowValidUntilEvent> onValidUntil;
private final ReadOnlyObjectWrapper<LocalServerBroadcaster> broadcaster = new ReadOnlyObjectWrapper<>();
private Consumer<Event> onBroadcasterExit = null;
public MultiplayerPage() {
testNAT();
}
@Override
public void onPageShown() {
checkAgreement(this::downloadCatoIfNecessary);
checkAgreement(this::downloadHiPerIfNecessary);
}
@Override
@@ -85,70 +84,81 @@ public class MultiplayerPage extends DecoratorAnimatedPage implements DecoratorP
return new MultiplayerPageSkin(this);
}
public ObservableList<MultiplayerChannel.CatoClient> getClients() {
return clients;
public int getPort() {
return port.get();
}
public MultiplayerManager.State getMultiplayerState() {
return multiplayerState.get();
public IntegerProperty portProperty() {
return port;
}
public ObjectProperty<MultiplayerManager.State> multiplayerStateProperty() {
return multiplayerState;
public void setPort(int port) {
this.port.set(port);
}
public void setMultiplayerState(MultiplayerManager.State multiplayerState) {
this.multiplayerState.set(multiplayerState);
public String getAddress() {
return address.get();
}
public Result<DiscoveryInfo> getNatState() {
return natState.get();
public StringProperty addressProperty() {
return address;
}
public ReadOnlyObjectProperty<Result<DiscoveryInfo>> natStateProperty() {
return natState.getReadOnlyProperty();
public void setAddress(String address) {
this.address.set(address);
}
public String getToken() {
return token.get();
public LocalServerBroadcaster getBroadcaster() {
return broadcaster.get();
}
public ReadOnlyStringProperty tokenProperty() {
return token.getReadOnlyProperty();
public ReadOnlyObjectWrapper<LocalServerBroadcaster> broadcasterProperty() {
return broadcaster;
}
public int getGamePort() {
return gamePort.get();
public void setBroadcaster(LocalServerBroadcaster broadcaster) {
this.broadcaster.set(broadcaster);
}
public ReadOnlyIntegerProperty gamePortProperty() {
return gamePort.getReadOnlyProperty();
public Date getExpireTime() {
return expireTime.get();
}
public MultiplayerManager.CatoSession getSession() {
public ReadOnlyObjectWrapper<Date> expireTimeProperty() {
return expireTime;
}
public void setExpireTime(Date expireTime) {
this.expireTime.set(expireTime);
}
public MultiplayerManager.HiperSession getSession() {
return session.get();
}
public ReadOnlyObjectProperty<MultiplayerManager.CatoSession> sessionProperty() {
public ReadOnlyObjectProperty<MultiplayerManager.HiperSession> sessionProperty() {
return session.getReadOnlyProperty();
}
private void testNAT() {
Task.supplyAsync(() -> {
DiscoveryTest tester = new DiscoveryTest(null, 0, "stun.miwifi.com", 3478);
return tester.test();
}).whenComplete(Schedulers.javafx(), (info, exception) -> {
if (exception == null) {
natState.set(Result.ok(info));
} else {
natState.set(Result.error());
void launchGame() {
Profile profile = Profiles.getSelectedProfile();
Versions.launch(profile, profile.getSelectedVersion(), (launcherHelper) -> {
launcherHelper.setKeep();
Account account = launcherHelper.getAccount();
if (account instanceof OfflineAccount && !(account instanceof MultiplayerOfflineAccount)) {
OfflineAccount offlineAccount = (OfflineAccount) account;
launcherHelper.setAccount(new MultiplayerOfflineAccount(
offlineAccount.getDownloader(),
offlineAccount.getUsername(),
offlineAccount.getUUID(),
offlineAccount.getSkin()
));
}
LOG.log(Level.INFO, "Nat test result " + MultiplayerPageSkin.getNATType(natState.get()), exception);
}).start();
});
}
private void checkAgreement(Runnable runnable) {
if (globalConfig().getMultiplayerAgreementVersion() < MultiplayerManager.CATO_AGREEMENT_VERSION) {
if (globalConfig().getMultiplayerAgreementVersion() < MultiplayerManager.HIPER_AGREEMENT_VERSION) {
JFXDialogLayout agreementPane = new JFXDialogLayout();
agreementPane.setHeading(new Label(i18n("launcher.agreement")));
agreementPane.setBody(new Label(i18n("multiplayer.agreement.prompt")));
@@ -157,7 +167,7 @@ public class MultiplayerPage extends DecoratorAnimatedPage implements DecoratorP
JFXButton yesButton = new JFXButton(i18n("launcher.agreement.accept"));
yesButton.getStyleClass().add("dialog-accept");
yesButton.setOnAction(e -> {
globalConfig().setMultiplayerAgreementVersion(MultiplayerManager.CATO_AGREEMENT_VERSION);
globalConfig().setMultiplayerAgreementVersion(MultiplayerManager.HIPER_AGREEMENT_VERSION);
runnable.run();
agreementPane.fireEvent(new DialogCloseEvent());
});
@@ -174,21 +184,18 @@ public class MultiplayerPage extends DecoratorAnimatedPage implements DecoratorP
}
}
private void downloadCatoIfNecessary() {
if (StringUtils.isBlank(MultiplayerManager.getCatoPath())) {
Controllers.dialog(i18n("multiplayer.download.unsupported"), i18n("install.failed.downloading"), MessageDialogPane.MessageType.ERROR);
fireEvent(new PageCloseEvent());
return;
}
if (!MultiplayerManager.getCatoExecutable().toFile().exists()) {
private void downloadHiPerIfNecessary() {
if (!MultiplayerManager.HIPER_PATH.toFile().exists()) {
setDisabled(true);
TaskExecutor executor = MultiplayerManager.downloadCato()
Controllers.taskDialog(MultiplayerManager.downloadHiper()
.whenComplete(Schedulers.javafx(), exception -> {
setDisabled(false);
if (exception != null) {
if (exception instanceof CancellationException) {
Controllers.showToast(i18n("message.cancelled"));
} else if (exception instanceof MultiplayerManager.HiperUnsupportedPlatformException) {
Controllers.dialog(i18n("multiplayer.download.unsupported"), i18n("install.failed.downloading"), MessageDialogPane.MessageType.ERROR);
fireEvent(new PageCloseEvent());
} else {
Controllers.dialog(DownloadProviders.localizeErrorMessage(exception), i18n("install.failed.downloading"), MessageDialogPane.MessageType.ERROR);
fireEvent(new PageCloseEvent());
@@ -196,316 +203,160 @@ public class MultiplayerPage extends DecoratorAnimatedPage implements DecoratorP
} else {
Controllers.showToast(i18n("multiplayer.download.success"));
}
}).executor();
Controllers.taskDialog(executor, i18n("multiplayer.download"), TaskCancellationAction.NORMAL);
executor.start();
}), i18n("multiplayer.download"), TaskCancellationAction.NORMAL);
} else {
setDisabled(false);
}
}
public void copyInvitationCode() {
if (getSession() == null || !getSession().isReady() || gamePort.get() < 0 || getMultiplayerState() != MultiplayerManager.State.MASTER) {
throw new IllegalStateException("CatoSession not ready");
}
FXUtils.copyText(getSession().generateInvitationCode(getSession().getServer().getPort()));
}
public void createRoom() {
if (getSession() != null || getMultiplayerState() != MultiplayerManager.State.DISCONNECTED) {
throw new IllegalStateException("CatoSession already ready");
}
Controllers.dialog(new CreateMultiplayerRoomDialog((result, resolve, reject) -> {
int gamePort = result.getServer().getAd();
boolean isStaticToken = StringUtils.isNotBlank(globalConfig().getMultiplayerToken());
MultiplayerManager.createSession(globalConfig().getMultiplayerToken(), result.getServer().getMotd(), gamePort, result.isAllowAllJoinRequests())
.thenAcceptAsync(session -> {
session.getServer().setOnClientAdding((client, resolveClient, rejectClient) -> {
runInFX(() -> {
Controllers.dialog(new MessageDialogPane.Builder(i18n("multiplayer.session.create.join.prompt", client.getUsername()), i18n("multiplayer.session.create.join"), MessageDialogPane.MessageType.INFO)
.yesOrNo(resolveClient, () -> rejectClient.accept(MultiplayerChannel.KickResponse.JOIN_ACEEPTANCE_TIMEOUT))
.cancelOnTimeout(30 * 1000)
.build());
});
});
session.getServer().onClientAdded().register(event -> {
runInFX(() -> {
clients.add(event);
});
});
session.getServer().onClientDisconnected().register(event -> {
runInFX(() -> {
clients.remove(event);
});
});
initCatoSession(session);
this.gamePort.set(gamePort);
setMultiplayerState(MultiplayerManager.State.MASTER);
resolve.run();
}, Platform::runLater)
.exceptionally(throwable -> {
reject.accept(localizeCreateErrorMessage(throwable, isStaticToken));
return null;
});
}));
}
public void joinRoom() {
if (getSession() != null || getMultiplayerState() != MultiplayerManager.State.DISCONNECTED) {
throw new IllegalStateException("CatoSession already ready");
}
Controllers.prompt(new PromptDialogPane.Builder(i18n("multiplayer.session.join"), (result, resolve, reject) -> {
PromptDialogPane.Builder.HintQuestion hintQuestion = (PromptDialogPane.Builder.HintQuestion) result.get(0);
boolean isStaticToken = StringUtils.isNotBlank(globalConfig().getMultiplayerToken());
String invitationCode = ((PromptDialogPane.Builder.StringQuestion) result.get(1)).getValue();
MultiplayerManager.Invitation invitation;
try {
invitation = MultiplayerManager.parseInvitationCode(invitationCode);
} catch (Exception e) {
LOG.log(Level.WARNING, "Failed to join session", e);
reject.accept(i18n("multiplayer.session.join.invitation_code.error"));
return;
}
int localPort; // invitation channel
try {
localPort = MultiplayerManager.findAvailablePort();
} catch (Exception e) {
reject.accept(i18n("multiplayer.session.join.port.error"));
return;
}
try {
MultiplayerManager.joinSession(
globalConfig().getMultiplayerToken(),
invitation.getId(),
globalConfig().isMultiplayerRelay() && (StringUtils.isNotBlank(globalConfig().getMultiplayerToken()) || StringUtils.isNotBlank(System.getProperty("hmcl.multiplayer.relay")))
? MultiplayerManager.Mode.BRIDGE
: MultiplayerManager.Mode.P2P,
invitation.getChannelPort(),
localPort, new MultiplayerManager.JoinSessionHandler() {
@Override
public void onWaitingForJoinResponse() {
runInFX(() -> {
hintQuestion.setQuestion(i18n("multiplayer.session.join.wait"));
});
}
})
.thenAcceptAsync(session -> {
initCatoSession(session);
AtomicBoolean kicked = new AtomicBoolean();
session.getClient().onDisconnected().register(() -> {
runInFX(() -> {
stopCatoSession();
if (!kicked.get()) {
Controllers.dialog(i18n("multiplayer.session.join.lost_connection"));
}
});
});
session.getClient().onKicked().register(kickedEvent -> {
runInFX(() -> {
kicked.set(true);
Controllers.dialog(i18n("multiplayer.session.join.kicked", localizeKickMessage(kickedEvent.getReason())));
});
});
gamePort.set(session.getClient().getGamePort());
setMultiplayerState(MultiplayerManager.State.SLAVE);
resolve.run();
}, Platform::runLater)
.exceptionally(throwable -> {
reject.accept(localizeJoinErrorMessage(throwable, isStaticToken));
return null;
});
} catch (MultiplayerManager.IncompatibleCatoVersionException e) {
reject.accept(i18n("multiplayer.session.join.invitation_code.version"));
}
})
.addQuestion(new PromptDialogPane.Builder.HintQuestion(i18n("multiplayer.session.join.hint")))
.addQuestion(new PromptDialogPane.Builder.StringQuestion(i18n("multiplayer.session.join.invitation_code"), "", new RequiredValidator())));
}
private String localizeKickMessage(String message) {
if (VERSION_NOT_MATCHED.equals(message)) {
return i18n("multiplayer.session.join.kicked.version_not_matched");
} else if (KICKED.equals(message)) {
return i18n("multiplayer.session.join.kicked.kicked");
} else if (JOIN_ACEEPTANCE_TIMEOUT.equals(message)) {
return i18n("multiplayer.session.join.kicked.join_acceptance_timeout");
} else {
return message;
}
}
private String localizeErrorMessage(Throwable t, boolean isStaticToken, Function<Throwable, String> fallback) {
private String localizeErrorMessage(Throwable t) {
Throwable e = resolveException(t);
if (e instanceof CancellationException) {
LOG.info("Connection rejected by the server");
return i18n("message.cancelled");
} else if (e instanceof MultiplayerManager.KickedException) {
LOG.info("Kicked by server");
return i18n("multiplayer.session.join.kicked", localizeKickMessage(((MultiplayerManager.KickedException) e).getReason()));
} else if (e instanceof MultiplayerManager.CatoAlreadyStartedException) {
LOG.info("Cato already started");
return i18n("multiplayer.session.error.already_started");
} else if (e instanceof MultiplayerManager.CatoNotExistsException) {
LOG.log(Level.WARNING, "Cato not found " + ((MultiplayerManager.CatoNotExistsException) e).getFile(), e);
return i18n("multiplayer.session.error.file_not_found");
} else if (e instanceof MultiplayerManager.JoinRequestTimeoutException) {
LOG.info("Cato already started");
return i18n("multiplayer.session.join.wait_timeout");
} else if (e instanceof MultiplayerManager.ConnectionErrorException) {
LOG.info("Failed to establish connection with server");
return i18n("multiplayer.session.join.error.connection");
} else if (e instanceof MultiplayerManager.CatoExitTimeoutException) {
LOG.info("Cato failed to connect to main net");
if (isStaticToken) {
return i18n("multiplayer.exit.timeout.static_token");
} else {
return i18n("multiplayer.exit.timeout.dynamic_token");
}
} else if (e instanceof MultiplayerManager.CatoExitException) {
LOG.info("Cato exited accidentally");
int exitCode = ((MultiplayerManager.CatoExitException) e).getExitCode();
if (!((MultiplayerManager.CatoExitException) e).isReady()) {
return i18n("multiplayer.exit.before_ready", exitCode);
} else {
return i18n("multiplayer.exit.after_ready", exitCode);
}
} else if (e instanceof MultiplayerManager.HiperInvalidConfigurationException) {
LOG.warning("HiPer invalid configuration");
return i18n("multiplayer.token.malformed");
} else if (e instanceof ChecksumMismatchException) {
return i18n("exception.artifact_malformed");
LOG.log(Level.WARNING, "Failed to verify HiPer files", e);
return i18n("multiplayer.error.file_not_found");
} else if (e instanceof MultiplayerManager.HiperExitException) {
int exitCode = ((MultiplayerManager.HiperExitException) e).getExitCode();
LOG.warning("HiPer exited unexpectedly with exit code " + exitCode);
return i18n("multiplayer.exit", exitCode);
} else if (e instanceof MultiplayerManager.HiperInvalidTokenException) {
LOG.warning("invalid token");
return i18n("multiplayer.token.invalid");
} else {
return fallback.apply(e);
LOG.log(Level.WARNING, "Unknown HiPer exception", e);
return e.getLocalizedMessage() + "\n" + StringUtils.getStackTrace(e);
}
}
private String localizeCreateErrorMessage(Throwable t, boolean isStaticToken) {
return localizeErrorMessage(t, isStaticToken, e -> {
LOG.log(Level.WARNING, "Failed to create session", e);
if (isStaticToken) {
return i18n("multiplayer.session.create.error.static_token") + e.getLocalizedMessage();
} else {
return i18n("multiplayer.session.create.error.dynamic_token") + e.getLocalizedMessage();
}
});
public void start() {
MultiplayerManager.startHiper(globalConfig().getMultiplayerToken())
.thenAcceptAsync(session -> {
this.session.set(session);
onExit = session.onExit().registerWeak(this::onExit);
onIPAllocated = session.onIPAllocated().registerWeak(this::onIPAllocated);
onValidUntil = session.onValidUntil().registerWeak(this::onValidUntil);
}, Schedulers.javafx())
.exceptionally(throwable -> {
runInFX(() -> Controllers.dialog(localizeErrorMessage(throwable), null, MessageDialogPane.MessageType.ERROR));
return null;
});
}
private String localizeJoinErrorMessage(Throwable t, boolean isStaticToken) {
return localizeErrorMessage(t, isStaticToken, e -> {
LOG.log(Level.WARNING, "Failed to join session", e);
return i18n("multiplayer.session.join.error");
});
}
public void kickPlayer(MultiplayerChannel.CatoClient client) {
if (getSession() == null || !getSession().isReady() || getMultiplayerState() != MultiplayerManager.State.MASTER) {
throw new IllegalStateException("CatoSession not ready");
}
Controllers.confirm(i18n("multiplayer.session.create.members.kick.prompt"), i18n("multiplayer.session.create.members.kick"), MessageDialogPane.MessageType.WARNING,
() -> {
getSession().getServer().kickPlayer(client);
}, null);
}
public void closeRoom() {
if (getSession() == null || !getSession().isReady() || getMultiplayerState() != MultiplayerManager.State.MASTER) {
throw new IllegalStateException("CatoSession not ready");
}
Controllers.confirm(i18n("multiplayer.session.close.warning"), i18n("message.warning"), MessageDialogPane.MessageType.WARNING,
this::stopCatoSession, null);
}
public void quitRoom() {
if (getSession() == null || !getSession().isReady() || getMultiplayerState() != MultiplayerManager.State.SLAVE) {
throw new IllegalStateException("CatoSession not ready");
}
Controllers.confirm(i18n("multiplayer.session.quit.warning"), i18n("message.warning"), MessageDialogPane.MessageType.WARNING,
this::stopCatoSession, null);
}
public void cancelRoom() {
if (getSession() == null || getSession().isReady() || getMultiplayerState() != MultiplayerManager.State.CONNECTING) {
throw new IllegalStateException("CatoSession not existing or already ready");
}
stopCatoSession();
}
private void initCatoSession(MultiplayerManager.CatoSession session) {
runInFX(() -> {
onExit = session.onExit().registerWeak(this::onCatoExit);
onIdGenerated = session.onIdGenerated().registerWeak(this::onCatoIdGenerated);
onPeerConnected = session.onPeerConnected().registerWeak(this::onCatoPeerConnected);
this.clients.clear();
this.session.set(session);
});
}
private void stopCatoSession() {
public void stop() {
if (getSession() != null) {
getSession().stop();
}
clearCatoSession();
if (getBroadcaster() != null) {
getBroadcaster().close();
}
clearSession();
}
private void clearCatoSession() {
this.session.set(null);
this.token.set(null);
this.gamePort.set(-1);
this.multiplayerState.set(MultiplayerManager.State.DISCONNECTED);
public void broadcast(String url) {
LocalServerBroadcaster broadcaster = new LocalServerBroadcaster(url);
this.onBroadcasterExit = broadcaster.onExit().registerWeak(this::onBroadcasterExit);
broadcaster.start();
this.broadcaster.set(broadcaster);
}
private void onCatoExit(MultiplayerManager.CatoExitEvent event) {
public void stopBroadcasting() {
if (getBroadcaster() != null) {
getBroadcaster().close();
setBroadcaster(null);
}
}
private void onBroadcasterExit(Event event) {
runInFX(() -> {
if (this.broadcaster.get() == event.getSource()) {
this.broadcaster.set(null);
}
});
}
private void clearSession() {
this.session.set(null);
this.expireTime.set(null);
this.onExit = null;
this.onIPAllocated = null;
this.onValidUntil = null;
this.broadcaster.set(null);
this.onBroadcasterExit = null;
}
private void onIPAllocated(MultiplayerManager.HiperIPEvent event) {
runInFX(() -> this.address.set(event.getIP()));
}
private void onValidUntil(MultiplayerManager.HiperShowValidUntilEvent event) {
runInFX(() -> this.expireTime.set(event.getValidUntil()));
}
private void onExit(MultiplayerManager.HiperExitEvent event) {
runInFX(() -> {
boolean ready = ((MultiplayerManager.CatoSession) event.getSource()).isReady();
switch (event.getExitCode()) {
case 0:
break;
case MultiplayerManager.CatoExitEvent.EXIT_CODE_SESSION_EXPIRED:
Controllers.dialog(i18n("multiplayer.session.expired"));
case MultiplayerManager.HiperExitEvent.CERTIFICATE_EXPIRED:
MultiplayerManager.clearConfiguration();
Controllers.dialog(i18n("multiplayer.token.expired"));
break;
case 1:
if (!ready) {
Controllers.dialog(i18n("multiplayer.exit.timeout"));
case MultiplayerManager.HiperExitEvent.INVALID_CONFIGURATION:
MultiplayerManager.clearConfiguration();
Controllers.dialog(i18n("multiplayer.token.malformed"));
break;
case MultiplayerManager.HiperExitEvent.NO_SUDO_PRIVILEGES:
if (OperatingSystem.CURRENT_OS == OperatingSystem.WINDOWS) {
Controllers.confirm(i18n("multiplayer.error.failed_sudo.windows"), null, MessageDialogPane.MessageType.WARNING, () -> {
FXUtils.openLink("https://docs.hmcl.net/multiplayer/admin.html");
}, null);
} else if (OperatingSystem.CURRENT_OS == OperatingSystem.LINUX) {
Controllers.dialog(i18n("multiplayer.error.failed_sudo.linux", MultiplayerManager.HIPER_PATH.toString()), null, MessageDialogPane.MessageType.WARNING);
} else if (OperatingSystem.CURRENT_OS == OperatingSystem.OSX) {
Controllers.confirm(i18n("multiplayer.error.failed_sudo.mac"), null, MessageDialogPane.MessageType.INFO, () -> {
try {
String text = "%hmcl-hiper ALL=(ALL:ALL) NOPASSWD: " + MultiplayerManager.HIPER_PATH.toString().replaceAll("[ @!(),:=\\\\]", "\\\\$0") + "\n";
File sudoersTmp = File.createTempFile("sudoer", ".tmp");
sudoersTmp.deleteOnExit();
FileUtils.writeText(sudoersTmp, text);
SystemUtils.callExternalProcess(
"osascript", "-e", String.format("do shell script \"%s\" with administrator privileges", String.join(";",
"dscl . create /Groups/hmcl-hiper PrimaryGroupID 758",
"dscl . merge /Groups/hmcl-hiper GroupMembership " + CommandBuilder.toShellStringLiteral(System.getProperty("user.name")) + "",
"mkdir -p /private/etc/sudoers.d",
"mv -f " + CommandBuilder.toShellStringLiteral(sudoersTmp.toString()) + " /private/etc/sudoers.d/hmcl-hiper",
"chown root /private/etc/sudoers.d/hmcl-hiper",
"chmod 0440 /private/etc/sudoers.d/hmcl-hiper"
).replaceAll("[\\\\\"]", "\\\\$0"))
);
} catch (Throwable e) {
LOG.log(Level.WARNING, "Failed to modify sudoers", e);
}
}, null);
}
break;
case -1:
case MultiplayerManager.HiperExitEvent.INTERRUPTED:
// do nothing
break;
case MultiplayerManager.HiperExitEvent.FAILED_GET_DEVICE:
Controllers.dialog(i18n("multiplayer.error.failed_get_device"));
break;
case MultiplayerManager.HiperExitEvent.FAILED_LOAD_CONFIG:
Controllers.dialog(i18n("multiplayer.error.failed_load_config"));
break;
default:
if (!((MultiplayerManager.CatoSession) event.getSource()).isReady()) {
Controllers.dialog(i18n("multiplayer.exit.before_ready", event.getExitCode()));
} else {
Controllers.dialog(i18n("multiplayer.exit.after_ready", event.getExitCode()));
}
Controllers.dialog(i18n("multiplayer.exit", event.getExitCode()));
break;
}
clearCatoSession();
});
}
private void onCatoPeerConnected(Event event) {
runInFX(() -> {
});
}
private void onCatoIdGenerated(MultiplayerManager.CatoIdEvent event) {
runInFX(() -> {
token.set(event.getId());
setMultiplayerState(((MultiplayerManager.CatoSession) event.getSource()).getType());
clearSession();
});
}
@@ -513,5 +364,4 @@ public class MultiplayerPage extends DecoratorAnimatedPage implements DecoratorP
public ReadOnlyObjectProperty<State> stateProperty() {
return state;
}
}
@@ -19,7 +19,10 @@ package org.jackhuang.hmcl.ui.multiplayer;
import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXPasswordField;
import de.javawi.jstun.test.DiscoveryInfo;
import com.jfoenix.controls.JFXTextField;
import javafx.application.Platform;
import javafx.beans.InvalidationListener;
import javafx.beans.WeakInvalidationListener;
import javafx.beans.binding.Bindings;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
@@ -28,26 +31,31 @@ import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.*;
import org.jackhuang.hmcl.game.LauncherHelper;
import org.jackhuang.hmcl.setting.Profile;
import org.jackhuang.hmcl.setting.Profiles;
import org.jackhuang.hmcl.setting.Theme;
import javafx.stage.FileChooser;
import javafx.util.StringConverter;
import org.jackhuang.hmcl.task.Schedulers;
import org.jackhuang.hmcl.ui.Controllers;
import org.jackhuang.hmcl.ui.FXUtils;
import org.jackhuang.hmcl.ui.SVG;
import org.jackhuang.hmcl.ui.animation.ContainerAnimations;
import org.jackhuang.hmcl.ui.animation.TransitionPane;
import org.jackhuang.hmcl.ui.construct.*;
import org.jackhuang.hmcl.ui.construct.MessageDialogPane.MessageType;
import org.jackhuang.hmcl.ui.decorator.DecoratorAnimatedPage;
import org.jackhuang.hmcl.ui.versions.Versions;
import org.jackhuang.hmcl.util.HMCLService;
import org.jackhuang.hmcl.util.Result;
import org.jackhuang.hmcl.util.javafx.BindingMapping;
import org.jackhuang.hmcl.util.javafx.MappedObservableList;
import org.jetbrains.annotations.Nullable;
import org.jackhuang.hmcl.util.Lang;
import org.jackhuang.hmcl.util.StringUtils;
import org.jackhuang.hmcl.util.i18n.Locales;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.concurrent.CompletableFuture;
import java.util.logging.Level;
import static org.jackhuang.hmcl.setting.ConfigHolder.globalConfig;
import static org.jackhuang.hmcl.ui.versions.VersionPage.wrap;
import static org.jackhuang.hmcl.util.Logging.LOG;
import static org.jackhuang.hmcl.util.i18n.I18n.i18n;
public class MultiplayerPageSkin extends DecoratorAnimatedPage.DecoratorAnimatedPageSkin<MultiplayerPage> {
@@ -63,74 +71,45 @@ public class MultiplayerPageSkin extends DecoratorAnimatedPage.DecoratorAnimated
super(control);
{
VBox roomPane = new VBox();
{
AdvancedListItem createRoomItem = new AdvancedListItem();
createRoomItem.setTitle(i18n("multiplayer.session.create"));
createRoomItem.setLeftGraphic(wrap(SVG::plusCircleOutline));
createRoomItem.setActionButtonVisible(false);
createRoomItem.setOnAction(e -> control.createRoom());
AdvancedListItem joinRoomItem = new AdvancedListItem();
joinRoomItem.setTitle(i18n("multiplayer.session.join"));
joinRoomItem.setLeftGraphic(wrap(SVG::accountArrowRightOutline));
joinRoomItem.setActionButtonVisible(false);
joinRoomItem.setOnAction(e -> control.joinRoom());
AdvancedListItem copyLinkItem = new AdvancedListItem();
copyLinkItem.setTitle(i18n("multiplayer.session.copy_room_code"));
copyLinkItem.setLeftGraphic(wrap(SVG::accountArrowRightOutline));
copyLinkItem.setActionButtonVisible(false);
copyLinkItem.setOnAction(e -> control.copyInvitationCode());
AdvancedListItem cancelItem = new AdvancedListItem();
cancelItem.setTitle(i18n("button.cancel"));
cancelItem.setLeftGraphic(wrap(SVG::closeCircle));
cancelItem.setActionButtonVisible(false);
cancelItem.setOnAction(e -> control.cancelRoom());
AdvancedListItem quitItem = new AdvancedListItem();
quitItem.setTitle(i18n("multiplayer.session.quit"));
quitItem.setLeftGraphic(wrap(SVG::closeCircle));
quitItem.setActionButtonVisible(false);
quitItem.setOnAction(e -> control.quitRoom());
AdvancedListItem closeRoomItem = new AdvancedListItem();
closeRoomItem.setTitle(i18n("multiplayer.session.close"));
closeRoomItem.setLeftGraphic(wrap(SVG::closeCircle));
closeRoomItem.setActionButtonVisible(false);
closeRoomItem.setOnAction(e -> control.closeRoom());
FXUtils.onChangeAndOperate(getSkinnable().multiplayerStateProperty(), state -> {
if (state == MultiplayerManager.State.DISCONNECTED) {
roomPane.getChildren().setAll(createRoomItem, joinRoomItem);
} else if (state == MultiplayerManager.State.CONNECTING) {
roomPane.getChildren().setAll(cancelItem);
} else if (state == MultiplayerManager.State.MASTER) {
roomPane.getChildren().setAll(copyLinkItem, closeRoomItem);
} else if (state == MultiplayerManager.State.SLAVE) {
roomPane.getChildren().setAll(quitItem);
}
});
}
AdvancedListBox sideBar = new AdvancedListBox()
.addNavigationDrawerItem(item -> {
item.setTitle(i18n("version.launch"));
item.setLeftGraphic(wrap(SVG::rocketLaunchOutline));
item.setOnAction(e -> {
Profile profile = Profiles.getSelectedProfile();
Versions.launch(profile, profile.getSelectedVersion(), LauncherHelper::setKeep);
control.launchGame();
});
})
.startCategory(i18n("multiplayer.session"))
.add(roomPane)
.startCategory(i18n("help"))
.addNavigationDrawerItem(item -> {
item.setTitle(i18n("help"));
item.setLeftGraphic(wrap(SVG::helpCircleOutline));
item.setOnAction(e -> FXUtils.openLink("https://docs.hmcl.net/multiplayer"));
})
// .addNavigationDrawerItem(item -> {
// item.setTitle(i18n("multiplayer.help.1"));
// item.setLeftGraphic(wrap(SVG::helpCircleOutline));
// item.setOnAction(e -> FXUtils.openLink("https://docs.hmcl.net/multiplayer/admin.html"));
// })
.addNavigationDrawerItem(item -> {
item.setTitle(i18n("multiplayer.help.2"));
item.setLeftGraphic(wrap(SVG::helpCircleOutline));
item.setOnAction(e -> FXUtils.openLink("https://docs.hmcl.net/multiplayer/help.html"));
})
.addNavigationDrawerItem(item -> {
item.setTitle(i18n("multiplayer.help.3"));
item.setLeftGraphic(wrap(SVG::helpCircleOutline));
item.setOnAction(e -> FXUtils.openLink("https://docs.hmcl.net/multiplayer/help.html#%E5%88%9B%E5%BB%BA%E6%96%B9"));
})
.addNavigationDrawerItem(item -> {
item.setTitle(i18n("multiplayer.help.4"));
item.setLeftGraphic(wrap(SVG::helpCircleOutline));
item.setOnAction(e -> FXUtils.openLink("https://docs.hmcl.net/multiplayer/help.html#%E5%8F%82%E4%B8%8E%E8%80%85"));
})
.addNavigationDrawerItem(item -> {
item.setTitle(i18n("multiplayer.help.text"));
item.setLeftGraphic(wrap(SVG::rocketLaunchOutline));
item.setOnAction(e -> FXUtils.openLink("https://docs.hmcl.net/multiplayer/text.html"));
})
.addNavigationDrawerItem(report -> {
report.setTitle(i18n("feedback"));
report.setLeftGraphic(wrap(SVG::messageAlertOutline));
@@ -146,128 +125,311 @@ public class MultiplayerPageSkin extends DecoratorAnimatedPage.DecoratorAnimated
content.setFillWidth(true);
ScrollPane scrollPane = new ScrollPane(content);
scrollPane.setFitToWidth(true);
scrollPane.setFitToHeight(true);
setCenter(scrollPane);
ComponentList roomPane = new ComponentList();
VBox mainPane = new VBox(16);
{
TransitionPane transitionPane = new TransitionPane();
roomPane.getContent().setAll(transitionPane);
VBox disconnectedPane = new VBox(8);
ComponentList offPane = new ComponentList();
{
HintPane hintPane = new HintPane(MessageDialogPane.MessageType.INFO);
hintPane.setText(i18n("multiplayer.state.disconnected.hint"));
HintPane hintPane = new HintPane(MessageType.WARNING);
hintPane.setText(i18n("multiplayer.off.hint"));
Label label = new Label(i18n("multiplayer.state.disconnected"));
BorderPane tokenPane = new BorderPane();
{
Label tokenTitle = new Label(i18n("multiplayer.token"));
BorderPane.setAlignment(tokenTitle, Pos.CENTER_LEFT);
tokenPane.setLeft(tokenTitle);
// Token acts like password, we hide it here preventing users from accidentally leaking their token when taking screenshots.
JFXPasswordField tokenField = new JFXPasswordField();
BorderPane.setAlignment(tokenField, Pos.CENTER_LEFT);
BorderPane.setMargin(tokenField, new Insets(0, 8, 0, 8));
tokenPane.setCenter(tokenField);
tokenField.textProperty().bindBidirectional(globalConfig().multiplayerTokenProperty());
tokenField.setPromptText(i18n("multiplayer.token.prompt"));
disconnectedPane.getChildren().setAll(hintPane, label);
Validator validator = new Validator("multiplayer.token.format_invalid", StringUtils::isAlphabeticOrNumber);
InvalidationListener listener = any -> tokenField.validate();
validator.getProperties().put(validator, listener);
tokenField.textProperty().addListener(new WeakInvalidationListener(listener));
tokenField.getValidators().add(validator);
JFXHyperlink applyLink = new JFXHyperlink(i18n("multiplayer.token.apply"));
BorderPane.setAlignment(applyLink, Pos.CENTER_RIGHT);
applyLink.setOnAction(e -> HMCLService.openRedirectLink("multiplayer-static-token"));
tokenPane.setRight(applyLink);
}
HBox startPane = new HBox();
{
JFXButton startButton = new JFXButton(i18n("multiplayer.off.start"));
startButton.getStyleClass().add("jfx-button-raised");
startButton.setButtonType(JFXButton.ButtonType.RAISED);
startButton.setOnMouseClicked(e -> control.start());
startButton.disableProperty().bind(MultiplayerManager.tokenInvalid);
startPane.getChildren().setAll(startButton);
startPane.setAlignment(Pos.CENTER_RIGHT);
}
if (!MultiplayerManager.IS_ADMINISTRATOR)
offPane.getContent().add(hintPane);
offPane.getContent().addAll(tokenPane, startPane);
}
VBox connectingPane = new VBox(8);
ComponentList onPane = new ComponentList();
{
Label label = new Label(i18n("multiplayer.state.connecting"));
BorderPane expirationPane = new BorderPane();
expirationPane.setLeft(new Label(i18n("multiplayer.session.expiration")));
Label expirationLabel = new Label();
expirationLabel.textProperty().bind(Bindings.createStringBinding(() ->
control.getExpireTime() == null ? "" : Locales.SIMPLE_DATE_FORMAT.get().format(control.getExpireTime()),
control.expireTimeProperty()));
expirationPane.setRight(expirationLabel);
connectingPane.getChildren().setAll(label);
GridPane masterPane = new GridPane();
masterPane.setVgap(8);
masterPane.setHgap(16);
ColumnConstraints titleColumn = new ColumnConstraints();
ColumnConstraints valueColumn = new ColumnConstraints();
ColumnConstraints rightColumn = new ColumnConstraints();
masterPane.getColumnConstraints().setAll(titleColumn, valueColumn, rightColumn);
valueColumn.setFillWidth(true);
valueColumn.setHgrow(Priority.ALWAYS);
{
BorderPane titlePane = new BorderPane();
GridPane.setColumnSpan(titlePane, 3);
Label title = new Label(i18n("multiplayer.master"));
titlePane.setLeft(title);
JFXHyperlink tutorial = new JFXHyperlink(i18n("multiplayer.master.video_tutorial"));
titlePane.setRight(tutorial);
tutorial.setOnAction(e -> HMCLService.openRedirectLink("multiplayer-tutorial-master"));
masterPane.addRow(0, titlePane);
HintPane hintPane = new HintPane(MessageType.INFO);
GridPane.setColumnSpan(hintPane, 3);
hintPane.setText(i18n("multiplayer.master.hint"));
masterPane.addRow(1, hintPane);
Label portTitle = new Label(i18n("multiplayer.master.port"));
BorderPane.setAlignment(portTitle, Pos.CENTER_LEFT);
JFXTextField portTextField = new JFXTextField();
GridPane.setColumnSpan(portTextField, 2);
FXUtils.setValidateWhileTextChanged(portTextField, true);
portTextField.getValidators().add(new Validator(i18n("multiplayer.master.port.validate"), (text) -> {
Integer value = Lang.toIntOrNull(text);
return value != null && 0 <= value && value <= 65535;
}));
portTextField.textProperty().bindBidirectional(control.portProperty(), new StringConverter<Number>() {
@Override
public String toString(Number object) {
return Integer.toString(object.intValue());
}
@Override
public Number fromString(String string) {
return Lang.parseInt(string, 0);
}
});
masterPane.addRow(2, portTitle, portTextField);
Label serverAddressTitle = new Label(i18n("multiplayer.master.server_address"));
BorderPane.setAlignment(serverAddressTitle, Pos.CENTER_LEFT);
Label serverAddressLabel = new Label();
BorderPane.setAlignment(serverAddressLabel, Pos.CENTER_LEFT);
serverAddressLabel.textProperty().bind(Bindings.createStringBinding(() -> {
return (control.getAddress() == null ? "" : control.getAddress()) + ":" + control.getPort();
}, control.addressProperty(), control.portProperty()));
JFXButton copyButton = new JFXButton(i18n("multiplayer.master.server_address.copy"));
copyButton.setOnAction(e -> FXUtils.copyText(serverAddressLabel.getText()));
masterPane.addRow(3, serverAddressTitle, serverAddressLabel, copyButton);
}
VBox slavePane = new VBox(8);
{
BorderPane titlePane = new BorderPane();
Label title = new Label(i18n("multiplayer.slave"));
titlePane.setLeft(title);
JFXHyperlink tutorial = new JFXHyperlink(i18n("multiplayer.slave.video_tutorial"));
tutorial.setOnAction(e -> HMCLService.openRedirectLink("multiplayer-tutorial-slave"));
titlePane.setRight(tutorial);
HintPane hintPane = new HintPane(MessageType.INFO);
GridPane.setColumnSpan(hintPane, 3);
hintPane.setText(i18n("multiplayer.slave.hint"));
slavePane.getChildren().add(hintPane);
HintPane hintPane2 = new HintPane(MessageType.WARNING);
GridPane.setColumnSpan(hintPane2, 3);
hintPane2.setText(i18n("multiplayer.slave.hint2"));
slavePane.getChildren().add(hintPane2);
GridPane notBroadcastingPane = new GridPane();
{
notBroadcastingPane.setVgap(8);
notBroadcastingPane.setHgap(16);
notBroadcastingPane.getColumnConstraints().setAll(titleColumn, valueColumn, rightColumn);
Label addressTitle = new Label(i18n("multiplayer.slave.server_address"));
JFXTextField addressField = new JFXTextField();
FXUtils.setValidateWhileTextChanged(addressField, true);
addressField.getValidators().add(new ServerAddressValidator());
JFXButton startButton = new JFXButton(i18n("multiplayer.slave.server_address.start"));
startButton.setOnAction(e -> control.broadcast(addressField.getText()));
notBroadcastingPane.addRow(0, addressTitle, addressField, startButton);
}
GridPane broadcastingPane = new GridPane();
{
broadcastingPane.setVgap(8);
broadcastingPane.setHgap(16);
broadcastingPane.getColumnConstraints().setAll(titleColumn, valueColumn, rightColumn);
Label addressTitle = new Label(i18n("multiplayer.slave.server_address"));
Label addressLabel = new Label();
addressLabel.textProperty().bind(Bindings.createStringBinding(() ->
control.getBroadcaster() != null ? control.getBroadcaster().getAddress() : "",
control.broadcasterProperty()));
JFXButton stopButton = new JFXButton(i18n("multiplayer.slave.server_address.stop"));
stopButton.setOnAction(e -> control.stopBroadcasting());
broadcastingPane.addRow(0, addressTitle, addressLabel, stopButton);
}
FXUtils.onChangeAndOperate(control.broadcasterProperty(), broadcaster -> {
if (broadcaster == null) {
slavePane.getChildren().setAll(titlePane, hintPane, hintPane2, notBroadcastingPane);
} else {
slavePane.getChildren().setAll(titlePane, hintPane, hintPane2, broadcastingPane);
}
});
}
FXUtils.onChangeAndOperate(control.expireTimeProperty(), t -> {
if (t == null) {
onPane.getContent().setAll(masterPane, slavePane);
} else {
onPane.getContent().setAll(expirationPane, masterPane, slavePane);
}
});
}
VBox masterPane = new VBox(8);
{
HintPane masterHintPane = new HintPane();
masterHintPane.setText(i18n("multiplayer.state.master.hint"));
Label label = new Label(i18n("multiplayer.state.master"));
label.textProperty().bind(Bindings.createStringBinding(() ->
i18n("multiplayer.state.master", control.getSession() == null ? "" : control.getSession().getName(), control.getGamePort()),
control.gamePortProperty(), control.sessionProperty()));
Label membersLabel = new Label(i18n("multiplayer.session.create.members"));
VBox clientsPane = new VBox(8);
clients = MappedObservableList.create(control.getClients(), ClientItem::new);
Bindings.bindContent(clientsPane.getChildren(), clients);
masterPane.getChildren().setAll(masterHintPane, label, membersLabel, clientsPane);
}
BorderPane slavePane = new BorderPane();
{
HintPane slaveHintPane = new HintPane();
slaveHintPane.setText(i18n("multiplayer.state.slave.hint"));
slavePane.setTop(slaveHintPane);
Label label = new Label();
label.textProperty().bind(Bindings.createStringBinding(() ->
i18n("multiplayer.state.slave", control.getSession() == null ? "" : control.getSession().getName(), "0.0.0.0:" + control.getGamePort()),
control.sessionProperty(), control.gamePortProperty()));
BorderPane.setAlignment(label, Pos.CENTER_LEFT);
slavePane.setCenter(label);
JFXButton copyButton = new JFXButton(i18n("multiplayer.state.slave.copy"));
copyButton.setOnAction(e -> FXUtils.copyText("0.0.0.0:" + control.getGamePort()));
slavePane.setRight(copyButton);
}
FXUtils.onChangeAndOperate(getSkinnable().multiplayerStateProperty(), state -> {
if (state == MultiplayerManager.State.DISCONNECTED) {
transitionPane.setContent(disconnectedPane, ContainerAnimations.NONE.getAnimationProducer());
} else if (state == MultiplayerManager.State.CONNECTING) {
transitionPane.setContent(connectingPane, ContainerAnimations.NONE.getAnimationProducer());
} else if (state == MultiplayerManager.State.MASTER) {
transitionPane.setContent(masterPane, ContainerAnimations.NONE.getAnimationProducer());
} else if (state == MultiplayerManager.State.SLAVE) {
transitionPane.setContent(slavePane, ContainerAnimations.NONE.getAnimationProducer());
FXUtils.onChangeAndOperate(getSkinnable().sessionProperty(), session -> {
if (session == null) {
mainPane.getChildren().setAll(offPane);
} else {
mainPane.getChildren().setAll(onPane);
}
});
}
ComponentList natDetectionPane = new ComponentList();
ComponentList persistencePane = new ComponentList();
{
GridPane pane = new GridPane();
ColumnConstraints title = new ColumnConstraints();
ColumnConstraints value = new ColumnConstraints();
pane.getColumnConstraints().setAll(title, value);
value.setFillWidth(true);
value.setHgrow(Priority.ALWAYS);
pane.setHgap(16);
pane.setVgap(8);
HintPane hintPane = new HintPane(MessageType.WARNING);
hintPane.setText(i18n("multiplayer.persistence.hint"));
HintPane hintPane = new HintPane(MessageDialogPane.MessageType.INFO);
hintPane.setText(i18n("multiplayer.nat.hint"));
GridPane.setColumnSpan(hintPane, 2);
pane.addRow(0, hintPane);
BorderPane importPane = new BorderPane();
{
Label left = new Label(i18n("multiplayer.persistence.import"));
BorderPane.setAlignment(left, Pos.CENTER_LEFT);
importPane.setLeft(left);
Label natResult = new Label();
natResult.textProperty().bind(BindingMapping.of(getSkinnable().natStateProperty())
.map(MultiplayerPageSkin::getNATType));
pane.addRow(1, new Label(i18n("multiplayer.nat.type")), natResult);
JFXButton importButton = new JFXButton(i18n("multiplayer.persistence.import.button"));
importButton.setOnMouseClicked(e -> {
Path targetPath = MultiplayerManager.getConfigPath(globalConfig().getMultiplayerToken());
if (Files.exists(targetPath)) {
LOG.warning("License file " + targetPath + " already exists");
Controllers.dialog(i18n("multiplayer.persistence.import.file_already_exists"), null, MessageType.ERROR);
return;
}
natDetectionPane.getContent().add(pane);
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle(i18n("multiplayer.persistence.import.title"));
fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter(i18n("multiplayer.persistence.license_file"), "*.yml"));
File file = fileChooser.showOpenDialog(Controllers.getStage());
if (file == null)
return;
CompletableFuture<Boolean> future = new CompletableFuture<>();
if (file.getName().matches("[a-z0-9]{40}.yml") && !targetPath.getFileName().toString().equals(file.getName())) {
Controllers.confirm(i18n("multiplayer.persistence.import.token_not_match"), null, MessageType.QUESTION,
() -> future.complete(true),
() -> future.complete(false)) ;
} else {
future.complete(true);
}
future.thenAcceptAsync(Lang.wrapConsumer(c -> {
if (c) Files.copy(file.toPath(), targetPath);
})).exceptionally(exception -> {
LOG.log(Level.WARNING, "Failed to import license file", exception);
Platform.runLater(() -> Controllers.dialog(i18n("multiplayer.persistence.import.failed"), null, MessageType.ERROR));
return null;
});
});
importButton.disableProperty().bind(MultiplayerManager.tokenInvalid);
importButton.getStyleClass().add("jfx-button-border");
importPane.setRight(importButton);
}
BorderPane exportPane = new BorderPane();
{
Label left = new Label(i18n("multiplayer.persistence.export"));
BorderPane.setAlignment(left, Pos.CENTER_LEFT);
exportPane.setLeft(left);
JFXButton exportButton = new JFXButton(i18n("multiplayer.persistence.export.button"));
exportButton.setOnMouseClicked(e -> {
String token = globalConfig().getMultiplayerToken();
Path configPath = MultiplayerManager.getConfigPath(token);
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle(i18n("multiplayer.persistence.export.title"));
fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter(i18n("multiplayer.persistence.license_file"), "*.yml"));
fileChooser.setInitialFileName(configPath.getFileName().toString());
File file = fileChooser.showSaveDialog(Controllers.getStage());
if (file == null)
return;
CompletableFuture.runAsync(Lang.wrap(() -> MultiplayerManager.downloadHiperConfig(token, configPath)), Schedulers.io())
.handleAsync((ignored, exception) -> {
if (exception != null) {
LOG.log(Level.INFO, "Unable to download hiper config file", e);
}
if (!Files.isRegularFile(configPath)) {
LOG.warning("License file " + configPath + " not exists");
Platform.runLater(() -> Controllers.dialog(i18n("multiplayer.persistence.export.file_not_exists"), null, MessageType.ERROR));
return null;
}
try {
Files.copy(configPath, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException ioException) {
LOG.log(Level.WARNING, "Failed to export license file", ioException);
Platform.runLater(() -> Controllers.dialog(i18n("multiplayer.persistence.export.failed"), null, MessageType.ERROR));
}
return null;
});
});
exportButton.disableProperty().bind(MultiplayerManager.tokenInvalid);
exportButton.getStyleClass().add("jfx-button-border");
exportPane.setRight(exportButton);
}
persistencePane.getContent().setAll(hintPane, importPane, exportPane);
}
ComponentList thanksPane = new ComponentList();
{
GridPane gridPane = new GridPane();
gridPane.getColumnConstraints().setAll(new ColumnConstraints(), FXUtils.getColumnHgrowing(), new ColumnConstraints());
gridPane.setVgap(8);
gridPane.setHgap(16);
// Token acts like password, we hide it here preventing users from accidentally leaking their token when taking screenshots.
JFXPasswordField tokenField = new JFXPasswordField();
tokenField.textProperty().bindBidirectional(globalConfig().multiplayerTokenProperty());
tokenField.setPromptText(i18n("multiplayer.session.create.token.prompt"));
JFXHyperlink applyLink = new JFXHyperlink(i18n("multiplayer.session.create.token.apply"));
applyLink.setOnAction(e -> HMCLService.openRedirectLink("multiplayer-static-token"));
gridPane.addRow(0, new Label(i18n("multiplayer.session.create.token")), tokenField, applyLink);
OptionToggleButton relay = new OptionToggleButton();
relay.disableProperty().bind(tokenField.textProperty().isEmpty());
relay.selectedProperty().bindBidirectional(globalConfig().multiplayerRelayProperty());
relay.setTitle(i18n("multiplayer.relay"));
relay.setSubtitle(i18n("multiplayer.relay.hint"));
HBox pane = new HBox();
pane.setAlignment(Pos.CENTER_LEFT);
@@ -278,64 +440,22 @@ public class MultiplayerPageSkin extends DecoratorAnimatedPage.DecoratorAnimated
HBox.setHgrow(placeholder, Priority.ALWAYS);
pane.getChildren().setAll(
new Label("Based on Cato"),
new Label("Based on HiPer"),
aboutLink,
placeholder,
FXUtils.segmentToTextFlow(i18n("multiplayer.powered_by"), Controllers::onHyperlinkAction));
thanksPane.getContent().addAll(gridPane, relay, pane);
thanksPane.getContent().addAll(pane);
}
content.getChildren().setAll(
ComponentList.createComponentListTitle(i18n("multiplayer.session")),
roomPane,
ComponentList.createComponentListTitle(i18n("multiplayer.nat")),
natDetectionPane,
ComponentList.createComponentListTitle(i18n("settings")),
mainPane,
ComponentList.createComponentListTitle(i18n("multiplayer.persistence")),
persistencePane,
ComponentList.createComponentListTitle(i18n("about")),
thanksPane
);
}
}
public static String getNATType(@Nullable Result<DiscoveryInfo> info) {
if (info == null) {
return i18n("multiplayer.nat.testing");
} else if (info.isError()) {
return i18n("multiplayer.nat.failed");
} else if (info.get().isBlockedUDP()) {
return i18n("multiplayer.nat.type.blocked_udp");
} else if (info.get().isFullCone()) {
return i18n("multiplayer.nat.type.full_cone");
} else if (info.get().isOpenAccess()) {
return i18n("multiplayer.nat.type.open_access");
} else if (info.get().isPortRestrictedCone()) {
return i18n("multiplayer.nat.type.port_restricted_cone");
} else if (info.get().isRestrictedCone()) {
return i18n("multiplayer.nat.type.restricted_cone");
} else if (info.get().isSymmetric()) {
return i18n("multiplayer.nat.type.symmetric");
} else if (info.get().isSymmetricUDPFirewall()) {
return i18n("multiplayer.nat.type.symmetric_udp_firewall");
} else {
return i18n("multiplayer.nat.type.unknown");
}
}
private class ClientItem extends StackPane {
ClientItem(MultiplayerChannel.CatoClient client) {
BorderPane pane = new BorderPane();
pane.setPadding(new Insets(8));
pane.setLeft(new Label(client.getUsername()));
JFXButton kickButton = new JFXButton();
kickButton.setGraphic(SVG.close(Theme.blackFillBinding(), 16, 16));
kickButton.getStyleClass().add("toggle-icon-tiny");
kickButton.setOnAction(e -> getSkinnable().kickPlayer(client));
pane.setRight(kickButton);
RipplerContainer container = new RipplerContainer(pane);
getChildren().setAll(container);
getStyleClass().add("md-list-cell");
}
}
}
@@ -1,238 +0,0 @@
/*
* Hello Minecraft! Launcher
* Copyright (C) 2021 huangyuhui <huanghongxun2008@126.com> and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.jackhuang.hmcl.ui.multiplayer;
import com.google.gson.JsonParseException;
import org.jackhuang.hmcl.event.Event;
import org.jackhuang.hmcl.event.EventManager;
import org.jackhuang.hmcl.util.FutureCallback;
import org.jackhuang.hmcl.util.Lang;
import org.jackhuang.hmcl.util.gson.JsonUtils;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import static org.jackhuang.hmcl.ui.multiplayer.MultiplayerChannel.*;
import static org.jackhuang.hmcl.util.Logging.LOG;
public class MultiplayerServer extends Thread {
private ServerSocket socket;
private final String sessionName;
private final int gamePort;
private final boolean allowAllJoinRequests;
private FutureCallback<CatoClient> onClientAdding;
private final EventManager<MultiplayerChannel.CatoClient> onClientAdded = new EventManager<>();
private final EventManager<MultiplayerChannel.CatoClient> onClientDisconnected = new EventManager<>();
private final EventManager<Event> onKeepAlive = new EventManager<>();
private final EventManager<Event> onHandshake = new EventManager<>();
private final Map<String, Endpoint> clients = new ConcurrentHashMap<>();
private final Map<String, Endpoint> nameClientMap = new ConcurrentHashMap<>();
public MultiplayerServer(String sessionName, int gamePort, boolean allowAllJoinRequests) {
this.sessionName = sessionName;
this.gamePort = gamePort;
this.allowAllJoinRequests = allowAllJoinRequests;
setName("MultiplayerServer");
setDaemon(true);
}
public void setOnClientAdding(FutureCallback<CatoClient> callback) {
onClientAdding = callback;
}
public EventManager<MultiplayerChannel.CatoClient> onClientAdded() {
return onClientAdded;
}
public EventManager<MultiplayerChannel.CatoClient> onClientDisconnected() {
return onClientDisconnected;
}
public EventManager<Event> onKeepAlive() {
return onKeepAlive;
}
public EventManager<Event> onHandshake() {
return onHandshake;
}
public void startServer() throws IOException {
startServer(0);
}
public void startServer(int port) throws IOException {
if (socket != null) {
throw new IllegalStateException("MultiplayerServer already started");
}
socket = new ServerSocket(port);
start();
}
public int getPort() {
if (socket == null) {
throw new IllegalStateException("MultiplayerServer not started");
}
return socket.getLocalPort();
}
@Override
public void run() {
LOG.info("Multiplayer Server listening 127.0.0.1:" + socket.getLocalPort());
try {
while (!isInterrupted()) {
Socket clientSocket = socket.accept();
clientSocket.setSoTimeout(10000);
Lang.thread(() -> handleClient(clientSocket), "MultiplayerServerClientThread", true);
}
} catch (IOException ignored) {
}
}
public void kickPlayer(CatoClient player) {
Endpoint client = nameClientMap.get(player.getUsername());
if (client == null) return;
try {
if (client.socket.isConnected()) {
client.write(new KickResponse(KickResponse.KICKED));
client.socket.close();
}
} catch (IOException e) {
LOG.log(Level.WARNING, "Failed to kick player " + player.getUsername() + ". Maybe already disconnected?", e);
}
}
private void handleClient(Socket targetSocket) {
String address = targetSocket.getRemoteSocketAddress().toString();
String clientName = null;
LOG.info("Accepted client " + address);
try (Socket clientSocket = targetSocket;
BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream(), StandardCharsets.UTF_8));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream(), StandardCharsets.UTF_8))) {
clientSocket.setKeepAlive(true);
Endpoint endpoint = new Endpoint(clientSocket, writer);
clients.put(address, endpoint);
String line;
while ((line = reader.readLine()) != null) {
if (isInterrupted()) {
return;
}
LOG.fine("Message from client " + targetSocket.getRemoteSocketAddress() + ":" + line);
MultiplayerChannel.Request request = JsonUtils.fromNonNullJson(line, MultiplayerChannel.Request.class);
if (request instanceof JoinRequest) {
JoinRequest joinRequest = (JoinRequest) request;
LOG.info("Received join request with clientVersion=" + joinRequest.getClientVersion() + ", id=" + joinRequest.getUsername());
clientName = joinRequest.getUsername();
if (!Objects.equals(MultiplayerManager.CATO_VERSION, joinRequest.getClientVersion())) {
try {
endpoint.write(new KickResponse(KickResponse.VERSION_NOT_MATCHED));
LOG.info("Rejected join request from id=" + joinRequest.getUsername());
socket.close();
} catch (IOException e) {
LOG.log(Level.WARNING, "Failed to send kick response.", e);
return;
}
}
CatoClient catoClient = new CatoClient(this, clientName);
nameClientMap.put(clientName, endpoint);
onClientAdded.fireEvent(catoClient);
if (onClientAdding != null && !allowAllJoinRequests) {
onClientAdding.call(catoClient, () -> {
try {
endpoint.write(new JoinResponse(sessionName, gamePort));
} catch (IOException e) {
LOG.log(Level.WARNING, "Failed to send join response.", e);
try {
socket.close();
} catch (IOException ioException) {
LOG.log(Level.WARNING, "Failed to close socket caused by join response sending failure.", e);
this.interrupt();
}
}
}, msg -> {
try {
endpoint.write(new KickResponse(msg));
LOG.info("Rejected join request from id=" + joinRequest.getUsername());
socket.close();
} catch (IOException e) {
LOG.log(Level.WARNING, "Failed to send kick response.", e);
}
});
} else {
// Allow all join requests.
endpoint.write(new JoinResponse(sessionName, gamePort));
}
} else if (request instanceof KeepAliveRequest) {
endpoint.write(new KeepAliveResponse(System.currentTimeMillis()));
onKeepAlive.fireEvent(new Event(this));
} else if (request instanceof HandshakeRequest) {
endpoint.write(new HandshakeResponse());
onHandshake.fireEvent(new Event(this));
} else {
LOG.log(Level.WARNING, "Unrecognized packet from client " + targetSocket.getRemoteSocketAddress() + ":" + line);
}
}
} catch (IOException e) {
LOG.log(Level.WARNING, "Failed to handle client socket.", e);
} catch (JsonParseException e) {
LOG.log(Level.SEVERE, "Failed to parse client request. This should not happen.", e);
} finally {
if (clientName != null) {
onClientDisconnected.fireEvent(new CatoClient(this, clientName));
}
clients.remove(address);
if (clientName != null) nameClientMap.remove(clientName);
}
}
public static class Endpoint {
public final Socket socket;
public final BufferedWriter writer;
public Endpoint(Socket socket, BufferedWriter writer) {
this.socket = socket;
this.writer = writer;
}
public synchronized void write(Object object) throws IOException {
writer.write(verifyJson(JsonUtils.UGLY_GSON.toJson(object)));
writer.newLine();
writer.flush();
}
}
}
@@ -191,7 +191,10 @@ public class DownloadListPage extends Control implements DecoratorPage, VersionP
}
protected String getLocalizedCategoryIndent(ModDownloadListPageSkin.CategoryIndented category) {
return StringUtils.repeats(' ', category.indent * 4) + getLocalizedCategory(category.getCategory() == null ? "0" : category.getCategory().getId());
return StringUtils.repeats(' ', category.indent * 4) +
(category.getCategory() == null
? i18n("curse.category.0")
: getLocalizedCategory(category.getCategory().getId()));
}
protected String getLocalizedOfficialPage() {
@@ -309,15 +312,17 @@ public class DownloadListPage extends Control implements DecoratorPage, VersionP
categoryComboBox.setPromptText(i18n("mods.category"));
categoryComboBox.getSelectionModel().select(0);
categoryComboBox.setConverter(stringConverter(getSkinnable()::getLocalizedCategoryIndent));
Task.supplyAsync(() -> getSkinnable().repository.getCategories())
.thenAcceptAsync(Schedulers.javafx(), categories -> {
List<CategoryIndented> result = new ArrayList<>();
result.add(new CategoryIndented(0, null));
for (RemoteModRepository.Category category : Lang.toIterable(categories)) {
resolveCategory(category, 0, result);
}
categoryComboBox.getItems().setAll(result);
}).start();
FXUtils.onChangeAndOperate(getSkinnable().downloadSource, downloadSource -> {
Task.supplyAsync(() -> getSkinnable().repository.getCategories())
.thenAcceptAsync(Schedulers.javafx(), categories -> {
List<CategoryIndented> result = new ArrayList<>();
result.add(new CategoryIndented(0, null));
for (RemoteModRepository.Category category : Lang.toIterable(categories)) {
resolveCategory(category, 0, result);
}
categoryComboBox.getItems().setAll(result);
}).start();
});
StackPane sortStackPane = new StackPane();
JFXComboBox<RemoteModRepository.SortType> sortComboBox = new JFXComboBox<>();
@@ -204,14 +204,14 @@ public class DownloadPage extends Control implements DecoratorPage {
return;
}
Controllers.taskDialog(Task.composeAsync(() -> {
Controllers.taskDialog(
Task.composeAsync(() -> {
FileDownloadTask task = new FileDownloadTask(NetworkUtils.toURL(file.getFile().getUrl()), dest, file.getFile().getIntegrityCheck());
task.setName(file.getName());
return task;
}),
i18n("message.downloading"),
TaskCancellationAction.NORMAL
);
TaskCancellationAction.NORMAL);
}
@Override
@@ -261,7 +261,7 @@ public class DownloadPage extends Control implements DecoratorPage {
if (getSkinnable().mod != null) {
JFXHyperlink openMcmodButton = new JFXHyperlink(i18n("mods.mcmod"));
openMcmodButton.setOnAction(e -> FXUtils.openLink(ModManager.getMcmodUrl(getSkinnable().mod.getMcmod())));
openMcmodButton.setOnAction(e -> FXUtils.openLink(getSkinnable().translations.getMcmodUrl(getSkinnable().mod)));
descriptionPane.getChildren().add(openMcmodButton);
if (StringUtils.isNotBlank(getSkinnable().mod.getMcbbs())) {
@@ -261,7 +261,7 @@ class ModListPageSkin extends SkinBase<ModListPage> {
mcmodButton.setText(i18n("mods.mcmod.page"));
mcmodButton.setOnAction(e -> {
fireEvent(new DialogCloseEvent());
FXUtils.openLink(ModManager.getMcmodUrl(modInfo.getMod().getMcmod()));
FXUtils.openLink(ModTranslations.MOD.getMcmodUrl(modInfo.getMod()));
});
getActions().add(mcmodButton);
}
@@ -36,10 +36,25 @@ import static org.jackhuang.hmcl.util.Pair.pair;
*
* @see <a href="https://www.mcmod.cn">mcmod.cn</a>
*/
public final class ModTranslations {
public static ModTranslations MOD = new ModTranslations("/assets/mod_data.txt");
public static ModTranslations MODPACK = new ModTranslations("/assets/modpack_data.txt");
public static ModTranslations EMPTY = new ModTranslations("");
public enum ModTranslations {
MOD("/assets/mod_data.txt") {
@Override
public String getMcmodUrl(Mod mod) {
return String.format("https://www.mcmod.cn/class/%s.html", mod.getMcmod());
}
},
MODPACK("/assets/modpack_data.txt") {
@Override
public String getMcmodUrl(Mod mod) {
return String.format("https://www.mcmod.cn/modpack/%s.html", mod.getMcmod());
}
},
EMPTY("") {
@Override
public String getMcmodUrl(Mod mod) {
return "";
}
};
public static ModTranslations getTranslationsByRepositoryType(RemoteModRepository.Type type) {
switch (type) {
@@ -59,7 +74,7 @@ public final class ModTranslations {
private List<Pair<String, Mod>> keywords;
private int maxKeywordLength = -1;
private ModTranslations(String resourceName) {
ModTranslations(String resourceName) {
this.resourceName = resourceName;
}
@@ -77,6 +92,8 @@ public final class ModTranslations {
return modIdMap.get(id);
}
public abstract String getMcmodUrl(Mod mod);
public List<Mod> searchMod(String query) {
if (!loadKeywords()) return Collections.emptyList();
@@ -90,6 +90,8 @@ public final class VersionSettingsPage extends StackPane implements DecoratorPag
private final OptionToggleButton noJVMArgsPane;
private final OptionToggleButton noGameCheckPane;
private final OptionToggleButton noJVMCheckPane;
private final OptionToggleButton noNativesPatchPane;
private final OptionToggleButton useSoftwareRenderer;
private final OptionToggleButton useNativeGLFWPane;
private final OptionToggleButton useNativeOpenALPane;
private final ComponentSublist javaSublist;
@@ -462,10 +464,14 @@ public final class VersionSettingsPage extends StackPane implements DecoratorPag
pane.getColumnConstraints().setAll(title, value);
txtJVMArgs = new JFXTextField();
txtJVMArgs.setPromptText(i18n("settings.advanced.jvm_args.prompt"));
txtJVMArgs.getStyleClass().add("fit-width");
pane.addRow(0, new Label(i18n("settings.advanced.jvm_args")), txtJVMArgs);
HintPane hintPane = new HintPane();
hintPane.setText(i18n("settings.advanced.jvm_args.prompt"));
GridPane.setColumnSpan(hintPane, 2);
pane.addRow(4, hintPane);
txtMetaspace = new JFXTextField();
txtMetaspace.setPromptText(i18n("settings.advanced.java_permanent_generation_space.prompt"));
txtMetaspace.getStyleClass().add("fit-width");
@@ -508,13 +514,22 @@ public final class VersionSettingsPage extends StackPane implements DecoratorPag
noJVMCheckPane = new OptionToggleButton();
noJVMCheckPane.setTitle(i18n("settings.advanced.dont_check_jvm_validity"));
noNativesPatchPane = new OptionToggleButton();
noNativesPatchPane.setTitle(i18n("settings.advanced.dont_patch_natives"));
useSoftwareRenderer = new OptionToggleButton();
useSoftwareRenderer.setTitle(i18n("settings.advanced.use_software_renderer"));
useNativeGLFWPane = new OptionToggleButton();
useNativeGLFWPane.setTitle(i18n("settings.advanced.use_native_glfw"));
useNativeOpenALPane = new OptionToggleButton();
useNativeOpenALPane.setTitle(i18n("settings.advanced.use_native_openal"));
workaroundPane.getContent().setAll(nativesDirSublist, noJVMArgsPane, noGameCheckPane, noJVMCheckPane, useNativeGLFWPane, useNativeOpenALPane);
workaroundPane.getContent().setAll(
nativesDirSublist,
noJVMArgsPane, noGameCheckPane, noJVMCheckPane, noNativesPatchPane,
useSoftwareRenderer, useNativeGLFWPane, useNativeOpenALPane);
}
rootPane.getChildren().addAll(componentList,
@@ -631,7 +646,9 @@ public final class VersionSettingsPage extends StackPane implements DecoratorPag
noGameCheckPane.selectedProperty().unbindBidirectional(lastVersionSetting.notCheckGameProperty());
noJVMCheckPane.selectedProperty().unbindBidirectional(lastVersionSetting.notCheckJVMProperty());
noJVMArgsPane.selectedProperty().unbindBidirectional(lastVersionSetting.noJVMArgsProperty());
noNativesPatchPane.selectedProperty().unbindBidirectional(lastVersionSetting.notPatchNativesProperty());
showLogsPane.selectedProperty().unbindBidirectional(lastVersionSetting.showLogsProperty());
useSoftwareRenderer.selectedProperty().unbindBidirectional(lastVersionSetting.useSoftwareRendererProperty());
useNativeGLFWPane.selectedProperty().unbindBidirectional(lastVersionSetting.useNativeGLFWProperty());
useNativeOpenALPane.selectedProperty().unbindBidirectional(lastVersionSetting.useNativeOpenALProperty());
FXUtils.unbindEnum(cboLauncherVisibility);
@@ -670,7 +687,9 @@ public final class VersionSettingsPage extends StackPane implements DecoratorPag
noGameCheckPane.selectedProperty().bindBidirectional(versionSetting.notCheckGameProperty());
noJVMCheckPane.selectedProperty().bindBidirectional(versionSetting.notCheckJVMProperty());
noJVMArgsPane.selectedProperty().bindBidirectional(versionSetting.noJVMArgsProperty());
noNativesPatchPane.selectedProperty().bindBidirectional(versionSetting.notPatchNativesProperty());
showLogsPane.selectedProperty().bindBidirectional(versionSetting.showLogsProperty());
useSoftwareRenderer.selectedProperty().bindBidirectional(versionSetting.useSoftwareRendererProperty());
useNativeGLFWPane.selectedProperty().bindBidirectional(versionSetting.useNativeGLFWProperty());
useNativeOpenALPane.selectedProperty().bindBidirectional(versionSetting.useNativeOpenALProperty());
FXUtils.bindEnum(cboLauncherVisibility, versionSetting.launcherVisibilityProperty());
@@ -0,0 +1,553 @@
package org.jackhuang.hmcl.ui.versions;
import com.github.steveice10.opennbt.tag.builtin.*;
import com.jfoenix.controls.JFXComboBox;
import com.jfoenix.controls.JFXTextField;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.ReadOnlyObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Pos;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import org.jackhuang.hmcl.game.World;
import org.jackhuang.hmcl.ui.FXUtils;
import org.jackhuang.hmcl.ui.construct.ComponentList;
import org.jackhuang.hmcl.ui.construct.DoubleValidator;
import org.jackhuang.hmcl.ui.construct.NumberValidator;
import org.jackhuang.hmcl.ui.construct.OptionToggleButton;
import org.jackhuang.hmcl.ui.decorator.DecoratorPage;
import org.jackhuang.hmcl.util.i18n.Locales;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Locale;
import java.util.logging.Level;
import static org.jackhuang.hmcl.util.Logging.LOG;
import static org.jackhuang.hmcl.util.i18n.I18n.i18n;
public final class WorldInfoPage extends StackPane implements DecoratorPage {
private final World world;
private final CompoundTag levelDat;
private final CompoundTag dataTag;
private final ObjectProperty<State> stateProperty = new SimpleObjectProperty<>();
public WorldInfoPage(World world) throws IOException {
this.world = world;
this.levelDat = world.readLevelDat();
this.dataTag = levelDat.get("Data");
CompoundTag worldGenSettings = dataTag.get("WorldGenSettings");
stateProperty.set(State.fromTitle(i18n("world.info.title", world.getWorldName())));
ScrollPane scrollPane = new ScrollPane();
scrollPane.setFitToHeight(true);
scrollPane.setFitToWidth(true);
scrollPane.setVbarPolicy(ScrollPane.ScrollBarPolicy.ALWAYS);
getChildren().setAll(scrollPane);
VBox rootPane = new VBox();
rootPane.setFillWidth(true);
scrollPane.setContent(rootPane);
FXUtils.smoothScrolling(scrollPane);
rootPane.getStyleClass().add("card-list");
ComponentList basicInfo = new ComponentList();
{
BorderPane worldNamePane = new BorderPane();
{
Label label = new Label(i18n("world.name"));
worldNamePane.setLeft(label);
BorderPane.setAlignment(label, Pos.CENTER_LEFT);
Label worldNameLabel = new Label();
worldNameLabel.setText(world.getWorldName());
BorderPane.setAlignment(worldNameLabel, Pos.CENTER_RIGHT);
worldNamePane.setRight(worldNameLabel);
}
BorderPane gameVersionPane = new BorderPane();
{
Label label = new Label(i18n("world.info.game_version"));
BorderPane.setAlignment(label, Pos.CENTER_LEFT);
gameVersionPane.setLeft(label);
Label gameVersionLabel = new Label();
gameVersionLabel.setText(world.getGameVersion());
BorderPane.setAlignment(gameVersionLabel, Pos.CENTER_RIGHT);
gameVersionPane.setRight(gameVersionLabel);
}
BorderPane randomSeedPane = new BorderPane();
{
Label label = new Label(i18n("world.info.random_seed"));
BorderPane.setAlignment(label, Pos.CENTER_LEFT);
randomSeedPane.setLeft(label);
Label randomSeedLabel = new Label();
BorderPane.setAlignment(randomSeedLabel, Pos.CENTER_RIGHT);
randomSeedPane.setRight(randomSeedLabel);
Tag tag = worldGenSettings != null ? worldGenSettings.get("seed") : dataTag.get("RandomSeed");
if (tag instanceof LongTag) {
randomSeedLabel.setText(tag.getValue().toString());
}
}
BorderPane lastPlayedPane = new BorderPane();
{
Label label = new Label(i18n("world.info.last_played"));
BorderPane.setAlignment(label, Pos.CENTER_LEFT);
lastPlayedPane.setLeft(label);
Label lastPlayedLabel = new Label();
lastPlayedLabel.setText(Locales.SIMPLE_DATE_FORMAT.get().format(new Date(world.getLastPlayed())));
BorderPane.setAlignment(lastPlayedLabel, Pos.CENTER_RIGHT);
lastPlayedPane.setRight(lastPlayedLabel);
}
BorderPane timePane = new BorderPane();
{
Label label = new Label(i18n("world.info.time"));
BorderPane.setAlignment(label, Pos.CENTER_LEFT);
timePane.setLeft(label);
Label timeLabel = new Label();
BorderPane.setAlignment(timeLabel, Pos.CENTER_RIGHT);
timePane.setRight(timeLabel);
Tag tag = dataTag.get("Time");
if (tag instanceof LongTag) {
long days = ((LongTag) tag).getValue() / 24000;
timeLabel.setText(i18n("world.info.time.format", days));
}
}
OptionToggleButton allowCheatsButton = new OptionToggleButton();
{
allowCheatsButton.setTitle(i18n("world.info.allow_cheats"));
Tag tag = dataTag.get("allowCommands");
if (tag instanceof ByteTag) {
ByteTag byteTag = (ByteTag) tag;
byte value = byteTag.getValue();
if (value == 0 || value == 1) {
allowCheatsButton.setSelected(value == 1);
allowCheatsButton.selectedProperty().addListener((o, oldValue, newValue) -> {
byteTag.setValue(newValue ? (byte) 1 : (byte) 0);
saveLevelDat();
});
} else {
allowCheatsButton.setDisable(true);
}
} else {
allowCheatsButton.setDisable(true);
}
}
OptionToggleButton generateFeaturesButton = new OptionToggleButton();
{
generateFeaturesButton.setTitle(i18n("world.info.generate_features"));
Tag tag = worldGenSettings != null ? worldGenSettings.get("generate_features") : dataTag.get("MapFeatures");
if (tag instanceof ByteTag) {
ByteTag byteTag = (ByteTag) tag;
byte value = byteTag.getValue();
if (value == 0 || value == 1) {
generateFeaturesButton.setSelected(value == 1);
generateFeaturesButton.selectedProperty().addListener((o, oldValue, newValue) -> {
byteTag.setValue(newValue ? (byte) 1 : (byte) 0);
saveLevelDat();
});
} else {
generateFeaturesButton.setDisable(true);
}
} else {
generateFeaturesButton.setDisable(true);
}
}
BorderPane difficultyPane = new BorderPane();
{
Label label = new Label(i18n("world.info.difficulty"));
BorderPane.setAlignment(label, Pos.CENTER_LEFT);
difficultyPane.setLeft(label);
JFXComboBox<Difficulty> difficultyBox = new JFXComboBox<>(Difficulty.items);
BorderPane.setAlignment(difficultyBox, Pos.CENTER_RIGHT);
difficultyPane.setRight(difficultyBox);
Tag tag = dataTag.get("Difficulty");
if (tag instanceof ByteTag) {
ByteTag byteTag = (ByteTag) tag;
Difficulty difficulty = Difficulty.of(byteTag.getValue());
if (difficulty != null) {
difficultyBox.setValue(difficulty);
difficultyBox.valueProperty().addListener((o, oldValue, newValue) -> {
if (newValue != null) {
byteTag.setValue((byte) newValue.ordinal());
saveLevelDat();
}
});
} else {
difficultyBox.setDisable(true);
}
} else {
difficultyBox.setDisable(true);
}
}
basicInfo.getContent().setAll(
worldNamePane, gameVersionPane, randomSeedPane, lastPlayedPane, timePane,
allowCheatsButton, generateFeaturesButton, difficultyPane);
rootPane.getChildren().addAll(ComponentList.createComponentListTitle(i18n("world.info.basic")), basicInfo);
}
Tag playerTag = dataTag.get("Player");
if (playerTag instanceof CompoundTag) {
CompoundTag player = (CompoundTag) playerTag;
ComponentList playerInfo = new ComponentList();
BorderPane locationPane = new BorderPane();
{
Label label = new Label(i18n("world.info.player.location"));
BorderPane.setAlignment(label, Pos.CENTER_LEFT);
locationPane.setLeft(label);
Label locationLabel = new Label();
BorderPane.setAlignment(locationLabel, Pos.CENTER_RIGHT);
locationPane.setRight(locationLabel);
Dimension dim = Dimension.of(player.get("Dimension"));
if (dim != null) {
String posString = dim.formatPosition(player.get("Pos"));
if (posString != null)
locationLabel.setText(posString);
}
}
BorderPane lastDeathLocationPane = new BorderPane();
{
Label label = new Label(i18n("world.info.player.last_death_location"));
BorderPane.setAlignment(label, Pos.CENTER_LEFT);
lastDeathLocationPane.setLeft(label);
Label lastDeathLocationLabel = new Label();
BorderPane.setAlignment(lastDeathLocationLabel, Pos.CENTER_RIGHT);
lastDeathLocationPane.setRight(lastDeathLocationLabel);
Tag tag = player.get("LastDeathLocation");
if (tag instanceof CompoundTag) {
Dimension dim = Dimension.of(((CompoundTag) tag).get("dimension"));
if (dim != null) {
String posString = dim.formatPosition(((CompoundTag) tag).get("pos"));
if (posString != null)
lastDeathLocationLabel.setText(posString);
}
}
}
BorderPane spawnPane = new BorderPane();
{
Label label = new Label(i18n("world.info.player.spawn"));
BorderPane.setAlignment(label, Pos.CENTER_LEFT);
spawnPane.setLeft(label);
Label spawnLabel = new Label();
BorderPane.setAlignment(spawnLabel, Pos.CENTER_RIGHT);
spawnPane.setRight(spawnLabel);
Dimension dim = Dimension.of(player.get("SpawnDimension"));
if (dim != null) {
Tag x = player.get("SpawnX");
Tag y = player.get("SpawnY");
Tag z = player.get("SpawnZ");
if (x instanceof IntTag && y instanceof IntTag && z instanceof IntTag)
spawnLabel.setText(dim.formatPosition(((IntTag) x).getValue(), ((IntTag) y).getValue(), ((IntTag) z).getValue()));
}
}
BorderPane playerGameTypePane = new BorderPane();
{
Label label = new Label(i18n("world.info.player.game_type"));
BorderPane.setAlignment(label, Pos.CENTER_LEFT);
playerGameTypePane.setLeft(label);
JFXComboBox<GameType> gameTypeBox = new JFXComboBox<>(GameType.items);
BorderPane.setAlignment(gameTypeBox, Pos.CENTER_RIGHT);
playerGameTypePane.setRight(gameTypeBox);
Tag tag = player.get("playerGameType");
if (tag instanceof IntTag) {
IntTag intTag = (IntTag) tag;
GameType gameType = GameType.of(intTag.getValue());
if (gameType != null) {
gameTypeBox.setValue(gameType);
gameTypeBox.valueProperty().addListener((o, oldValue, newValue) -> {
if (newValue != null) {
intTag.setValue(newValue.ordinal());
saveLevelDat();
}
});
} else {
gameTypeBox.setDisable(true);
}
} else {
gameTypeBox.setDisable(true);
}
}
BorderPane healthPane = new BorderPane();
{
Label label = new Label(i18n("world.info.player.health"));
BorderPane.setAlignment(label, Pos.CENTER_LEFT);
healthPane.setLeft(label);
JFXTextField healthField = new JFXTextField();
healthField.setPrefWidth(50);
healthField.setAlignment(Pos.CENTER_RIGHT);
BorderPane.setAlignment(healthField, Pos.CENTER_RIGHT);
healthPane.setRight(healthField);
Tag tag = player.get("Health");
if (tag instanceof FloatTag) {
FloatTag floatTag = (FloatTag) tag;
healthField.setText(new DecimalFormat("#").format(floatTag.getValue().floatValue()));
healthField.textProperty().addListener((o, oldValue, newValue) -> {
if (newValue != null) {
try {
floatTag.setValue(Float.parseFloat(newValue));
saveLevelDat();
} catch (Throwable ignored) {
}
}
});
FXUtils.setValidateWhileTextChanged(healthField, true);
healthField.setValidators(new DoubleValidator(i18n("input.number"), true));
} else {
healthField.setDisable(true);
}
}
BorderPane foodLevelPane = new BorderPane();
{
Label label = new Label(i18n("world.info.player.food_level"));
BorderPane.setAlignment(label, Pos.CENTER_LEFT);
foodLevelPane.setLeft(label);
JFXTextField foodLevelField = new JFXTextField();
foodLevelField.setPrefWidth(50);
foodLevelField.setAlignment(Pos.CENTER_RIGHT);
BorderPane.setAlignment(foodLevelField, Pos.CENTER_RIGHT);
foodLevelPane.setRight(foodLevelField);
Tag tag = player.get("foodLevel");
if (tag instanceof IntTag) {
IntTag intTag = (IntTag) tag;
foodLevelField.setText(String.valueOf(intTag.getValue()));
foodLevelField.textProperty().addListener((o, oldValue, newValue) -> {
if (newValue != null) {
try {
intTag.setValue(Integer.parseInt(newValue));
saveLevelDat();
} catch (Throwable ignored) {
}
}
});
FXUtils.setValidateWhileTextChanged(foodLevelField, true);
foodLevelField.setValidators(new NumberValidator(i18n("input.number"), true));
} else {
foodLevelField.setDisable(true);
}
}
BorderPane xpLevelPane = new BorderPane();
{
Label label = new Label(i18n("world.info.player.xp_level"));
BorderPane.setAlignment(label, Pos.CENTER_LEFT);
xpLevelPane.setLeft(label);
JFXTextField xpLevelField = new JFXTextField();
xpLevelField.setPrefWidth(50);
xpLevelField.setAlignment(Pos.CENTER_RIGHT);
BorderPane.setAlignment(xpLevelField, Pos.CENTER_RIGHT);
xpLevelPane.setRight(xpLevelField);
Tag tag = player.get("XpLevel");
if (tag instanceof IntTag) {
IntTag intTag = (IntTag) tag;
xpLevelField.setText(String.valueOf(intTag.getValue()));
xpLevelField.textProperty().addListener((o, oldValue, newValue) -> {
if (newValue != null) {
try {
intTag.setValue(Integer.parseInt(newValue));
saveLevelDat();
} catch (Throwable ignored) {
}
}
});
FXUtils.setValidateWhileTextChanged(xpLevelField, true);
xpLevelField.setValidators(new NumberValidator(i18n("input.number"), true));
} else {
xpLevelField.setDisable(true);
}
}
playerInfo.getContent().setAll(
locationPane, lastDeathLocationPane, spawnPane,
playerGameTypePane, healthPane, foodLevelPane, xpLevelPane
);
rootPane.getChildren().addAll(ComponentList.createComponentListTitle(i18n("world.info.player")), playerInfo);
}
}
private void saveLevelDat() {
LOG.info("Saving level.dat of world " + world.getWorldName());
try {
this.world.writeLevelDat(levelDat);
} catch (IOException e) {
LOG.log(Level.WARNING, "Failed to save level.dat of world " + world.getWorldName(), e);
}
}
@Override
public ReadOnlyObjectProperty<State> stateProperty() {
return stateProperty;
}
private static final class Dimension {
static final Dimension OVERWORLD = new Dimension(null);
static final Dimension THE_NETHER = new Dimension(i18n("world.info.dimension.the_nether"));
static final Dimension THE_END = new Dimension(i18n("world.info.dimension.the_end"));
final String name;
static Dimension of(Tag tag) {
if (tag instanceof IntTag) {
switch (((IntTag) tag).getValue()) {
case 0:
return OVERWORLD;
case 1:
return THE_NETHER;
case 2:
return THE_END;
default:
return null;
}
} else if (tag instanceof StringTag) {
String id = ((StringTag) tag).getValue();
switch (id) {
case "overworld":
case "minecraft:overworld":
return OVERWORLD;
case "the_nether":
case "minecraft:the_nether":
return THE_NETHER;
case "the_end":
case "minecraft:the_end":
return THE_END;
default:
return new Dimension(id);
}
} else {
return null;
}
}
private Dimension(String name) {
this.name = name;
}
String formatPosition(Tag tag) {
if (tag instanceof ListTag) {
ListTag listTag = (ListTag) tag;
if (listTag.size() != 3)
return null;
Tag x = listTag.get(0);
Tag y = listTag.get(1);
Tag z = listTag.get(2);
if (x instanceof DoubleTag && y instanceof DoubleTag && z instanceof DoubleTag) {
//noinspection MalformedFormatString
return this == OVERWORLD
? String.format("(%.2f, %.2f, %.2f)", x.getValue(), y.getValue(), z.getValue())
: String.format("%s (%.2f, %.2f, %.2f)", name, x.getValue(), y.getValue(), z.getValue());
}
return null;
}
if (tag instanceof IntArrayTag) {
IntArrayTag intArrayTag = (IntArrayTag) tag;
int x = intArrayTag.getValue(0);
int y = intArrayTag.getValue(1);
int z = intArrayTag.getValue(2);
return this == OVERWORLD
? String.format("(%d, %d, %d)", x, y, z)
: String.format("%s (%d, %d, %d)", name, x, y, z);
}
return null;
}
String formatPosition(int x, int y, int z) {
return this == OVERWORLD
? String.format("(%d, %d, %d)", x, y, z)
: String.format("%s (%d, %d, %d)", name, x, y, z);
}
String formatPosition(double x, double y, double z) {
return this == OVERWORLD
? String.format("(%.2f, %.2f, %.2f)", x, y, z)
: String.format("%s (%.2f, %.2f, %.2f)", name, x, y, z);
}
}
private enum Difficulty {
PEACEFUL, EASY, NORMAL, HARD;
static final ObservableList<Difficulty> items = FXCollections.observableList(Arrays.asList(values()));
static Difficulty of(int d) {
return d >= 0 && d <= items.size() ? items.get(d) : null;
}
@Override
public String toString() {
return i18n("world.info.difficulty." + name().toLowerCase(Locale.ROOT));
}
}
private enum GameType {
SURVIVAL, CREATIVE, ADVENTURE, SPECTATOR;
static final ObservableList<GameType> items = FXCollections.observableList(Arrays.asList(values()));
static GameType of(int d) {
return d >= 0 && d <= items.size() ? items.get(d) : null;
}
@Override
public String toString() {
return i18n("world.info.player.game_type." + name().toLowerCase(Locale.ROOT));
}
}
}
@@ -50,6 +50,8 @@ public class WorldListItem extends Control {
title.set(parseColorEscapes(world.getWorldName()));
subtitle.set(i18n("world.description", world.getFileName(), Locales.SIMPLE_DATE_FORMAT.get().format(new Date(world.getLastPlayed())), world.getGameVersion() == null ? i18n("message.unknown") : world.getGameVersion()));
setOnMouseClicked(event -> showInfo());
}
@Override
@@ -99,4 +101,12 @@ public class WorldListItem extends Control {
}
Controllers.navigate(new DatapackListPage(world.getWorldName(), world.getFile()));
}
public void showInfo() {
try {
Controllers.navigate(new WorldInfoPage(world));
} catch (Exception e) {
// TODO
}
}
}
@@ -43,7 +43,9 @@ final class ExecutableHeaderHelper {
private ExecutableHeaderHelper() {}
private static Map<String, String> suffix2header = mapOf(
pair("exe", "assets/HMCLauncher.exe"));
pair("exe", "assets/HMCLauncher.exe"),
pair("sh", "assets/HMCLauncher.sh")
);
private static Optional<String> getSuffix(Path file) {
String filename = file.getFileName().toString();
@@ -47,6 +47,7 @@ public class CrashReporter implements Thread.UncaughtExceptionHandler {
pair("javafx.fxml.LoadException", i18n("crash.NoClassDefFound")),
pair("Location is not set", i18n("crash.NoClassDefFound")),
pair("UnsatisfiedLinkError", i18n("crash.user_fault")),
pair("java.time.zone.ZoneRulesException: Unable to load TZDB time-zone rules", i18n("crash.user_fault")),
pair("java.lang.NoClassDefFoundError", i18n("crash.NoClassDefFound")),
pair("org.jackhuang.hmcl.util.ResourceNotFoundError", i18n("crash.NoClassDefFound")),
pair("java.lang.VerifyError", i18n("crash.NoClassDefFound")),
@@ -20,6 +20,8 @@ package org.jackhuang.hmcl.util;
import java.nio.file.Path;
import java.util.Set;
import static org.jackhuang.hmcl.util.Logging.LOG;
/**
* Utility for Adding JavaFX to module path.
*
@@ -30,6 +32,6 @@ public final class JavaFXPatcher {
}
public static void patch(Set<String> modules, Path... jarPaths) {
// Nothing to do with Java 8
LOG.info("No need to patch JavaFX with Java 8");
}
}
@@ -0,0 +1,114 @@
package org.jackhuang.hmcl.util;
import com.google.gson.reflect.TypeToken;
import org.jackhuang.hmcl.game.Library;
import org.jackhuang.hmcl.game.NativesDirectoryType;
import org.jackhuang.hmcl.game.Version;
import org.jackhuang.hmcl.setting.VersionSetting;
import org.jackhuang.hmcl.util.gson.JsonUtils;
import org.jackhuang.hmcl.util.platform.Architecture;
import org.jackhuang.hmcl.util.platform.JavaVersion;
import org.jackhuang.hmcl.util.platform.OperatingSystem;
import org.jackhuang.hmcl.util.versioning.VersionNumber;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.*;
import java.util.logging.Level;
import static org.jackhuang.hmcl.util.Logging.LOG;
public final class NativePatcher {
private NativePatcher() {
}
private static final Library NONEXISTENT_LIBRARY = new Library(null);
public static Version patchNative(Version version, String gameVersion, JavaVersion javaVersion, VersionSetting settings) {
if (settings.isNotPatchNatives())
return version;
if (settings.getNativesDirType() == NativesDirectoryType.CUSTOM) {
if (gameVersion != null && VersionNumber.VERSION_COMPARATOR.compare(gameVersion, "1.19") < 0)
return version;
ArrayList<Library> newLibraries = new ArrayList<>();
for (Library library : version.getLibraries()) {
if (!library.appliesToCurrentEnvironment())
continue;
if (library.getClassifier() == null
|| !library.getArtifactId().startsWith("lwjgl")
|| !library.getClassifier().startsWith("natives")) {
newLibraries.add(library);
}
}
return version.setLibraries(newLibraries);
}
if (javaVersion.getArchitecture().isX86())
return version;
if (javaVersion.getPlatform().getOperatingSystem() == OperatingSystem.OSX
&& javaVersion.getArchitecture() == Architecture.ARM64
&& gameVersion != null
&& VersionNumber.VERSION_COMPARATOR.compare(gameVersion, "1.19") >= 0)
return version;
Map<String, Library> replacements = Hole.nativeReplacement.get(javaVersion.getPlatform().toString());
if (replacements == null) {
LOG.warning("No alternative native library provided for platform " + javaVersion.getPlatform());
return version;
}
ArrayList<Library> newLibraries = new ArrayList<>();
for (Library library : version.getLibraries()) {
if (!library.appliesToCurrentEnvironment())
continue;
if (library.isNative()) {
Library replacement = replacements.getOrDefault(library.getName() + ":natives", NONEXISTENT_LIBRARY);
if (replacement == NONEXISTENT_LIBRARY) {
if (!(settings.isUseNativeGLFW() && library.getArtifactId().contains("glfw"))
&& !(settings.isUseNativeOpenAL() && library.getArtifactId().contains("openal"))) {
LOG.warning("No alternative native library " + library.getName() + " provided for platform " + javaVersion.getPlatform());
return version;
}
newLibraries.add(library);
} else if (replacement != null) {
newLibraries.add(replacement);
}
} else {
Library replacement = replacements.getOrDefault(library.getName(), NONEXISTENT_LIBRARY);
if (replacement == NONEXISTENT_LIBRARY) {
newLibraries.add(library);
} else if (replacement != null) {
newLibraries.add(replacement);
}
}
}
return version.setLibraries(newLibraries);
}
public static Library getSoftwareRendererLoader(JavaVersion javaVersion) {
Map<String, Library> map = Hole.nativeReplacement.get(javaVersion.getPlatform().toString());
return map != null ? map.get("software-renderer-loader") : null;
}
private static final class Hole {
static Map<String, Map<String, Library>> nativeReplacement;
static {
//noinspection ConstantConditions
try (Reader reader = new InputStreamReader(NativePatcher.class.getResourceAsStream("/assets/natives.json"))) {
nativeReplacement = JsonUtils.GSON.fromJson(reader, new TypeToken<Map<String, Map<String, Library>>>() {
}.getType());
} catch (IOException e) {
nativeReplacement = Collections.emptyMap();
LOG.log(Level.WARNING, "Failed to load native library list", e);
}
}
}
}
Binary file not shown.
@@ -0,0 +1,183 @@
#!/usr/bin/env bash
set -e
# Switch message language
if [ -z "${LANG##zh_*}" ]; then
_HMCL_USE_CHINESE=true
else
_HMCL_USE_CHINESE=false
fi
# _HMCL_OS
case "$OSTYPE" in
linux*)
_HMCL_OS="linux";;
darwin*)
_HMCL_OS="osx";;
msys*|cygwin*)
_HMCL_OS="windows";;
*)
_HMCL_OS="unknown";;
esac
# Normalize _HMCL_ARCH
case "$(uname -m)" in
x86_64|x86-64|amd64|em64t|x64)
_HMCL_ARCH="x86_64";;
x86_32|x86-32|x86|ia32|i386|i486|i586|i686|i86pc|x32)
_HMCL_ARCH="x86";;
arm64|aarch64|armv8*|armv9*)
_HMCL_ARCH="arm64";;
arm|arm32|aarch32|armv7*)
_HMCL_ARCH="arm32";;
loongarch64)
_HMCL_ARCH="loongarch64";;
*)
_HMCL_ARCH="unknown";;
esac
# Self path
_HMCL_PATH="${BASH_SOURCE[0]}"
_HMCL_DIR=$(dirname "$_HMCL_PATH")
if [ "$_HMCL_OS" == "windows" ]; then
_HMCL_JAVA_EXE_NAME="java.exe"
else
_HMCL_JAVA_EXE_NAME="java"
fi
# _HMCL_VM_OPTIONS
if [ -n "${HMCL_JAVA_OPTS+x}" ]; then
_HMCL_VM_OPTIONS=${HMCL_JAVA_OPTS}
else
_HMCL_VM_OPTIONS="-XX:MinHeapFreeRatio=5 -XX:MaxHeapFreeRatio=15"
fi
# First, find Java in HMCL_JAVA_HOME
if [ -n "${HMCL_JAVA_HOME+x}" ]; then
if [ -x "$HMCL_JAVA_HOME/bin/$_HMCL_JAVA_EXE_NAME" ]; then
"$HMCL_JAVA_HOME/bin/$_HMCL_JAVA_EXE_NAME" $_HMCL_VM_OPTIONS -jar "$_HMCL_PATH"
exit 0
else
if [ "$_HMCL_USE_CHINESE" == true ]; then
echo "环境变量 HMCL_JAVA_HOME 的值无效,请设置为合法的 Java 路径。" 1>&2
else
echo "The value of the environment variable HMCL_JAVA_HOME is invalid, please set it to a valid Java path." 1>&2
fi
exit 1
fi
fi
# Find Java in HMCL_DIR
case "$_HMCL_ARCH" in
x86_64)
if [ -x "$_HMCL_DIR/jre-x64/bin/$_HMCL_JAVA_EXE_NAME" ]; then
"$_HMCL_DIR/jre-x64/bin/$_HMCL_JAVA_EXE_NAME" $_HMCL_VM_OPTIONS -jar "$_HMCL_PATH"
exit 0
fi
if [ -x "$_HMCL_DIR/jre-x86/bin/$_HMCL_JAVA_EXE_NAME" ]; then
"$_HMCL_DIR/jre-x86/bin/$_HMCL_JAVA_EXE_NAME" $_HMCL_VM_OPTIONS -jar "$_HMCL_PATH"
exit 0
fi
;;
x86)
if [ -x "$_HMCL_DIR/jre-x86/bin/$_HMCL_JAVA_EXE_NAME" ]; then
"$_HMCL_DIR/jre-x86/bin/$_HMCL_JAVA_EXE_NAME" $_HMCL_VM_OPTIONS -jar "$_HMCL_PATH"
exit 0
fi
;;
arm64)
if [ -x "$_HMCL_DIR/jre-arm64/bin/$_HMCL_JAVA_EXE_NAME" ]; then
"$_HMCL_DIR/jre-arm64/bin/$_HMCL_JAVA_EXE_NAME" $_HMCL_VM_OPTIONS -jar "$_HMCL_PATH"
exit 0
fi
;;
arm32)
if [ -x "$_HMCL_DIR/jre-arm32/bin/$_HMCL_JAVA_EXE_NAME" ]; then
"$_HMCL_DIR/jre-arm32/bin/$_HMCL_JAVA_EXE_NAME" $_HMCL_VM_OPTIONS -jar "$_HMCL_PATH"
exit 0
fi
;;
loongarch64)
if [ -x "$_HMCL_DIR/jre-loongarch64/bin/$_HMCL_JAVA_EXE_NAME" ]; then
"$_HMCL_DIR/jre-loongarch64/bin/$_HMCL_JAVA_EXE_NAME" $_HMCL_VM_OPTIONS -jar "$_HMCL_PATH"
exit 0
fi
;;
esac
# Find Java in JAVA_HOME
if [ -f "$JAVA_HOME/bin/$_HMCL_JAVA_EXE_NAME" ]; then
"$JAVA_HOME/bin/$_HMCL_JAVA_EXE_NAME" $_HMCL_VM_OPTIONS -jar "$_HMCL_PATH"
exit 0
fi
# Find Java in PATH
if [ -x "$(command -v $_HMCL_JAVA_EXE_NAME)" ]; then
$_HMCL_JAVA_EXE_NAME $_HMCL_VM_OPTIONS -jar "$_HMCL_PATH"
exit 0
fi
# Java not found
if [[ "$_HMCL_OS" == "unknown" || "$_HMCL_ARCH" == "unknown" ]]; then
if [ "$_HMCL_USE_CHINESE" == true ]; then
echo "运行 HMCL 需要 Java 运行时环境,请安装 Java 并设置环境变量后重试。" 1>&2
else
echo "The Java runtime environment is required to run HMCL. " 1>&2
echo "Please install Java and set the environment variables and try again." 1>&2
fi
exit 1
fi
if [[ "$_HMCL_ARCH" == "loongarch64" ]]; then
if [ "$_HMCL_USE_CHINESE" == true ]; then
echo "运行 HMCL 需要 Java 运行时环境,请安装龙芯 JDK8 (http://www.loongnix.cn/zh/api/java/downloads-jdk8/index.html) 并设置环境变量后重试。" 1>&2
else
echo "The Java runtime environment is required to run HMCL." 1>&2
echo "Please install Loongson JDK8 (http://www.loongnix.cn/zh/api/java/downloads-jdk8/index.html) and set the environment variables, then try again." 1>&2
fi
exit 1
fi
case "$_HMCL_OS" in
linux)
_HMCL_DOWNLOAD_PAGE_OS="&os=Linux";;
osx)
_HMCL_DOWNLOAD_PAGE_OS="&os=macOS";;
windows)
_HMCL_DOWNLOAD_PAGE_OS="&os=Windows";;
*)
echo "Unknown os: $_HMCL_OS" 1>&2
exit 1
;;
esac
case "$_HMCL_ARCH" in
arm64)
_HMCL_DOWNLOAD_PAGE_ARCH="&bitness=64-bit&architecture=ARM";;
arm32)
_HMCL_DOWNLOAD_PAGE_ARCH="&bitness=32-bit&architecture=ARM";;
x86_64)
_HMCL_DOWNLOAD_PAGE_ARCH="&bitness=64-bit&architecture=x86";;
x86)
_HMCL_DOWNLOAD_PAGE_ARCH="&bitness=32-bit&architecture=x86";;
*)
echo "Unknown architecture: $_HMCL_ARCH" 1>&2
exit 1
;;
esac
_HMCL_DOWNLOAD_PAGE="https://bell-sw.com/pages/downloads/?version=java-17-lts$_HMCL_DOWNLOAD_PAGE_OS$_HMCL_DOWNLOAD_PAGE_ARCH&package=jdk-full"
if [ "$_HMCL_USE_CHINESE" == true ]; then
echo "运行 HMCL 需要 Java 运行时环境,请安装 Java 并设置环境变量后重试。" 1>&2
echo "$_HMCL_DOWNLOAD_PAGE" 1>&2
else
echo "The Java runtime environment is required to run HMCL. " 1>&2
echo "Please install Java and set the environment variables and try again." 1>&2
echo "$_HMCL_DOWNLOAD_PAGE" 1>&2
fi
exit 1
+28 -1
View File
@@ -315,6 +315,33 @@
-fx-cursor: hand;
}
.installer-item {
-fx-padding: 8px;
}
.installer-item:list-item {
-fx-border-color: #e0e0e0;
-fx-border-width: 0 0 1 0;
-fx-alignment: center-left;
}
.installer-item:list-item > .installer-item-name {
-fx-pref-width: 80px;
}
.installer-item:list-item > .installer-item-status {
-fx-max-width: infinity;
}
.installer-item:card {
-fx-background-color: white;
-fx-background-radius: 4;
-fx-alignment: center;
-fx-pref-width: 180px;
-fx-effect: dropshadow(gaussian, rgba(0, 0, 0, 0.26), 10, 0.12, -1, 2);
}
/*******************************************************************************
* *
* Main Page *
@@ -858,7 +885,7 @@
-fx-background-radius: 4;
-fx-padding: 8px;
-fx-effect: dropshadow(gaussian, rgba(0, 0, 0, 0.26), 10, 0.12, -1, 2);
-fx-effect: dropshadow(gaussian, rgba(0, 0, 0, 0.26), 5, 0.06, -0.5, 1);
}
.card:selected {
@@ -18,7 +18,7 @@
<JFXTextField fx:id="txtServerUrl" promptText="%account.injector.server_url" onAction="#onAddNext" />
</body>
<actions>
<Label fx:id="lblCreationWarning" />
<Label fx:id="lblCreationWarning" wrapText="true" />
<HBox>
<JFXButton onMouseClicked="#onAddCancel" text="%button.cancel" styleClass="dialog-cancel" />
<SpinnerPane fx:id="nextPane" styleClass="small-spinner-pane">
@@ -17,12 +17,12 @@
<SpinnerPane fx:id="spinnerPane" styleClass="large-spinner-pane">
<VBox fx:id="borderPane" alignment="CENTER" FXUtils.limitWidth="500">
<ComponentList>
<BorderPane><left><Label text="%modpack.task.install.will" /></left><right><Label fx:id="lblModpackLocation" /></right></BorderPane>
<BorderPane><left><Label BorderPane.alignment="CENTER_LEFT" text="%archive.name" /></left><right><JFXTextField fx:id="txtModpackName" StackPane.margin="$insets" /></right></BorderPane>
<BorderPane><left><Label text="%modpack.task.install.will" /></left><center><Label BorderPane.alignment="CENTER_RIGHT" fx:id="lblModpackLocation" /></center></BorderPane>
<BorderPane><left><Label BorderPane.alignment="CENTER_LEFT" text="%archive.name" /></left><center><JFXTextField BorderPane.alignment="CENTER_RIGHT" fx:id="txtModpackName" StackPane.margin="$insets" /></center></BorderPane>
<BorderPane><left><Label text="%modpack.name"/></left><right><Label fx:id="lblName" /></right></BorderPane>
<BorderPane><left><Label text="%archive.version"/></left><right><Label fx:id="lblVersion" /></right></BorderPane>
<BorderPane><left><Label text="%archive.author"/></left><right><Label fx:id="lblAuthor" /></right></BorderPane>
<BorderPane><left><Label text="%modpack.name"/></left><center><Label BorderPane.alignment="CENTER_RIGHT" fx:id="lblName" /></center></BorderPane>
<BorderPane><left><Label text="%archive.version"/></left><center><Label BorderPane.alignment="CENTER_RIGHT" fx:id="lblVersion" /></center></BorderPane>
<BorderPane><left><Label text="%archive.author"/></left><center><Label BorderPane.alignment="CENTER_RIGHT" fx:id="lblAuthor" /></center></BorderPane>
<BorderPane>
<left><JFXButton fx:id="btnDescription" onMouseClicked="#onDescribe" text="%modpack.description" styleClass="jfx-button-border" /></left>
<right><JFXButton buttonType="RAISED" fx:id="btnInstall" onMouseClicked="#onInstall" text="%button.install" styleClass="jfx-button-raised" /></right>
@@ -1,6 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<?import com.jfoenix.controls.JFXButton?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.*?>
<?import java.lang.String?>
@@ -8,18 +7,18 @@
xmlns:fx="http://javafx.com/fxml"
type="StackPane">
<HBox spacing="8" styleClass="jfx-dialog-layout">
<Label fx:id="graphic" translateX="10" translateY="10" minWidth="40" maxWidth="40" minHeight="40" maxHeight="40" />
<Label fx:id="graphic" translateX="10" translateY="10" minWidth="40" maxWidth="40" minHeight="40"
maxHeight="40"/>
<VBox HBox.hgrow="ALWAYS">
<StackPane>
<styleClass>
<String fx:value="jfx-layout-heading" />
<String fx:value="title" />
<String fx:value="jfx-layout-heading"/>
<String fx:value="title"/>
</styleClass>
<Label fx:id="title" text="%message.info" />
<Label fx:id="title" text="%message.info"/>
</StackPane>
<StackPane fx:id="content" styleClass="jfx-layout-body">
</StackPane>
<HBox fx:id="actions" styleClass="jfx-layout-actions" />
<StackPane fx:id="content" styleClass="jfx-layout-body"/>
<HBox fx:id="actions" styleClass="jfx-layout-actions"/>
</VBox>
</HBox>
</fx:root>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 999 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 912 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1001 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 861 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 958 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 988 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 947 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 KiB

File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -27,8 +27,8 @@ about.claim.statement=テキスト全体のリンクをクリックします。
about.community=コミュニティ
about.community.discord=Discord
about.community.discord.statement=チャットに参加しよう!
about.community.kaiheila=KaiHeiLa
about.community.kaiheila.statement=チャットに参加しよう!
about.community.kookapp=KOOK
about.community.kookapp.statement=チャットに参加しよう!
about.dependency=Dependencies
about.legal=法的承認
about.thanks_to=Thanks to
@@ -60,7 +60,7 @@ account.create.yggdrasil=Mojang Login
account.create.offline=Offline
account.create.authlibInjector=サードパーティーアカウントを追加
account.email=メールアドレス
account.failed=エラーコード:%d
account.failed=ログインに失敗しました
account.failed.character_deleted=キャラクターが削除されました。
account.failed.connect_authentication_server=認証サーバーに接続できません。インターネット接続を確認してください。
account.failed.connect_injector_server=認証サーバーに接続できません。ネットワークをチェックして、URLが正しいことを確認してください。
@@ -83,11 +83,14 @@ account.injector.server_name=サーバー名
account.login=ログイン
account.login.hint=パスワードは保存されません。
account.login.refresh=再ログイン
account.login.refresh.microsoft.hint=<b>アカウント認証が無効なため、Microsoft アカウントを再度追加する必要があります</b>\n「OK」ボタンをクリックして、新しく開いたブラウザウィンドウでログインプロセスを続行する必要があります。
account.login.refresh.microsoft.manual=<b>アカウント認証が無効なため、Microsoft アカウントを再度追加する必要があります</b>\n「OK」ボタンをクリックした後、新しく開いたブラウザウィンドウで認証を完了する必要があります。ブラウザウィンドウが表示されない場合は、ここをクリックしてURLをコピーし、ブラウザで手動で開くことができます。
account.logout=ログアウト
account.register=登録
account.manage=アカウントリスト
account.methods=ログインタイプ
account.methods.authlib_injector=authlib-インジェクター
account.methods.little_skin=Little Skin
account.methods.microsoft=Microsoft Account
account.methods.microsoft.birth=誕生日の設定を編集する方法...
account.methods.microsoft.deauthorize=アカウントのバインドを解除
@@ -96,9 +99,11 @@ account.methods.microsoft.error.add_family=まだ18歳ではないため、Minec
account.methods.microsoft.error.add_family_probably=すでに18歳であるかどうかにかかわらず、アカウント設定を確認してください。そうでない場合は、アカウントを家族に追加する必要があります。
account.methods.microsoft.error.country_unavailable=XBoxLiveはお住まいの国/地域ではご利用いただけません。
account.methods.microsoft.error.missing_xbox_account=MicrosoftアカウントがXboxアカウントに接続されていません。続行する前に作成してください。
account.methods.microsoft.error.no_character=アカウントにMinecraftJavaプロファイルがありません。 Microsoftアカウントは有効ですが、ゲームを所有していません。
account.methods.microsoft.error.no_character=アカウントにMinecraftJavaプロファイルがありません。\nゲームファイルが作成されていない可能性があります\n上記のリンクをクリックして作成してください
account.methods.microsoft.error.unknown=ログインに失敗しました。Microsoftはエラーコード %d で応答します。
account.methods.microsoft.logging_in=ログイン...
account.methods.forgot_password=パスワードをお忘れの方
account.methods.microsoft.makegameidsettings=プロファイルを作成
account.methods.microsoft.hint=「ログイン」ボタンをクリックして、新しく開いたブラウザウィンドウでログインプロセスを続行する必要があります。\nMicrosoftアカウントへのログインに使用されたトークンが誤って漏洩した場合は、下の[アカウントのバインドを解除]をクリックして、ログイン認証をキャンセルできます。
account.methods.microsoft.manual=「ログイン」ボタンをクリックした後、新しく開いたブラウザウィンドウで認証を完了する必要があります。ブラウザウィンドウが表示されない場合は、ここをクリックしてURLをコピーし、ブラウザで手動で開くことができます。\nMicrosoftアカウントへのログインに使用されたトークンが誤って漏洩した場合は、下の[アカウントのバインドを解除]をクリックして、ログイン認証をキャンセルできます。
account.methods.microsoft.profile=アカウントプロファイル..
@@ -443,6 +448,8 @@ install.installer.install_online.tooltip=Fabric、Forge、OptiFine、LiteLoader
install.installer.liteloader=LiteLoader
install.installer.not_installed=インストールされていません
install.installer.optifine=OptiFine
install.installer.quilt=Quilt
install.installer.quilt-api=QSL/QFAPI
install.installer.version=%s
install.modpack=modpackを導入
install.new_game=新規作成
@@ -470,7 +477,6 @@ launch.advice.not_enough_space=割り当てたメモリが多すぎます。物
launch.advice.require_newer_java_version=Minecraft %1$s にはJava %2$s 以降が必要です。今すぐダウンロードしますか?
launch.advice.too_large_memory_for_32bit=32ビットJavaランタイム環境が原因で、割り当てたメモリが多すぎるため、ゲームがクラッシュする可能性があります。 32ビットシステムの最大メモリ容量は1024MBです。打ち上げを続けましょうか。
launch.advice.vanilla_linux_java_8=Linux x86-64の場合、Minecraft1.12.2以下はJava8でのみ実行できます。\nJava9以降のバージョンでは、liblwjgl.soなどの32ビットネイティブライブラリをロードできません。
launch.advice.vanilla_x86=Minecraftは現在、x86およびx86-64以外のアーキテクチャの公式サポートを提供していません。\nプラットフォームの対応するネイティブライブラリをダウンロードして、その配置パスを指定してみてください。
launch.advice.vanilla_x86.translation=Minecraftは現在、x86およびx86-64以外のアーキテクチャの公式サポートを提供していません。\nJava for x86-64を使用して、トランスレータを介してminecraftを実行するか、プラットフォームの対応するネイティブライブラリをダウンロードして指定してくださいその配置パス。
launch.failed=起動できません
launch.failed.cannot_create_jvm=Java仮想マシンを作成できませんでした。 Java引数は問題を引き起こす可能性があります。 JVM引数なしで再起動してください。
@@ -567,7 +573,7 @@ modpack.files.scripts=MineTweaker構成
modpack.files.servers_dat=サーバーリスト
modpack.install=%s modpackをインストールします
modpack.installing=modpackのインストール
modpack.introduction=Curse、MultiMC、HMCLmodpackがサポートされています。
modpack.introduction= Curse, Modrinth, MultiMC, MCBBS Modpackがサポートされています。
modpack.invalid=無効なmodpackファイル。
modpack.mismatched_type=不適切なmodpackタイプ、現在のゲームは %s modpackですが、更新ファイルは %s modpackです。
modpack.name=Modpack名
@@ -582,8 +588,8 @@ modpack.task.install.error=このmodpackファイルは認識できません。
modpack.task.install.will=modpackをインストールします:
modpack.type.curse=Curse
modpack.type.curse.completion=Cursemodpackに関連するファイルをインストールします
modpack.type.curse.tolerable_error=このCursemodpackのすべてのファイルのダウンロードを完了できません。対応するゲームバージョンを開始するときに、ダウンロードを再試行できます。ネットワークの問題により、数回再試行する場合があります。
modpack.type.curse.error=このCursemodpackをインストールできません。再試行してください。
modpack.type.curse.tolerable_error=このmodpackのすべてのファイルのダウンロードを完了できません。対応するゲームバージョンを開始するときに、ダウンロードを再試行できます。ネットワークの問題により、数回再試行する場合があります。
modpack.type.curse.error=このmodpackをインストールできません。再試行してください。
modpack.type.curse.not_found=必要なリソースの一部が欠落しているため、ダウンロードできませんでした。最新バージョンまたは他のmodpackを検討してください。
modpack.type.manual.warning=このmodpackをインポートする代わりに、おそらくこのmodpackファイルを直接解凍する必要があります。そして、バンドルされたランチャーを使用してゲームを起動します。このmodpackは、ランチャーによってエクスポートされるのではなく、.minecraftディレクトリを圧縮することによって手動で作成されます。 HMCLはこのmodpackのインポートを試みることができます、続行しますか?
modpack.type.mcbbs=MCBBS標準
@@ -593,7 +599,7 @@ modpack.type.multimc.export=Hello Minecraftでインポートできます!ラ
modpack.type.server=サーバー自動更新Modpack
modpack.type.server.export=サーバーマネージャーがゲームクライアントをリモートで更新できるようにする
modpack.type.server.malformed=不正なサーバーのmodpackマニフェスト
modpack.unsupported=サポートされていないmodpack、HMCL、MultiMC、およびCursemodpackのみがサポートされています。
modpack.unsupported=サポートされていないmodpack、Curse, Modrinth, MultiMC, MCBBSおよびMultiMCのみがサポートされています。
modpack.update=ゲームアップデート
modpack.wizard=modpackウィザードのエクスポート
modpack.wizard.step.1=基本オプション
@@ -663,7 +669,6 @@ multiplayer.exit.after_ready=マルチプレイヤーセッションが壊れて
multiplayer.exit.before_ready=マルチプレイヤーセッションの作成に失敗しました。 cato exitcode %d
multiplayer.exit.timeout=マルチプレイヤーサーバーへの接続に失敗しました。
multiplayer.exit.timeout.dynamic_token=マルチプレイヤーサーバーへの接続に失敗しました。
multiplayer.hint=マルチプレイヤー機能は実験的なものです。フィードバックをお願いします。
multiplayer.nat=ネットワークタイプの検出
multiplayer.nat.failed=ネットワークタイプの検出に失敗しました。
multiplayer.nat.hint=ネットワークタイプの検出により、ネットワークがマルチプレイヤーモードの要件を満たしているかどうかが明確になります。
@@ -680,7 +685,7 @@ multiplayer.nat.type.restricted_cone=Medium(制限付きコーン)
multiplayer.nat.type.symmetric=Bad(対称)
multiplayer.nat.type.symmetric_udp_firewall=Bad(UDPファイアウォールと対称)
multiplayer.nat.type.unknown=不明`
multiplayer.powered_by=マルチプレイヤーサービスは<a href="https://mcer.cn">mcer.cn</a>によって提供されます。 <a href="https://hmcl.huangyuhui.net/api/redirect/multiplayer-agreement">EULA</a>
multiplayer.powered_by=マルチプレイヤーサービスは<a href="https://mcer.cn">mcer.cn</a>によって提供されます。 <a href\="https://docs.hmcl.net/multiplayer/#%E4%BD%BF%E7%94%A8%E6%8E%88%E6%9D%83">Licence/a>
multiplayer.report=レポート
multiplayer.relay=リレーモード
multiplayer.relay.hint=静的トークンを持ち、テストされたNATタイプが不良対称であるユーザーの場合
@@ -817,7 +822,9 @@ settings.advanced.java_permanent_generation_space=PermGen Space / MB
settings.advanced.java_permanent_generation_space.prompt=Java 8以降のメタスペース、MB
settings.advanced.jvm=Java仮想マシンの設定
settings.advanced.jvm_args=JavaVM引数
settings.advanced.jvm_args.prompt=ここに入力して、デフォルト設定を上書きします
settings.advanced.jvm_args.prompt=- 入力パラメータがデフォルトパラメータと同じである場合、追加されません\n\
- GCパラメータを入力すると、デフォルトパラメータのG1パラメータが無効になります\n\
- 追加時にデフォルトの引数を追加しない場合は、下の[デフォルトのJVM引数を追加しない]をクリックしてください
settings.advanced.launcher_visibility.close=ゲームの起動時にランチャーを閉じます。
settings.advanced.launcher_visibility.hide=ゲームの起動時にランチャーを非表示にします。
settings.advanced.launcher_visibility.hide_and_reopen=ランチャーを非表示にし、ゲームが終了したら再度開きます。
@@ -937,13 +944,13 @@ update.changelog=変更
update.channel.dev=ベータ
update.channel.dev.hint=ベータ版を使用しています。ベータ版には、リリースバージョンと比較していくつかの追加機能が含まれている可能性があり、テストにのみ使用されます。\n \
ベータ版は不安定なはずです!\n \
問題が発生した場合は、<a href="hmcl://settings/feedback">フィードバックページ</a>にアクセスして報告するか、チャット<a href="https://discord.gg/jVvC7HfM6U">Discord</a>または<a href="https://kaihei.co/Kx7n3t">KaiHeiLa</a>で問題を報告します。\n \n \
問題が発生した場合は、<a href="hmcl://settings/feedback">フィードバックページ</a>にアクセスして報告するか、チャット<a href="https://discord.gg/jVvC7HfM6U">Discord</a>または<a href="https://kook.top/Kx7n3t">KOOK</a>で問題を報告します。\n \n \
このヒントを非表示にするには、<a href="https://hmcl.huangyuhui.net/api/redirect/sponsor">寄付</a>するか、フィードバックに貢献をする必要があります。
update.channel.dev.title=ベータ版のヒント
update.channel.nightly=アルファ
update.channel.nightly.hint=アルファ版を使用しています。これには、ベータ版およびリリース版と比較していくつかの追加機能が含まれている可能性があり、テストにのみ使用されます。\n \
アルファ版は不安定です!\n \
問題が発生した場合は、<a href="hmcl://settings/feedback">フィードバックページ</a>にアクセスして報告するか、チャット<a href="https://discord.gg/jVvC7HfM6U">Discord</a>または<a href="https://kaihei.co/Kx7n3t">KaiHeiLa</a>で問題を報告します。\n \n \
問題が発生した場合は、<a href="hmcl://settings/feedback">フィードバックページ</a>にアクセスして報告するか、チャット<a href="https://discord.gg/jVvC7HfM6U">Discord</a>または<a href="https://kook.top/Kx7n3t">KOOK</a>で問題を報告します。\n \n \
このヒントを非表示にするには、<a href="https://hmcl.huangyuhui.net/api/redirect/sponsor">寄付</a>するか、フィードバックに印象的な貢献をする必要があります。
update.channel.nightly.title=アルファ版のヒント
update.channel.stable=リリース
@@ -27,8 +27,8 @@ about.claim.statement=Кликните на ссылку, чтобы увиде
about.community=Сообщество
about.community.discord=Discord
about.community.discord.statement=Присоединиться!
about.community.kaiheila=KaiHeiLa
about.community.kaiheila.statement=Присоединиться!
about.community.kookapp=KOOK
about.community.kookapp.statement=Присоединиться!
about.dependency=Зависимости
about.legal=Юридическое подтверждение
about.thanks_to=Отдельная благодарность
@@ -60,7 +60,7 @@ account.create.yggdrasil=Добавление аккаунта Mojang
account.create.offline=Добавление офлайн аккаунта
account.create.authlibInjector=Добавление аккаунта authlib-injector
account.email=Электронная почта
account.failed=Код ошибки: %d
account.failed=Авторизация не удалась
account.failed.character_deleted=Персонаж был удалён.
account.failed.connect_authentication_server=Невозможно подключиться к серверу авторизации. Проверьте сетевое подключение.
account.failed.connect_injector_server=Невозможно подключиться к серверу авторизации. Проверьте сетевое подключение и убедитесь, что ссылка указана правильно.
@@ -83,11 +83,14 @@ account.injector.server_name=Имя сервера
account.login=Войти
account.login.hint=Мы не храним ваш пароль.
account.login.refresh=Повторный вход
account.login.refresh.microsoft.hint=<b>Поскольку авторизация учетной записи недействительна, вам необходимо повторно добавить свою учетную запись Microsoft</b>\nВам необходимо нажать кнопку «OK» и продолжить процесс авторизации во вновь открывшемся окне браузера.
account.login.refresh.microsoft.manual=<b>Поскольку авторизация учетной записи недействительна, вам необходимо повторно добавить свою учетную запись Microsoft</b>\nПосле нажатия кнопки «OK», вы должны завершить авторизацию во вновь открывшемся окне браузера. Если окно браузера не открылось, вы можете щёлкнуть здесь, чтобы скопировать ссылку и вручную открыть её в браузере.
account.logout=Выйти
account.register=Регистрация
account.manage=Список аккаунтов
account.methods=Метод авторизации
account.methods.authlib_injector=authlib-injector
account.methods.little_skin=Little Skin
account.methods.microsoft=Аккаунт Microsoft
account.methods.microsoft.birth=Как изменить настройки дня рождения...
account.methods.microsoft.deauthorize=Отменить авторизацию аккаунта
@@ -96,12 +99,14 @@ account.methods.microsoft.error.add_family=Поскольку тебе ещё н
account.methods.microsoft.error.add_family_probably=Проверьте в настройках своего аккаунта, исполнилось ли вам уже 18 лет или нет. Если нет, необходимо добавить семейный аккаунт.
account.methods.microsoft.error.country_unavailable=Xbox Live недоступен в вашей стране/регионе.
account.methods.microsoft.error.missing_xbox_account=Ваш аккаунт Microsoft не подключена к Xbox. Создайте его, прежде чем продолжить.
account.methods.microsoft.error.no_character=На аккаунте отсутствует профиль Minecraft Java. Хотя аккаунт Microsoft действителен, на ней не приобретено игры.
account.methods.microsoft.error.no_character=На аккаунте отсутствует профиль Minecraft Java. \nФайл игры не может быть создан, пожалуйста,\nнажмите на ссылку выше, чтобы создать его
account.methods.microsoft.error.unknown=Не удалось войти. Microsoft отвечает с кодом ошибки %d.
account.methods.microsoft.logging_in=Авторизация...
account.methods.microsoft.makegameidsettings=Создать архив
account.methods.microsoft.hint=Вам необходимо нажать кнопку «Войти» и продолжить процесс авторизации во вновь открывшемся окне браузера.\nЕсли токен, используемый для входа в аккаунт Microsoft случайно утёк, вы можете нажать «Отменить авторизацию аккаунта» ниже, чтобы отменить авторизацию.
account.methods.microsoft.manual=После нажатия кнопки «Войти», вы должны завершить авторизацию во вновь открывшемся окне браузера. Если окно браузера не открылось, вы можете щёлкнуть здесь, чтобы скопировать ссылку и вручную открыть её в браузере.\nЕсли токен, используемый для входа в аккаунт Microsoft случайно утёк, вы можете нажать «Отменить авторизацию аккаунта» ниже, чтобы отменить авторизацию.
account.methods.microsoft.profile=Профиль аккаунта...
account.methods.forgot_password=ЗАБЫЛ ПАРОЛЬ
account.methods.microsoft.snapshot=Лаунчер версии снапшот не поддерживает авторизацию через систему Microsoft.
account.methods.microsoft.waiting_browser=Ожидание авторизации в открытом окне браузера...
account.methods.offline=Офлайн
@@ -445,6 +450,8 @@ install.installer.install_online.tooltip=Поддержка установки F
install.installer.liteloader=LiteLoader
install.installer.not_installed=Не установлен
install.installer.optifine=OptiFine
install.installer.quilt=Quilt
install.installer.quilt-api=QSL/QFAPI
install.installer.version=%s
install.modpack=Установить модпак
install.new_game=Установить новую игру
@@ -474,7 +481,6 @@ launch.advice.require_newer_java_version=Minecraft %1$s требует Java %2$s
launch.advice.too_large_memory_for_32bit=Вы выделили слишком много памяти, из-за 32-разрядной Java Runtime Environment ваша игра может рухнуть. Максимальный объем памяти для 32-разрядных систем составляет 1024 МБ. Продолжить запуск?
launch.advice.vanilla_linux_java_8=На Linux x86-64, Minecraft 1.12.2 и ниже может работать только на Java 8.\nВерсии Java 9 и выше не могут загружать 32-битные нативные библиотеки, такие как liblwjgl.so.
launch.advice.modlauncher8=Используемая вами версия Forge несовместима с текущей версией Java. Попробуйте обновить Forge или начните с Java 8u312/11.0.13/17.0.1 или более ранней версии. Продолжить запуск?
launch.advice.vanilla_x86=В настоящее время Minecraft не обеспечивает официальную поддержку архитектур, отличных от x86 и x86-64.\nВы можете попробовать скачать соответствующую нативную библиотеку платформы и указать её путь размещения.
launch.advice.vanilla_x86.translation=В настоящее время Minecraft не обеспечивает официальную поддержку архитектур, отличных от x86 и x86-64.\nПожалуйста, используйте Java для x86-64 для запуска minecraft через переводчик, или загрузите соответствующую нативную библиотеку платформы и укажите её путь размещения.
launch.failed=Невозможно запустить
launch.failed.cannot_create_jvm=Не удалось создать виртуальную машину Java. Аргументы Java могут вызвать проблемы. Перезапустите без аргументов JVM.
@@ -571,7 +577,7 @@ modpack.files.scripts=Конфигурация MineTweaker
modpack.files.servers_dat=Список серверов
modpack.install=Установить модпак %s
modpack.installing=Установка модпака
modpack.introduction=Поддерживаются модпаки Curse, MultiMC, HMCL.
modpack.introduction=Поддерживаются модпаки Curse, Modrinth, MultiMC, MCBBS.
modpack.invalid=Неверный файл модпака.
modpack.mismatched_type=Неправильный тип модпака, ваша текущая игра - это модпак %s, но ваш файл обновления - это модпак %s.
modpack.name=Название модпака
@@ -586,8 +592,8 @@ modpack.task.install.error=Этот файл модпака не может бы
modpack.task.install.will=Установить модпак:
modpack.type.curse=Curse
modpack.type.curse.completion=Установите файлы, связанные с модпаком Curse
modpack.type.curse.tolerable_error=Мы не можем завершить скачивание всех файлов этого модпака Curse. Вы можете повторить скачивание при запуске соответствующей версии игры. Вы можете повторить попытку несколько раз из-за проблем с сетью.
modpack.type.curse.error=Невозможно установить этот модпак Curse. Повторите ещё раз.
modpack.type.curse.tolerable_error=Мы не можем завершить скачивание всех файлов этого модпака. Вы можете повторить скачивание при запуске соответствующей версии игры. Вы можете повторить попытку несколько раз из-за проблем с сетью.
modpack.type.curse.error=Невозможно установить этот модпак. Повторите ещё раз.
modpack.type.curse.not_found=Некоторые из необходимых ресурсов отсутствуют и поэтому не могут быть загружены. Скачайте последнюю версию или другие модпаки.
modpack.type.manual.warning=Возможно, вам нужно напрямую распаковать файл этого модпака, а не импортировать его. И запустите игру с помощью прилагаемого лаунчера. Этот модпак создаётся вручную путем сжатия директории .minecraft, а не экспортируется лаунчером. HMCL может попытаться импортировать этот модпак, продолжать?
modpack.type.mcbbs=Стандарт MCBBS
@@ -597,7 +603,7 @@ modpack.type.multimc.export=Может быть импортирован Hello M
modpack.type.server=Сервер автообновления модпака
modpack.type.server.export=Разрешить менеджеру сервера удаленно обновлять клиент игры
modpack.type.server.malformed=Некорректный манифест модпака сервера
modpack.unsupported=Неподдерживаемый модпак, поддерживаются только модпаки HMCL, MultiMC и Curse.
modpack.unsupported=Неподдерживаемый модпак, поддерживаются только модпаки Curse, Modrinth, MultiMC, MCBBS.
modpack.update=Обновить игру
modpack.wizard=Мастер экспорта модпака
modpack.wizard.step.1=Основные параметры
@@ -667,23 +673,7 @@ multiplayer.exit.after_ready=Сессия сетевой игры сломана
multiplayer.exit.before_ready=Не удалось создать сессию сетевой игры. Код выхода като %d
multiplayer.exit.timeout.static_token=Не удалось подключиться к серверу сетевой игры. Переключитесь на динамический токен и попробуйте снова.
multiplayer.exit.timeout.dynamic_token=Не удалось подключиться к серверу сетевой игры.
multiplayer.hint=Функция сетевой игры экспериментальная. Оставьте свой отзыв.
multiplayer.nat=Обнаружение типа сети
multiplayer.nat.hint=Определение типа сети позволит понять, соответствует ли ваша сеть нашим требованиям для сетевой игры.
multiplayer.nat.latency=Задержка
multiplayer.nat.not_yet_tested=Ещё не протестировано
multiplayer.nat.packet_loss_ratio=Коэффициент потери пакетов
multiplayer.nat.testing=Тестирование
multiplayer.nat.type=Тип NAT
multiplayer.nat.type.blocked_udp=Очень плохой (заблокированный UDP)
multiplayer.nat.type.full_cone=Хороший (полный конус)
multiplayer.nat.type.open_access=Хороший (открытый доступ)
multiplayer.nat.type.port_restricted_cone=Средний (конус с ограничением порта)
multiplayer.nat.type.restricted_cone=Средний (ограниченный конус)
multiplayer.nat.type.symmetric=Плохой (симметричный)
multiplayer.nat.type.symmetric_udp_firewall=Плохо (симметричный с брандмауэром UDP)
multiplayer.nat.type.unknown=Неизвестно
multiplayer.powered_by=Сетевая игра предоставлена <a href="https://mcer.cn">mcer.cn</a>. <a href="https://hmcl.huangyuhui.net/api/redirect/multiplayer-agreement">EULA</a>
multiplayer.powered_by=Сетевая игра предоставлена <a href="https://mcer.cn">mcer.cn</a>. <a href\="https://docs.hmcl.net/multiplayer/#%E4%BD%BF%E7%94%A8%E6%8E%88%E6%9D%83">Licence</a>
multiplayer.report=Отчёт
multiplayer.relay=Режим реле
multiplayer.relay.hint=Для пользователей, у которых есть статический токен, и чей проверенный тип NAT - плохо-семитричный
@@ -821,7 +811,9 @@ settings.advanced.java_permanent_generation_space=PermGen места/МБ
settings.advanced.java_permanent_generation_space.prompt=Метапространство на Java 8 и выше, МБ
settings.advanced.jvm=Параметры Java VM
settings.advanced.jvm_args=Аргументы Java VM
settings.advanced.jvm_args.prompt=Заполните здесь, чтобы переопределить настройки по умолчанию
settings.advanced.jvm_args.prompt=- Если входной параметр совпадает с параметром по умолчанию, он не будет добавлен\n\
- Введите любые параметры GC, параметр G1 параметра по умолчанию будет отключен\n\
- Нажмите «Отсутствие аргументов JVM по умолчанию» ниже, чтобы не добавлять аргументы по умолчанию при добавлении.
settings.advanced.launcher_visibility.close=Закрывать лаунчер при запуске игры
settings.advanced.launcher_visibility.hide=Сворачивать лаунчер при запуске игры
settings.advanced.launcher_visibility.hide_and_reopen=Сворачивать лаунчер при запуске игры и вновь открывать после закрытия игры
@@ -942,13 +934,13 @@ update.changelog=Изменения
update.channel.dev=Бета
update.channel.dev.hint=Вы используете бета-версию, которая может включать некоторые дополнительные функции по сравнению с релизной версией, используемой только для тестирования.\n\
Бета-версия может быть нестабильной!\n\
Если вы встретили какие-то проблемы, вы можете зайти на <a href="hmcl://settings/feedback">страницу обратной связи</a>, чтобы сообщить о них, или присоединиться к чату <a href="https://discord.gg/jVvC7HfM6U">Discord</a> или <a href="https://kaihei.co/Kx7n3t">KaiHeiLa</a>, чтобы сообщить о проблемах.\n\n\
Если вы встретили какие-то проблемы, вы можете зайти на <a href="hmcl://settings/feedback">страницу обратной связи</a>, чтобы сообщить о них, или присоединиться к чату <a href="https://discord.gg/jVvC7HfM6U">Discord</a> или <a href="https://kook.top/Kx7n3t">KOOK</a>, чтобы сообщить о проблемах.\n\n\
Чтобы скрыть эту подсказку, нужно <a href="https://hmcl.huangyuhui.net/api/redirect/sponsor">пожертвовать</a> или сделать внушительный вклад через обратную связь.
update.channel.dev.title=Подсказки для бета-версии
update.channel.nightly=Альфа
update.channel.nightly.hint=Вы используете альфа-версию, которая может включать некоторые дополнительные функциональные возможности по сравнению с бета-версией и версией релиза, используемой только для тестирования.\n\
Альфа-версия может быть нестабильной!\n\
Если вы встретили какие-то проблемы, вы можете зайти на <a href="hmcl://settings/feedback">страницу обратной связи</a>, чтобы сообщить о них, или присоединиться к чату <a href="https://discord.gg/jVvC7HfM6U">Discord</a> или <a href="https://kaihei.co/Kx7n3t">KaiHeiLa</a>, чтобы сообщить о проблемах.\n\n\
Если вы встретили какие-то проблемы, вы можете зайти на <a href="hmcl://settings/feedback">страницу обратной связи</a>, чтобы сообщить о них, или присоединиться к чату <a href="https://discord.gg/jVvC7HfM6U">Discord</a> или <a href="https://kook.top/Kx7n3t">KOOK</a>, чтобы сообщить о проблемах.\n\n\
Чтобы скрыть эту подсказку, нужно <a href="https://hmcl.huangyuhui.net/api/redirect/sponsor">пожертвовать</a> или сделать внушительный вклад через обратную связь.
update.channel.nightly.title=Подсказки для альфа-версии
update.channel.stable=Релиз
@@ -27,18 +27,18 @@ about.claim.statement=點擊連結以查看全文
about.community=社區
about.community.discord=Discord
about.community.discord.statement=歡迎加入 Discord 討論區,加入後請遵守討論區規定
about.community.kaiheila=開黑啦
about.community.kaiheila.statement=歡迎加入開黑啦討論區,加入後請遵守討論區規定
about.community.kookapp=KOOK
about.community.kookapp.statement=歡迎加入 KOOK 討論區,加入後請遵守討論區規定
about.dependency=相依元件
about.legal=法律聲明
about.thanks_to=鳴謝
about.thanks_to.bangbang93.statement=提供 BMCLAPI 下載源,請贊助支持 BMCLAPI!
about.thanks_to.bangbang93.statement=提供 BMCLAPI 下載地點,請贊助支持 BMCLAPI!
about.thanks_to.contributors=所有通過 Issues、Pull Requests 等管道參與本項目的貢獻者
about.thanks_to.contributors.statement=沒有開源社區的支持,Hello Minecraft! Launcher 無法走到今天
about.thanks_to.gamerteam.statement=提供預設背景圖
about.thanks_to.glavo.statement=為 HMCL 貢獻許多技術支持
about.thanks_to.mcbbs=MCBBS 我的世界中文論壇
about.thanks_to.mcbbs.statement=提供 MCBBS 下載源
about.thanks_to.mcbbs.statement=提供 MCBBS 下載地點
about.thanks_to.mcmod=MC 百科
about.thanks_to.mcmod.statement=提供 Mod 中文名映射表與 Mod 百科
about.thanks_to.noin=阿貓 (mcer.cn)
@@ -60,7 +60,7 @@ account.create.yggdrasil=添加 Mojang 帳戶
account.create.offline=添加離線模式帳戶
account.create.authlibInjector=添加外置登入帳戶 (authlib-injector)
account.email=電子信箱
account.failed=錯誤碼: %d
account.failed=帳戶刷新失敗!
account.failed.character_deleted=已刪除此角色
account.failed.connect_authentication_server=無法連線至認證伺服器,可能是網路問題,請檢查設備能否正常上網或使用代理服務
account.failed.connect_injector_server=無法連線至認證伺服器,可能是網路故障,請檢查設備能否正常上網、檢查網址是否輸入錯誤或使用代理服務
@@ -70,24 +70,31 @@ account.failed.invalid_password=密碼無效
account.failed.invalid_token=請嘗試登出並重新輸入密碼登入
account.failed.migration=你的帳號需要被遷移至微軟帳號。如果你已經遷移,你需要使用微軟登錄方式登錄遷移後的微軟帳號。
account.failed.no_character=該帳戶沒有角色
account.failed.server_disconnected=無法訪問登入服務器,帳戶信息刷新失敗!\n你可以選擇跳過帳戶刷新(但啓動遊戲後可能會因為帳戶信息過期而導致無法進入開啟正版驗證的服務器)\n或嘗試再次刷新帳戶?
account.failed.server_response_malformed=無法解析認證伺服器回應,可能是伺服器故障
account.failed.wrong_account=登錄了錯誤的帳號
account.hmcl.hint=你需要點擊“登入”按鈕,並在打開的網頁中完成登入
account.injector.add=新增認證伺服器
account.injector.empty=無 (按一下右側 + 加入)
account.injector.http=警告: 此伺服器使用不安全的 HTTP 協定,您的密碼在登入時會被明文傳輸。
account.injector.link.homepage=首頁
account.injector.link.register=註冊
account.injector.server=認證伺服器
account.injector.server_url=伺服器位址
account.injector.server_name=伺服器名稱
account.login=登入
account.login.hint=我們不會保存你的密碼
account.login.skip=重新刷新帳戶
account.login.retry=再次刷新帳戶
account.login.refresh=重新登錄
account.login.refresh.microsoft.hint=<b>因為賬戶授權失效,需要重新添加你的微軟賬戶</b>\n你需要按照以下步驟添加:\n \n1.點擊“確定”按鈕\n2.在網頁瀏覽器顯示的網站中輸入 HMCL 顯示的代碼(自動拷貝,直接粘貼即可),並點擊“下一步”\n3.按照網站的提示登入\n4.當網站顯示“ 是否允許此應用訪問你的信息?”的標識時,請點擊“是”\n5.當網站提示“大功告成”的標示時,及表示登入成功!然後等待賬戶完成添加即可!\n \n-若網站提示“出现错误”的標識,請嘗試重新按照以上步驟登入\n-若賬戶添加失敗,請嘗試重新按照以上步驟登入\n<b>-若設備網絡環境不佳,可能登陸網站加載很慢甚至無法加載,此時請使用 VPN 或代理伺服器並重試</b>
account.login.refresh.microsoft.manual=<b>因為賬戶授權失效,需要重新添加你的微軟賬戶</b>\n你需要按照以下步驟添加:\n \n1.點擊“確定”按鈕\n2.在網頁瀏覽器顯示的網站中輸入該代碼:<b>%1$s</b>(已自動拷貝,請點此再次拷貝),並點擊“下一步”\n3.按照網站的提示登入\n4.當網站顯示“ 是否允許此應用訪問你的信息?”的標識時,請點擊“是”\n5.當網站提示“大功告成”的標示時,及表示登入成功!然後等待賬戶完成添加即可!\n \n-若網站提示“出现错误”的標識,請嘗試重新按照以上步驟登入\n-若賬戶添加失敗,請嘗試重新按照以上步驟登入\n-若網站未能打開,請手動在網頁瀏覽器中打開:%2$s\n<b>-若設備網絡環境不佳,可能登陸網站加載很慢甚至無法加載,此時請使用 VPN 或代理伺服器並重試</b>
account.logout=登出
account.register=註冊
account.manage=帳戶列表
account.methods=登入方式
account.methods.authlib_injector=authlib-injector 登入
account.methods.little_skin=Little Skin
account.methods.microsoft=微軟帳戶
account.methods.microsoft.birth=如何修改帳戶出生日期
account.methods.microsoft.deauthorize=解除帳戶授權
@@ -96,13 +103,15 @@ account.methods.microsoft.error.add_family=由於你未滿 18 歲,你的帳戶
account.methods.microsoft.error.add_family_probably=請檢查你的帳戶設置,如果你未滿 18 歲,你的帳戶必須被加入到家庭中才能登錄遊戲。你也可以點擊上方連結更改你的帳戶的出生日期,使年齡滿 18 歲以上以繼續登錄。
account.methods.microsoft.error.country_unavailable=你所在的國家或地區不受 XBox Live 的支援。
account.methods.microsoft.error.missing_xbox_account=你的微軟帳號尚未關聯 XBox 帳號,你必須先創建 XBox 帳號,才能登入遊戲。
account.methods.microsoft.error.no_character=該帳號沒有包含 Minecraft Java 版購買記錄,
account.methods.microsoft.error.no_character=該帳戶未包含 Minecraft Java 版購買記錄\n可能未創建遊戲檔案,請點擊上方鏈接創建
account.methods.microsoft.error.unknown=登入失敗,錯誤碼:%d
account.methods.microsoft.logging_in=登入中...
account.methods.microsoft.makegameidsettings=創建檔案
account.methods.microsoft.hint=你需要按照以下步驟添加:\n1.點擊“登入”按鈕\n2.在網頁瀏覽器顯示的網站中輸入 HMCL 顯示的代碼(自動拷貝,直接粘貼即可),並點擊“下一步”\n3.按照網站的提示登入\n4.當網站顯示“ 是否允許此應用訪問你的信息?”的標識時,請點擊“是”\n5.當網站提示“大功告成”的標示時,及表示登入成功!然後等待賬戶完成添加即可!\n-若網站提示“出现错误”的標識,請嘗試重新按照以上步驟登入\n-若賬戶添加失敗,請嘗試重新按照以上步驟登入\n<b>-若設備網絡環境不佳,可能登陸網站加載很慢甚至無法加載,此時請使用 VPN 或代理伺服器並重試</b>\n-若登入微軟賬號的 Token 洩露,可點擊下方“解除帳戶授權”解除登入授權,然後等待 Token 過期
account.methods.microsoft.manual=你需要按照以下步驟添加:\n1.點擊“登入”按鈕\n2.在網頁瀏覽器顯示的網站中輸入該代碼:<b>%1$s</b>(已自動拷貝,請點此再次拷貝),並點擊“下一步”\n3.按照網站的提示登入\n4.當網站顯示“ 是否允許此應用訪問你的信息?”的標識時,請點擊“是”\n5.當網站提示“大功告成”的標示時,及表示登入成功!然後等待賬戶完成添加即可\n-若網站提示“出现错误”的標識,請嘗試重新按照以上步驟登入\n-若賬戶添加失敗,請嘗試重新按照以上步驟登入\n-若網站未能打開,請手動在網頁瀏覽器中打開:%2$s\n<b>-若設備網絡環境不佳,可能登陸網站加載很慢甚至無法加載,此時請使用 VPN 或代理伺服器並重試</b>\n-若登入微軟賬號的 Token 洩露,可點擊下方“解除帳戶授權”解除登入授權,然後等待 Token 過期
account.methods.microsoft.profile=帳戶設置頁
account.methods.microsoft.snapshot=HMCL 快照版不支持微软登录
account.methods.forgot_password=忘記密碼
account.methods.microsoft.snapshot=HMCL 快照版暫不提供微軟登入支持,請使用穩定版或測試版進行登入。
account.methods.microsoft.waiting_browser=等待在新打開的瀏覽器窗口中完成登入...
account.methods.offline=離線模式
account.methods.offline.uuid=UUID
@@ -146,6 +155,7 @@ assets.index.malformed=資源檔案的索引檔案損壞,您可以在遊戲 [
button.cancel=取消
button.change_source=切換下載源
button.clear=清除
button.copy_and_exit=複製並退出
button.delete=刪除
button.edit=編輯
button.install=安裝
@@ -155,6 +165,7 @@ button.ok=確定
button.refresh=重新整理
button.remove=刪除
button.remove.confirm=您確認要刪除嗎?該操作無法撤銷!
button.retry=重試
button.save=儲存
button.save_as=另存為
button.select_all=全選
@@ -184,7 +195,7 @@ curse.category.4479=高難度
curse.category.4482=大型模組包
curse.category.4472=科技
curse.category.4473=魔法
curse.category.5128=香草+
curse.category.5128=原版增強
# https://addons-ecs.forgesvc.net/api/v2/category/section/6
curse.category.5299=教育
@@ -298,13 +309,14 @@ download.provider.mojang=官方伺服器 (OptiFine 自動安裝的下載來源
download.provider.official=儘量使用官方源(最新,但可能加載慢)
download.provider.balanced=選擇加載速度快的下載源(平衡,但可能不是最新)
download.provider.mirror=儘量使用鏡像源(加載快,但可能不是最新)
download.java=下載 Java
download.javafx=正在下載必要的運行時組件
download.javafx.notes=正在通過網絡下載 HMCL 必要的運行時組件。\n點擊“切換下載源”按鈕查看詳情以及選擇下載源,點擊“取消”按鈕停止並退出。\n注意:如果下載速度過慢,請嘗試切换下載源。
download.javafx.component=正在下載模塊 %s
download.javafx.prepare=準備開始下載
exception.access_denied=因為無法訪問文件 %s,HMCL 沒有對該文件的訪問權限,或者該文件被其他程序打開。\n\
請你檢查當前操作系統帳戶是否能訪問該文件,比如非管理員用戶可能不能訪問其他帳戶的個人文件夾內的文件。\n\
exception.access_denied=因為無法存取檔案 %s,HMCL 沒有對該文件的訪問權限,或者該文件被其他程序打開。\n\
請你檢查當前操作系統帳戶是否能訪存取檔案,比如非管理員用戶可能不能訪問其他帳戶的個人資料夾內的文件。\n\
對於 Windows 用戶,你還可以嘗試通過資源監視器查看是否有程序占用了該文件,如果是,你可以關閉占用此文件相關程序,或者重啟電腦再試。
exception.artifact_malformed=下載的文件正確,無法通過校驗。
exception.ssl_handshake=無法建立 SSL 連接,因為當前 Java 虛擬機缺少相關的 SSL 證書。你可以嘗試使用其他的 Java 虛擬機啟動 HMCL 再試。
@@ -316,13 +328,19 @@ extension.ps1=PowerShell 指令碼
extension.sh=Bash 指令碼
fatal.javafx.incompatible=缺少 JavaFX 運行環境。\nHMCL 無法在低於 Java 11 且缺少 JavaFX 的 Java 環境上自行補全 JavaFX 運行環境。\n請更換如 Oracle Java 8 等包含 JavaFX 的 Java 運行環境,或者更新到 Java 11 或更高版本。
fatal.javafx.incompatible.loongson=缺少 JavaFX 運行環境。\n請使龍芯 JDK 8 (http://www.loongnix.cn/zh/api/java/downloads-jdk8/index.html) 啟動 HMCL。
fatal.javafx.missing=找不到 JavaFX。\n如果您使用的是 Java 11 或更高版本,請降級到 Oracle JRE 8,或者安裝 BellSoft Liberica Full JRE。\n如果您使用的是其他 OpenJDK 构建,請確保其包含 OpenJFX。
fatal.missing_dst_root_ca_x3=目前的 Java 平台缺少 DST Root CA X3 憑證。\n您依然可以使用 Hello Minecraft! Launcher,但會無法連線到部分網站 (如使用 Lets Encrypt 憑證的站台),這可能會使 Hello Minecraft! Launcher 無法正常運作。\n請將您的 Java 升級到 8u101 以上來解決此問題。
fatal.config_change_owner_root=你正在使用 root 帳戶啟動 Hello Minecraft! Launcher,這可能導致你未來無法使用其他帳戶正常啟動 Hello Minecraft! Launcher。\n是否繼續啟動?
fatal.config_loading_failure=Hello Minecraft! Launcher 無法載入設定檔案。\n請確保 Hello Minecraft! Launcher 對 "%s" 目錄及該目錄下的檔案擁有讀寫權限。
fatal.config_loading_failure.unix=Hello Minecraft! Launcher 無法載入設定檔案,因為設定檔案是由用戶 %1$s 創建的。\n請使用 root 帳戶啟動 HMCL (不推薦),或在終端中執行以下命令將設定檔案的所有權變更為當前用戶: \n%2$s
fatal.migration_requires_manual_reboot=Hello Minecraft! Launcher 即將升級完成,請重新開啟 Hello Minecraft! Launcher。
fatal.apply_update_failure=我們很抱歉 Hello Minecraft! Launcher 無法自動完成升級程式,因為出現了一些問題。\n但你依然可以從 %s 處手動下載 Hello Minecraft! Launcher 來完成升級。\n請考慮向我們回報該問題。
fatal.samba=如果您正在通過 Samba 共亯的資料夾中運行 HMCL,HMCL 可能無法正常工作,請嘗試更新您的 Java 或在本地資料夾內運行 HMCL。
fatal.illegal_char=您的用戶資料夾路徑中存在非法字元‘=’。HMCL 能够運行,但一些功能無法正常使用。 \n您將無法使用外置登入帳戶以及離線登入更換皮膚功能,並且在進行多人遊戲時可能存在更大的安全隱患。
fatal.unsupported_platform=Minecraft 尚未你您的平臺提供完善支持,所以可能影響遊戲體驗或無法啟動遊戲。\n若無法啟動 Minecraft 1.17 及以上版本,可以嘗試在版本設定中打開“使用 OpenGL 軟渲染器”選項,使用 CPU 渲染以獲得更好的相容性。
fatal.unsupported_platform.osx_arm64=HMCL 已為 Apple Silicon 平臺提供支援,使用 ARM 原生 Java 啟動遊戲以獲得更流暢的遊戲體驗。\n如果你在遊戲中遭遇問題,使用 x86-64 架構的 Java 啟動遊戲可能有更好的相容性。
fatal.unsupported_platform.windows_arm64=HMCL 已為 Windows on Arm 平臺提供原生支持。如果你在遊戲中遭遇問題,請嘗試使用 x86 架構的 Java 啟動遊戲。\n\n如果你正在使用<b>高通</b>平臺,你可能需要安裝 <a href="ms-windows-store://pdp/?productid=9NQPSL29BFFF">OpenGL 相容包</a>後才能進行遊戲。點擊連結前往 Microsoft Store 安裝相容包。
feedback=回饋
feedback.add=新增回饋
@@ -361,7 +379,7 @@ folder.saves=遊戲存檔資料夾
folder.screenshots=截圖資料夾
game=遊戲
game.crash.feedback=查看了日誌發現問題很常見?在回饋頁面提交回饋豐富崩潰分析系統!
game.crash.feedback=查看了日誌發現問題很常見?在 <a href="https://discord.gg/jVvC7HfM6U">Discord</a> 或 <a href="https://kook.top/Kx7n3t">KOOK 群</a>提交回饋豐富崩潰分析系統!
game.crash.info=遊戲訊息
game.crash.reason=崩潰原因
game.crash.reason.analyzing=分析中...
@@ -376,10 +394,10 @@ game.crash.reason.fabric_warnings=Fabric 提供了一些警告訊息:\n%1$s
game.crash.reason.file_already_exists=當前遊戲因為文件 %1$s 已經存在,無法繼續運行。\n如果你認為這個文件可以刪除,你可以在備份這個文件後嘗試刪除它,並重新啟動遊戲。
game.crash.reason.file_changed=當前遊戲因為檔案校驗失敗,無法繼續運行。\n如果你手動修改了 Minecraft.jar 檔案,你需要回退修改,或者重新下載遊戲。
game.crash.reason.gl_operation_failure=當前遊戲因為你使用的某些 Mod、光影包、材質包,無法繼續運行。\n請先嘗試禁用你所使用的Mod/光影包/材質包再試。
game.crash.reason.graphics_driver=當前遊戲因為你的顯示卡驅動存在問題崩潰了。\n\
請嘗試升級你的顯示卡驅動到最新版本後再嘗試啟動遊戲。\n\
game.crash.reason.graphics_driver=當前遊戲因為你的顯示卡驅動存在問題崩潰了,請嘗試升級你的顯示卡驅動到最新版本後再嘗試啟動遊戲。\n\
如果你的電腦存在獨立顯示卡,你需要檢查遊戲是否使用集成/核芯顯示卡啟動。如果是,請嘗試使用獨立顯示卡啟動 HMCL 與遊戲。如果仍有問題,你可能需要考慮換一個新顯示卡或新電腦。\n\
如果你確實需要使用核芯顯示卡,請檢查你的電腦的 CPU 是否是 Intel(R) Core(TM) 3000 系列或更舊的處理器,如果是,對於 Minecraft 1.16.5 及更舊版本,請你將遊戲所使用的 Java 版本降級至 1.8.0_51 及以下版本,否則你必須更換獨立顯示卡或新電腦。\n\
如果你確實需要使用核芯顯示卡,請檢查你的電腦的 CPU 是否是 Intel(R) Core(TM) 3000 系列或更舊的處理器,如果是,對於 Minecraft 1.16.5 及更舊版本,請你將遊戲所使用的 Java 版本降級至 1.8.0_51 及以下版本,否則你需要更換獨立顯示卡或新電腦。\n\
在版本設定中打開“使用 OpenGL 軟渲染器”選項也可以解决此問題,但打開此選項後在 CPU 效能不足的情况下幀數會顯著降低,僅推薦以調試為目的或應急時開啟。\n\
詳情請點擊 <a href="https://hmcl.huangyuhui.net/help/game/graphics-card">此處</a> 查看
game.crash.reason.illegal_access_error=當前遊戲因為某些 Mod 的問題,無法繼續運行。\n如果你認識:%1$s,你可以更新或刪除對應 Mod 再試。
game.crash.reason.jdk_9=當前遊戲因為 Java 版本過高,無法繼續運行。\n你需要下載安裝 Java 8,並在遊戲設置中將 Java 設置為 1.8 的版本。
@@ -401,10 +419,11 @@ game.crash.reason.no_such_method_error=當前遊戲因為代碼不完整,無
game.crash.reason.opengl_not_supported=當前遊戲因為你的顯示卡驅動存在問題,無法繼續運行。\n原因是 OpenGL 不受支援,你現在是否在遠程桌面或者串流模式下?如果是,請直接使用原電腦啟動遊戲。\n或者嘗試升級你的顯示卡驅動到最新版本後再嘗試啟動遊戲。如果你的電腦存在獨立顯示卡,你需要檢查遊戲是否使用集成/核心顯示卡啟動,如果是,請嘗試使用獨立顯示卡啟動 HMCL 與遊戲。如果仍有問題,你可能需要考慮換一個新顯示卡或新電腦。
game.crash.reason.openj9=當前遊戲無法運行在 OpenJ9 虛擬機上,請你在遊戲設置中更換 Hotspot Java 虛擬機,並重新啟動遊戲。如果沒有下載安裝,你可以在網路上自行下載。
game.crash.reason.out_of_memory=當前遊戲因為記憶體不足,無法繼續運行。\n這可能是記憶體分配太小,或者 Mod 數量過多導致的。\n你可以在遊戲設置中調大遊戲記憶體分配值以允許遊戲在更大的記憶體下運行。\n如果仍然出現該錯誤,你可能需要換一台更好的電腦。
game.crash.reason.processing_of_javaagent_failed=當前遊戲因為加載 -javaagent 參數失敗,無法繼續運行。\n如果你在 Java 虛擬機參數 中添加了相關參數,請檢查是否正確。\n如果你沒有添加相關參數或參數確認正確, 請嘗試:\n打開 控制面板 -- 時鐘和區域 分類(選項為類別顯示才有此選項,沒有就跳過)-- 區域 -- 上方的 管理 選項卡 -- 下方的 更改系統區域設置 按鈕 -- 在彈出的視窗中將 “使用Unicode UTF-8提供全球語言支持” 選項關閉,重啓設備後再嘗試啟動遊戲。\n可在<a href="https://discord.gg/jVvC7HfM6U">Discord</a>或<a href="https://kook.top/Kx7n3t">KOOK群</a>尋求幫助
game.crash.reason.resolution_too_high=當前遊戲因為材質包解析度過高,無法繼續運行\n你可以更換一個解析度更低的材質,或者更換一個視訊記憶體更大的顯示卡。
game.crash.reason.stacktrace=原因未知,請點擊日誌按鈕查看詳細訊息。\n下面是一些關鍵字,其中可能包含 Mod 名稱,你可以透過搜索的方式查找有關訊息。\n%s
game.crash.reason.too_old_java=當前遊戲因為 Java 虛擬機版本過低,無法繼續運行。\n你需要在遊戲設置中更換 %1$s 或更新版本的 Java 虛擬機,並重新啟動遊戲。如果沒有下載安裝,你可以點擊 <a href="https://docs.microsoft.com/zh-TW/java/openjdk/download">此處</a> 下載微軟 JDK。
game.crash.reason.unknown=原因未知,請點擊日誌按鈕查看詳細訊息。\n<b>不要將本界面截圖給他人!</b>如果你要求助他人,請你點擊左下角導出遊戲崩潰訊息後將導出的文件發送給他人以供分析!\n你可以向我們提供遊戲崩潰日誌以提升 HMCL 的日誌分析能力。
game.crash.reason.unknown=原因未知,請點擊日誌按鈕查看詳細訊息。\n<b>不要將本界面截圖給他人!</b>如果你要求助他人,請你點擊左下角導出遊戲崩潰訊息後將導出的文件發送給他人以供分析!
game.crash.reason.unsatisfied_link_error=當前遊戲因為缺少本地庫,無法繼續運行。\n這些本地庫缺失:%1$s。\n如果你在遊戲設置中修改了本地庫路徑選項,請你修改回預設模式。\n如果已經在預設模式下,請檢查本地庫缺失是否是 Mod 引起的,或由 HMCL 引起的。如果你確定是 HMCL 引起的,建議你向我們回饋。\n如果你確實需要自訂本地庫路徑,你需要保證其中包含缺失的本地庫。
game.crash.title=遊戲意外退出
game.directory=遊戲路徑
@@ -449,6 +468,8 @@ install.installer.install_online.tooltip=支援安裝 Fabric、Forge、OptiFine
install.installer.liteloader=LiteLoader
install.installer.not_installed=不安裝
install.installer.optifine=OptiFine
install.installer.quilt=Quilt
install.installer.quilt-api=QSL/QFAPI
install.installer.version=%s
install.modpack=安裝模組包
install.new_game=安裝新遊戲版本
@@ -477,9 +498,8 @@ launch.advice.newer_java=偵測到您未使用 Java 8 及更新版本,Java 8
launch.advice.not_enough_space=您設定的記憶體大小過大,由於超過了系統記憶體大小 %dMB,所以可能影響遊戲體驗或無法啟動遊戲。是否繼續啟動?
launch.advice.require_newer_java_version=Minecraft %1$s 僅能運行在 Java %2$s 或更高版本上,但 HMCL 未能找到該 Java 版本,你可以點擊“是” ,HMCL 會自動下載他,是否下載?
launch.advice.too_large_memory_for_32bit=您設定的記憶體大小過大,由於可能超過了 32 位元 Java 的記憶體分配限制,所以可能無法啟動遊戲,請將記憶體調至低於 1024MB 的值。是否繼續啟動?
launch.advice.vanilla_linux_java_8=對於 Linux x86-64 平台,Minecraft 1.12.2 及以下版本僅支持 Java 8。\nJava 9+ 版本會無法載入 32 位的 liblwjgl.so。
launch.advice.vanilla_x86=Minecraft 官方尚未提供對非 x86-64 平臺的支持。\n您可以嘗試下載您所用平臺對應的本機庫,在遊戲設定的調試選項中指定其路徑後再嘗試運行。
launch.advice.vanilla_x86.translation=你的電腦中沒有安裝 X64 架構的 Java 虛擬機(JDK),你可以在 <a href="https://docs.microsoft.com/zh-tw/java/openjdk/download"> 這裡 </a> 下載 <b> X64 </b> 架構的 Java 虛擬機。\nMinecraft 尚未提供對 ARM 平台的支持,不能在您目前使用的 ARM64 架構 JDK 上運行。因此 HMCL 會借助 Rosetta 2 轉譯執行 X64 架構的 JDK 來啟動 Minecraft。
launch.advice.vanilla_linux_java_8=對於 Linux x86-64 平台,Minecraft 1.12.2 及以下版本僅支援 Java 8。\nJava 9+ 版本會無法載入 32 位的 liblwjgl.so。
launch.advice.vanilla_x86.translation=Minecraft 尚未為您的平臺提供完善支持,所以可能影響遊戲體驗或無法啟動遊戲。\n你可以在 <a href="https://docs.microsoft.com/java/openjdk/download"> 這裡 </a>下載<b> X86-64 </b> 架構的 Java 以獲得更完整的體驗。\n是否繼續啟動?
launch.failed=啟動失敗
launch.failed.cannot_create_jvm=偵測到無法建立 Java 虛擬機,可能是 Java 參數有問題。可以在設定中開啟無參數模式啟動。
launch.failed.creating_process=啟動失敗,在建立新處理程式時發生錯誤。可能是 Java 路徑錯誤。
@@ -491,7 +511,7 @@ launch.failed.execution_policy=設定執行策略
launch.failed.execution_policy.failed_to_set=設定執行策略失敗
launch.failed.execution_policy.hint=當前執行策略封锁您執行 PowerShell 腳本。\n點擊“確定”允許當前用戶執行本地 PowerShell 腳本,或點擊“取消”保持現狀。
launch.failed.exited_abnormally=遊戲非正常退出,請查看記錄檔案,或聯絡他人尋求幫助。
launch.failed.no_accepted_java=找不到適合當前遊戲使用的 Java。如果您認為實際存在合適的 Java,您可以在遊戲設置中手動設置 Java。
launch.failed.no_accepted_java=找不到適合當前遊戲使用的 Java,是否使用默認 Java 啟動遊戲?點擊“是”使用默認 Java 繼續啟動遊戲,\n或者請到遊戲設定中選擇一個合適的Java虛擬機器版本。
launch.state.dependencies=處理遊戲相依元件
launch.state.done=啟動完成
launch.state.java=檢測 Java 版本
@@ -576,7 +596,7 @@ modpack.files.scripts=MineTweaker 設定
modpack.files.servers_dat=多人遊戲伺服器列表
modpack.install=安裝 %s 模組包
modpack.installing=正在安裝模組包
modpack.introduction=支援 Curse、MultiMC、HMCL 模組包。
modpack.introduction=支援 Curse、Modrinth、MultiMC、MCBBS 模組包。
modpack.invalid=無效的模組包升級檔案,可能是下載時出現問題。
modpack.mismatched_type=模組包類型不符,目前遊戲是 %s 模組包,但是提供的模組包更新檔案是 %s 模組包。
modpack.name=模組包名稱
@@ -587,11 +607,11 @@ modpack.origin.mcbbs=MCBBS
modpack.origin.mcbbs.prompt=貼子 id
modpack.scan=解析模組包
modpack.task.install=匯入模組包
modpack.task.install.error=無法識別該模組包,目前僅支援匯入 Curse、Modrinth、MultiMC、HMCL 模組包。
modpack.task.install.error=無法識別該模組包,目前僅支援匯入 Curse、Modrinth、MultiMC、MCBBS 模組包。
modpack.task.install.will=將會安裝模組包:
modpack.type.curse=Curse
modpack.type.curse.tolerable_error=但未能完成 Curse 模組包檔案的下載,您可以在啟動該遊戲版本時繼續 Curse 模組包檔案的下載。由於網路問題,您可能需要重試多次。
modpack.type.curse.error=無法完成 Curse 模組包的下載,請多次重試或設定代理
modpack.type.curse.tolerable_error=但未能完成該模組包檔案的下載,您可以在啟動該遊戲版本時繼續該模組包檔案的下載。由於網路問題,您可能需要重試多次……
modpack.type.curse.error=無法完成該模組包所需的依賴下載,請多次重試或設定代理……
modpack.type.curse.not_found=部分必需檔案已經從網路中被刪除並且再也無法下載,請嘗試該模組包的最新版本或者安裝其他模組包。
modpack.type.manual.warning=您大概需要直接解压该模組包,并使用其自带的启动器即可开始游戏,而不需要导入模組包。该模組包不是由启动器导出的模組包,而是人工打包 .minecraft 资料夹而来的,这类模組包通常附带游戏启动器。HMCL 可以尝试导入该模組包,但不保证可用性,是否继续?
modpack.type.mcbbs=我的世界中文論壇模組包標準
@@ -602,7 +622,7 @@ modpack.type.multimc.export=可以被 Hello Minecraft! Launcher (HMCL) 和 Multi
modpack.type.server=伺服器自動更新模組包
modpack.type.server.export=允許伺服器管理員遠端更新遊戲用戶端
modpack.type.server.malformed=伺服器模組包配置格式錯誤,請聯絡伺服器管理員解決此問題
modpack.unsupported=不支援該模組包。僅 HMCL、MultiMC、Curse 模組包受支援。
modpack.unsupported=不支援該模組包。僅 Curse、Modrinth、MultiMC、MCBBS 模組包受支援。
modpack.update=正在升級模組包
modpack.wizard=匯出模組包引導
modpack.wizard.step.1=基本設定
@@ -619,17 +639,23 @@ modpack.wizard.step.initialization.warning=在製作模組包前,請您確認
modpack.wizard.step.initialization.server=點選此處查看有關伺服器自動更新模組包的製作教學
modrinth.category.adventure=冒險
modrinth.category.challenging=高難度
modrinth.category.combat=戰鬥
modrinth.category.cursed=Cursed
modrinth.category.decoration=裝飾
modrinth.category.equipment=裝備
modrinth.category.fabric=Fabric
modrinth.category.food=食物
modrinth.category.forge=Forge
modrinth.category.kitchen-sink=大雜燴
modrinth.category.library=支持庫
modrinth.category.lightweight=輕量
modrinth.category.magic=魔法
modrinth.category.misc=其他
modrinth.category.modloader=Modloader
modrinth.category.multiplayer=多人
modrinth.category.optimization=最佳化
modrinth.category.quests=任務
modrinth.category.quilt=Quilt
modrinth.category.rift=Rift
modrinth.category.storage=儲存
@@ -644,8 +670,8 @@ mods.add.success=成功新增模組 %s。
mods.category=類別
mods.check_updates=檢查模組更新
mods.check_updates.current_version=當前版本
mods.check_updates.failed=部分文件下載失敗
mods.check_updates.file=文件
mods.check_updates.failed=部分檔案下載失敗
mods.check_updates.file=檔案
mods.check_updates.source=來源
mods.check_updates.target_version=目標版本
mods.check_updates.update=更新
@@ -668,87 +694,66 @@ mods.restore=回退
mods.url=官方頁面
multiplayer=多人聯機
multiplayer.agreement.prompt=使用多人聯機功能前,你需要先同意多人聯機服務提供方 ioi 系列作品的用戶協議與免責聲明。\n用戶使用聯機服務的行為,將被視為無條件同意該用戶協議與免責聲明。
multiplayer.agreement.prompt=多人聯機功能由 速聚 提供。使用前,你需要先同意多人聯機服務提供方 速聚 的用戶協議與免責聲明。\n你需要了解,HMCL 僅為 速聚 提供多人聯機服務入口,使用中遇到的任何問題由 速聚 負責處理。您在使用多人聯機服務過程中所遇到的任何問題與糾紛(包括其付費業務)均與 HMCL 無關,應與 速聚 協商解決。
multiplayer.download=正在下載相依元件
multiplayer.download.failed=初始化失敗,部分文件未能完成下載
multiplayer.download.failed=初始化失敗,部分檔案未能完成下載
multiplayer.download.success=多人聯機初始化完成
multiplayer.download.unsupported=多人聯機依賴不支持當前系統或平台
multiplayer.exit.after_ready=多人聯機會話意外退出,退出碼 %d
multiplayer.exit.before_ready=多人聯機房間創建失敗,cato 退出碼 %d
multiplayer.exit.timeout.static_token=無法連接多人聯機服務,你的憑證可能無法正常工作,你可以清空憑證再試。\n你可以聯系在線管理員請問鑑權伺服器是否正常工作,或者耐心等待十分鍾。
multiplayer.exit.timeout.dynamic_token=無法連接多人聯機服務,你可以在多人聯機頁面的回饋中回饋問題。
multiplayer.hint=多人聯機功能處於實驗階段,如果有問題請回饋。
multiplayer.nat=網路檢測
multiplayer.nat.failed=檢測失敗,但你仍然可以繼續使用聯機功能。
multiplayer.nat.hint=執行網路檢測可以讓你更清楚你的網路狀況是否符合聯機功能的需求。不符合聯機功能運行條件的網路狀況將可能導致聯機失敗。
multiplayer.nat.latency=延遲
multiplayer.nat.not_yet_tested=尚未檢測
multiplayer.nat.packet_loss_ratio=丟包率
multiplayer.nat.testing=檢測中
multiplayer.nat.type=NAT 類型
multiplayer.nat.type.blocked_udp=極差(網路禁止 UDP 協議)
multiplayer.nat.type.full_cone=好(完全圓錐型)
multiplayer.nat.type.open_access=好(公網開放型)
multiplayer.nat.type.port_restricted_cone=中(埠受限圓錐型)
multiplayer.nat.type.restricted_cone=中(受限圓錐型)
multiplayer.nat.type.symmetric=差(對稱型)
multiplayer.nat.type.symmetric_udp_firewall=差(對稱型+防火牆)
multiplayer.nat.type.unknown=未知
multiplayer.powered_by=多人聯機服務由(<a href="https://mcer.cn">mcer.cn</a>) 提供。<a href="https://hmcl.huangyuhui.net/api/redirect/multiplayer-agreement">用戶協議與免責聲明</a>
multiplayer.error.failed_get_device=HiPer無法創建網路設備,可能是 HiPer 正在運行中。請關閉正在運行中的其他啟動器,或通過工作管理員終止 HiPer。
multiplayer.error.failed_load_config=HiPer 初始化失敗,可能是配置文件存在問題或證書已失效。
multiplayer.error.failed_sudo.linux=HiPer 需要管理員許可權才能運行,您可以通過設置環境變量 HMCL_ASKPASS 配置 HiPer 如何申請權限。\n若將 HMCL_ASKPASS 設置為 'false',請通過配置 sudoers 文件允許 '%s' 免密獲取 root 權限,重啟後再次啟動 HMCL 即可;\n若將 HMCL_ASKPASS 設置為 'user',請先設置環境變量 SUDO_ASKPASS,HMCL 將使用 sudo --askpass 啟動 HiPer (具體請參見 man sudo)。
multiplayer.error.failed_sudo.mac=HiPer 需要管理員許可權才能運行。是否要授予 HiPer 管理員許可權? \n點擊“是”授予 HiPer 管理員許可權,然後重啓電腦後再次打開啟動器即可聯機。
multiplayer.error.failed_sudo.windows=HiPer 需要管理員權限才能運行,請使用管理員權限重新啟動 HMCL。是否查看教程?
multiplayer.error.file_not_found=已發現 HiPer 有可用的更新,請重新進入多人聯機頁面以更新 HiPer。
multiplayer.error.session_expired=本次使用時間已結束,若要繼續使用,請更新索引碼
multiplayer.exit=HiPer 意外退出,退出碼 %d
multiplayer.help.1=管理員權限打開
multiplayer.help.2=多人聯機教程
multiplayer.help.3=創建方幫助
multiplayer.help.4=參與者幫助
multiplayer.help.text=測試能否聯機
multiplayer.hint=多人聯機服務正在維護中。
multiplayer.hint.details=查看詳情
multiplayer.persistence=授權信息管理
multiplayer.persistence.export=將授權信息導出至文件
multiplayer.persistence.export.button=導出授權文件
multiplayer.persistence.export.failed=導出授權文件失敗,請檢查您所選擇的保存路徑。
multiplayer.persistence.export.file_not_exists=獲取授權文件失敗,請檢查索引碼是否輸入正確。
multiplayer.persistence.export.title=選擇授權文件保存路徑
multiplayer.persistence.hint=此功能為長期授權 (有效期超過 24 小時) 用戶提供,如果你正在使用短期授權 (有效期不超過 24 小時),則無需使用本功能。\n當你使用長期授權時,請在獲取授權後的 24 小時內使用索引碼啟動 HiPer,否則 HiPer 將無法獲取授權信息。\n隨後,你可以通過下方的“導出授權信息”功能保存授權文件。\n請注意妥善保管授權文件,在獲取授權 24 小時後,該文件是你的長期授權的唯一憑證,丟失該文件將無法通過索引碼進行聯機。
multiplayer.persistence.import=從文件導入授權信息
multiplayer.persistence.import.button=導入授權文件
multiplayer.persistence.import.failed=導入授權文件失敗。
multiplayer.persistence.import.file_already_exists=授權文件已經存在。
multiplayer.persistence.import.title=選擇授權文件
multiplayer.persistence.import.token_not_match=你選擇的授權文件可能與索引碼不匹配,是否繼續導入?
multiplayer.persistence.license_file=授權文件
multiplayer.powered_by=本服務由 (<a href="https://mcer.cn">速聚</a>) 提供。<a href\="https://docs.hmcl.net/multiplayer/#%E4%BD%BF%E7%94%A8%E6%8E%88%E6%9D%83">授權協議</a>
multiplayer.report=違法違規檢舉
multiplayer.relay=橋接服務
multiplayer.relay.hint=Cato 面向較差網路提供的網路質量增強最佳化解決方案|若無法聯機請到 mcer.cn 的個人中心兌換憑證後啟用
multiplayer.session=房間
multiplayer.session.name.format=%1$s 的房間
multiplayer.session.name.motd=HMCL 多人聯機房間 - %s
multiplayer.session.close=關閉房間
multiplayer.session.close.warning=關閉房間後,已經加入聯機房間的玩家將會斷開連接,是否繼續?
multiplayer.session.copy_room_code=複製邀請碼
multiplayer.session.create=創建房間
multiplayer.session.create.error.dynamic_token=創建聯機房間失敗,請稍後再試。
multiplayer.session.create.error.static_token=創建聯機房間失敗,你的憑證可能無法正常工作,你可以清空憑證再試。\n你可以聯系在線管理員請問鑑權伺服器是否正常工作,或者耐心等待十分鍾。
multiplayer.session.create.hint=創建聯機房間前,你需要先在正在運行的遊戲內的遊戲菜單中選擇 對區域網路開放 選項,然後在下方的輸入框中輸入遊戲內提示的埠號(通常是 5 位的數字)
multiplayer.session.create.join=連接申請
multiplayer.session.create.join.allow=自動接受所有連接申請(不啟用此選項時,你需要手動同意申請,以避免不相關人士誤連你的伺服器)
multiplayer.session.create.join.prompt=玩家 %s 申請加入多人聯機房間,是否接受?
multiplayer.session.create.members=成員
multiplayer.session.create.members.kick=踢出房間
multiplayer.session.create.members.kick.prompt=是否踢出該玩家?踢出後該玩家不能再參與該聯機房間。
multiplayer.session.create.name=房間名稱
multiplayer.session.create.port=埠號
multiplayer.session.create.port.error=無法檢測遊戲埠號,你必須先啟動遊戲並在遊戲內打開對區域網路開放選項後才能啟動聯機。
multiplayer.session.create.token=憑證
multiplayer.session.create.token.apply=申請憑證
multiplayer.session.create.token.prompt=預設為無憑證。你可以點擊旁邊的“申請憑證”獲得詳情
multiplayer.session.error.already_started=本地已經開啟 cato 服務,請檢查是否有其他 HMCL 正在運行聯機服務。或者你可以在任務管理器裡殺掉 cato 進程以繼續。
multiplayer.session.error.file_not_found=找不到 cato 程序。該程序應該在進入多人聯機頁面時完成下載。請檢查你電腦的防毒軟體是否將 cato 標記為病毒,如果是,請恢復 cato。
multiplayer.session.expired=聯機會話連續使用時間超過了 3 小時,你需要重新創建/加入房間以繼續聯機。
multiplayer.session.join=加入房間
multiplayer.session.join.error=加入房間失敗
multiplayer.session.join.error.connection=加入房間失敗。無法與對方建立連接。如果你或對方的網路類型是差(對稱型),可能無法使用聯機功能。
multiplayer.session.join.hint=你需要向已經創建好房間的玩家索要邀請碼以便加入多人聯機房間
multiplayer.session.join.invitation_code=邀請碼
multiplayer.session.join.invitation_code.error=邀請碼不正確,請向開服玩家獲取邀請碼
multiplayer.session.join.kicked=你與房間失去連接:%s。
multiplayer.session.join.kicked.join_acceptance_timeout=對方未能即時同意你的加入申請
multiplayer.session.join.kicked.kicked=你被房主踢出房間。
multiplayer.session.join.kicked.version_not_matched=多人聯機功能版本號不一致,請保證連接多人聯機功能版本號一致。
multiplayer.session.join.lost_connection=你已與房間失去連接。這可能意味著房主已經解散房間,或者你無法連接至房間。
multiplayer.session.join.port.error=無法找到可用的本地網路埠,請確保 HMCL 擁有綁定本地埠的權限。
multiplayer.session.join.rejected=你被房主拒絕連接。
multiplayer.session.join.wait=等待對方同意加入申請。
multiplayer.session.members=房間成員
multiplayer.session.quit=退出房間
multiplayer.session.quit.warning=退出房間後,你將會與伺服器斷開連接,是否繼續?
multiplayer.session.username=使用者名稱
multiplayer.state.connecting=連接中
multiplayer.state.disconnected=未創建/加入房間
multiplayer.state.disconnected.hint=多人聯機功能需要先有一位玩家創建房間後,其他玩家加入房間後繼續遊戲。
multiplayer.state.master=你已創建房間:%1$s,埠號 %2$d
multiplayer.state.master.hint=創建房間後,你可以點擊複製邀請碼,並發送給你希望加入聯機的玩家。這些玩家在進入 HMCL 多人聯機頁面後,點擊加入房間並黏貼邀請碼即可加入聯機房間。
multiplayer.state.slave=你已加入房間: %1$s,位址為 %2$s
multiplayer.state.slave.copy=拷貝位址
multiplayer.state.slave.hint=加入房間後,你需要在 Minecraft 的多人遊戲頁面選擇 HMCL 多人聯機房間伺服器,或者手動添加下方的地址的伺服器。
multiplayer.token=索引碼
multiplayer.token.apply=申請索引碼
multiplayer.token.format_invalid=索引碼格式不正確
multiplayer.token.invalid=索引碼不正確。
multiplayer.token.expired=HiPer 證書過期,請重新啟動 HMCL 再試。
multiplayer.token.malformed=HiPer 配置檔案無法解析,請重新啟動 HMCL 再試。
multiplayer.token.prompt=你需要索引碼才能使用多人聯機服務。點擊旁邊的“申請索引碼”查看詳情
multiplayer.off.hint=由於需要注册系統網路服務許可權,啟動 HiPer 時將會向用戶申請管理員許可權。若出現認證提示,允許以啟動 HiPer。
multiplayer.off.start=啟動 HiPer
multiplayer.master=创建方提示
multiplayer.master.hint=1.啟動遊戲\n2.選擇單人遊戲模式進入一個存檔\n3.在遊戲選項菜單內選擇 對局域網開放 選項,之後你可以在遊戲聊天框內看到遊戲提示的端口號(通常是 4~5 位數字)\n4.點擊下方的生成伺服器地址按鈕,輸入端口號,你就可以獲得你的伺服器地址了\n5.該地址需要提供給其他需要加入伺服器的玩家用於添加伺服器。
multiplayer.master.server_address=生成伺服器地址
multiplayer.master.server_address.copy=拷貝
multiplayer.master.video_tutorial=教學影片
multiplayer.master.port=埠號
multiplayer.master.port.validate=在遊戲聊天框中出現的埠號 (0~65535)
multiplayer.slave=參與者提示
multiplayer.slave.hint=1.要求創建方按照上方的 創建方提示 操作\n2.啟動遊戲\n3.選擇多人遊戲模式,選擇添加服務器\n4.遊戲會要求你輸入服務器地址,你只需要向創建方索要服務器地址並輸入,並進入服務器即可。
multiplayer.slave.hint2=1.一般情況下,參與者的遊戲賬戶必須是 微軟賬戶 或 外置登錄賬戶(如 Little Skin),否則你需要將服務器地址輸入至下方的輸入框中並點擊“加入”,在遊戲中選擇多人遊戲模式,進入局域網世界方可加入\n2.一般情況下,參與者的遊戲版本、模組要必須與創建方的一致,否則加入失敗。
multiplayer.slave.server_address=創建方伺服器地址
multiplayer.slave.server_address.start=加入
multiplayer.slave.server_address.stop=退出
multiplayer.slave.video_tutorial=教學影片
multiplayer.session.expiration=索引碼到期時間
datapack=資料包
datapack.add=加入資料包
@@ -771,6 +776,34 @@ world.import.already_exists=此世界已經存在
world.import.choose=選擇要匯入的存檔壓縮檔
world.import.failed=無法匯入此世界: %s
world.import.invalid=無法識別的存檔壓縮包
world.info.title=世界 %s - 世界資訊
world.info.basic=基本資訊
world.info.allow_cheats=允許作弊
world.info.dimension.the_nether=下界
world.info.dimension.the_end=末地
world.info.difficulty=難度
world.info.difficulty.peaceful=和平
world.info.difficulty.easy=簡單
world.info.difficulty.normal=普通
world.info.difficulty.hard=困難
world.info.game_version=遊戲版本
world.info.last_played=上一次遊戲時間
world.info.generate_features=生成建築
world.info.player=玩家資訊
world.info.player.food_level=饑餓值
world.info.player.game_type=遊戲模式
world.info.player.game_type.adventure=冒險
world.info.player.game_type.creative=創造
world.info.player.game_type.spectator=旁觀
world.info.player.game_type.survival=生存
world.info.player.health=生命值
world.info.player.last_death_location=上次死亡位置
world.info.player.location=位置
world.info.player.spawn=床/重生錨位置
world.info.player.xp_level=經驗等級
world.info.random_seed=種子
world.info.time=遊戲內時間
world.info.time.format=%s 天
world.game_version=遊戲版本
world.manage=世界/資料包
world.name=世界名稱
@@ -816,7 +849,7 @@ settings.advanced.custom_commands=自訂命令
settings.advanced.custom_commands.hint=自訂命令被調用時將包含如下的環境變數:\n\
\ - $INST_NAME: 版本名稱\n\
\ - $INST_ID: 版本名稱\n\
\ - $INST_DIR: 版本文件夾\n\
\ - $INST_DIR: 版本資料夾\n\
\ - $INST_MC_DIR: 遊戲運行路徑\n\
\ - $INST_JAVA: 遊戲運行使用的 Java 路徑\n\
\ - $INST_FORGE: 若安裝了 Forge,將會存在本環境變數\n\
@@ -825,13 +858,16 @@ settings.advanced.custom_commands.hint=自訂命令被調用時將包含如下
\ - $INST_FABRIC: 若安裝了 Fabric,將會存在本環境變數
settings.advanced.dont_check_game_completeness=不檢查遊戲完整性
settings.advanced.dont_check_jvm_validity=不檢查 JVM 與遊戲的相容性
settings.advanced.dont_patch_natives=不嘗試自動替換本機庫
settings.advanced.game_dir.default=預設(.minecraft/)
settings.advanced.game_dir.independent=各版本獨立(.minecraft/versions/<版本名>/,除 assets、libraries)
settings.advanced.java_permanent_generation_space=記憶體永久儲存區域
settings.advanced.java_permanent_generation_space.prompt=格式: MB
settings.advanced.jvm=Java 虛擬機設定
settings.advanced.jvm_args=Java 虛擬機參數
settings.advanced.jvm_args.prompt=填寫此處可以覆蓋預設設定
settings.advanced.jvm_args.prompt=- 若在“Java 虛擬機參數”中輸入的參數與默認參數相同,則不會添加\n\
- 在“Java 虛擬機參數”輸入任何 GC 參數,默認參數的 G1 參數會禁用\n\
- 點擊下方“不添加默認的 JVM 參數”可在啟動遊戲時不添加默認參數
settings.advanced.launcher_visibility.close=遊戲啟動後結束啟動器
settings.advanced.launcher_visibility.hide=遊戲啟動後隱藏啟動器
settings.advanced.launcher_visibility.hide_and_reopen=隱藏啟動器並在遊戲結束後重新開啟
@@ -859,6 +895,7 @@ settings.advanced.server_ip=伺服器位址
settings.advanced.server_ip.prompt=預設,啟動遊戲後直接進入對應伺服器
settings.advanced.use_native_glfw=[Linux] 使用系統 GLFW
settings.advanced.use_native_openal=[Linux] 使用系統 OpenAL
settings.advanced.use_software_renderer=使用 OpenGL 軟渲染器(相容性更好,但效能較差)
settings.advanced.workaround=除錯選項
settings.advanced.workaround.warning=除錯選項僅提供給專業玩家使用。修改除錯選項可能會導致遊戲無法啟動。除非你知道你在做什麼,否則請你不要修改這些選項。
settings.advanced.wrapper_launcher=前置指令
@@ -952,13 +989,13 @@ update.changelog=更新日誌
update.channel.dev=測試版
update.channel.dev.hint=你正在使用測試版。測試版包含一些未在正式版中包含的測試性功能,僅用於體驗新功能。\n\
測試版功能未受充分驗證,使用起來可能不穩定!\n\
如果你遇到了使用問題,可以在設置的 <a href="hmcl://settings/feedback">回饋頁面</a> 中進行回饋,或加入回饋頁面中提供的 <a href="https://discord.gg/jVvC7HfM6U">Discord</a> 或 <a href="https://kaihei.co/Kx7n3t">開黑啦</a>群以回饋問題。\n\n\
如果你遇到了使用問題,可以在設置的 <a href="hmcl://settings/feedback">回饋頁面</a> 中進行回饋,或加入回饋頁面中提供的 <a href="https://discord.gg/jVvC7HfM6U">Discord</a> 或 <a href="https://kook.top/Kx7n3t">KOOK 群</a>以回饋問題。\n\n\
你需要 <a href="https://hmcl.huangyuhui.net/api/redirect/sponsor">贊助</a> 或在回饋過程中作出貢獻以隱藏本提示。
update.channel.dev.title=測試版提示
update.channel.nightly=預覽版
update.channel.nightly.hint=你正在使用預覽版。預覽版可能會每天更新一次,包含一些未在正式版和測試版中包含的測試性功能,僅用於體驗新功能\n\
測試版功能未受充分驗證,使用起來可能不穩定!\n\
如果你遇到了使用問題,可以在設置的 <a href="hmcl://settings/feedback">回饋頁面</a> 中進行回饋,或加入回饋頁面中提供的 <a href="https://discord.gg/jVvC7HfM6U">Discord</a> 或 <a href="https://kaihei.co/Kx7n3t">開黑啦</a>群以回饋問題。\n\n\
如果你遇到了使用問題,可以在設置的 <a href="hmcl://settings/feedback">回饋頁面</a> 中進行回饋,或加入回饋頁面中提供的 <a href="https://discord.gg/jVvC7HfM6U">Discord</a> 或 <a href="https://kook.top/Kx7n3t">KOOK 群</a>以回饋問題。\n\n\
你需要 <a href="https://hmcl.huangyuhui.net/api/redirect/sponsor">贊助</a> 或在回饋過程中作出貢獻以隱藏本提示。
update.channel.nightly.title=預覽版提示
update.channel.stable=建議版本
@@ -27,8 +27,8 @@ about.claim.statement=点击链接以查看全文
about.community=社区
about.community.discord=Discord
about.community.discord.statement=欢迎加入 Discord 讨论区,加入后请遵守讨论区规定
about.community.kaiheila=开黑啦
about.community.kaiheila.statement=欢迎加入开黑啦讨论区,加入后请遵守讨论区规定!
about.community.kookapp=KOOK
about.community.kookapp.statement=欢迎加入 KOOK 讨论区,加入后请遵守讨论区规定!
about.dependency=依赖
about.legal=法律声明
about.thanks_to=鸣谢
@@ -60,7 +60,7 @@ account.create.yggdrasil=添加 Mojang 帐户
account.create.offline=添加离线模式帐户
account.create.authlibInjector=添加外置登录帐户 (authlib-injector)
account.email=邮箱
account.failed=错误码: %d
account.failed=账户刷新失败!
account.failed.character_deleted=此角色已被删除
account.failed.connect_authentication_server=无法连接认证服务器,可能是网络问题,请检查设备能否正常上网或使用代理服务
account.failed.connect_injector_server=无法连接认证服务器,可能是网络问题,请检查设备是否能正常上网,检查 URL 是否输入错误,或使用代理服务
@@ -70,24 +70,31 @@ account.failed.invalid_password=无效的密码
account.failed.invalid_token=请尝试登出并重新输入密码登录
account.failed.migration=你的帐号需要被迁移至微软帐号。如果你已经迁移,你需要使用微软登录方式登录迁移后的微软帐号。
account.failed.no_character=该帐号没有角色
account.failed.server_disconnected=无法访问登录服务器,账户信息刷新失败!\n你可以选择 跳过账户刷新(但启动游戏后可能会因为账户信息过期而导致无法进入开启正版验证的服务器)\n或尝试再次刷新账户?
account.failed.server_response_malformed=无法解析认证服务器响应,可能是服务器故障
account.failed.wrong_account=登录了错误的帐号
account.hmcl.hint=你需要点击“登录”按钮,并在打开的网页中完成登录
account.injector.add=添加认证服务器
account.injector.empty=无(点击右侧加号添加)
account.injector.http=警告:此服务器使用不安全的 HTTP 协议,您的密码在登录时会被明文传输!
account.injector.link.homepage=主页
account.injector.link.register=注册
account.injector.server=认证服务器
account.injector.server_url=服务器地址
account.injector.server_name=服务器名称
account.login=登录
account.login.hint=我们不会保存你的密码
account.login.skip=跳过账户刷新
account.login.retry=再次刷新账户
account.login.refresh=重新登录
account.login.refresh.microsoft.hint=<b>因为账户授权失效,需要重新添加你的微软账户</b>\n你需要按照以下步骤添加:\n \n1.点击“确定”按钮\n2.在网页浏览器显示的网站中输入 HMCL 显示的代码(自动拷贝,直接粘贴即可),并点击“下一步”\n3.按照网站的提示登录\n4.当网站提示“是否允许此应用访问你的信息?”的标识时,请点击“是”\n5.当网站提示“大功告成”的标识时,及表示登录成功!然后等待账户完成添加即可!\n \n-若网站提示“出现错误”的标识时,请重新按照以上步骤重新添加\n-若账户添加失败,请重新按照以上步骤重新添加\n<b>-若设备网络环境不佳,可能登录网站加载很慢甚至无法加载,此时请使用 VPN 或代理服务器并重试</b>\n-若登录微软账户的 Token (不是密码)泄露,可点击下方“解除账户绑定”解除登录授权,然后等待 Token 过期
account.login.refresh.microsoft.manual=<b>因为账户授权失效,需要重新添加你的微软账户</b>\n你需要按照以下步骤添加:\n \n1.点击“确定”按钮\n2.在网页浏览器显示的网站中输入:<b>%1$s</b>(已自动拷贝,点此再次拷贝),并点击“下一步”\n3.按照网站的提示登录\n4.当网站提示“是否允许此应用访问你的信息?”的标识时,请点击“是”\n5.当网站提示“大功告成”的标识时,及表示登录成功!然后等待账户完成添加即可!\n \n-若网站提示“出现错误”的标识时,请重新按照以上步骤重新添加\n-若账户添加失败,请重新按照以上步骤重新添加\n-若网站未能显示,请手动在网页浏览器中打开:%2$s\n<b>-若设备网络环境不佳,可能登录网站加载很慢甚至无法加载,此时请使用 VPN 或代理服务器并重试</b>\n-若登录微软账户的 Token (不是密码)泄露,可点击下方“解除账户绑定”解除登录授权,然后等待 Token 过期
account.logout=登出
account.register=注册
account.manage=帐户列表
account.methods=登录方式
account.methods.authlib_injector=外置登录 (authlib-injector)
account.methods.little_skin=Little Skin
account.methods.microsoft=微软帐户
account.methods.microsoft.birth=如何修改帐户出生日期
account.methods.microsoft.close_page=已完成微软帐户授权,接下来启动器还需要完成剩余登录步骤。你已经可以关闭本页面了。
@@ -96,13 +103,15 @@ account.methods.microsoft.error.add_family=由于你未满 18 岁,你的帐户
account.methods.microsoft.error.add_family_probably=请检查你的帐户设置,如果年龄未满 18 岁,你的帐户必须被加入到家庭中才能登录游戏。你也可以点击上方链接更改你的帐户的出生日期,使年龄满 18 岁以上以继续登录。
account.methods.microsoft.error.country_unavailable=你所在的国家或地区不受 XBox Live 的支持。
account.methods.microsoft.error.missing_xbox_account=你的微软帐户尚未关联 XBox 帐户,你必须先创建 XBox 帐户,才能登录游戏。
account.methods.microsoft.error.no_character=该帐户没有包含 Minecraft Java 版购买记录
account.methods.microsoft.error.no_character=该帐户未包含 Minecraft Java 版购买记录\n可能未创建游戏档案,请点击上方链接创建
account.methods.microsoft.error.unknown=登录失败,错误码:%d
account.methods.microsoft.logging_in=登录中……
account.methods.microsoft.makegameidsettings=创建档案
account.methods.microsoft.hint=你需要按照以下步骤添加:\n1.点击“登录”按钮\n2.在网页浏览器显示的网站中输入 HMCL 显示的代码(自动拷贝,直接粘贴即可),并点击“下一步”\n3.按照网站的提示登录\n4.当网站提示“是否允许此应用访问你的信息?”的标识时,请点击“是”\n5.当网站提示“大功告成”的标识时,及表示登录成功!然后等待账户完成添加即可!\n-若网站提示“出现错误”的标识时,请重新按照以上步骤重新添加\n-若账户添加失败,请重新按照以上步骤重新添加\n<b>-若设备网络环境不佳,可能登录网站加载很慢甚至无法加载,此时请使用 VPN 或代理服务器并重试</b>\n-若登录微软账户的 Token (不是密码)泄露,可点击下方“解除账户绑定”解除登录授权,然后等待 Token 过期
account.methods.microsoft.manual=你需要按照以下步骤添加:\n1.点击“登录”按钮\n2.在网页浏览器显示的网站中输入:<b>%1$s</b>(已自动拷贝,点此再次拷贝),并点击“下一步”\n3.按照网站的提示登录\n4.当网站提示“是否允许此应用访问你的信息?”的标识时,请点击“是”\n5.当网站提示“大功告成”的标识时,及表示登录成功!然后等待账户完成添加即可\n-若网站提示“出现错误”的标识时,请重新按照以上步骤重新添加\n-若账户添加失败,请重新按照以上步骤重新添加\n-若网站未能显示,请手动在网页浏览器中打开:%2$s\n<b>-若设备网络环境不佳,可能登录网站加载很慢甚至无法加载,此时请使用 VPN 或代理服务器并重试</b>\n-若登录微软账户的 Token (不是密码)泄露,可点击下方“解除账户绑定”解除登录授权,然后等待 Token 过期
account.methods.microsoft.profile=帐户设置页
account.methods.microsoft.snapshot=HMCL 快照版不支持微软登录
account.methods.forgot_password=忘记密码
account.methods.microsoft.snapshot=HMCL 快照版暂不提供微软登录支持,请使用推荐版本(稳定版)或测试版进行登录!
account.methods.microsoft.waiting_browser=等待在新打开的浏览器窗口中完成登录……
account.methods.offline=离线模式
account.methods.offline.uuid=UUID
@@ -146,6 +155,7 @@ assets.index.malformed=资源文件的索引文件损坏,您可以在相应的
button.cancel=取消
button.change_source=切换下载源
button.clear=清除
button.copy_and_exit=复制并退出
button.delete=删除
button.edit=修改
button.install=安装
@@ -155,6 +165,7 @@ button.ok=确定
button.refresh=刷新
button.remove=删除
button.remove.confirm=您确定要删除吗?此操作无法撤销!
button.retry=重试
button.save=保存
button.save_as=另存为
button.select_all=全选
@@ -184,7 +195,7 @@ curse.category.4479=高难度
curse.category.4482=大型整合包
curse.category.4472=科技
curse.category.4473=魔法
curse.category.5128=香草+
curse.category.5128=原版增强
# https://addons-ecs.forgesvc.net/api/v2/category/section/6
curse.category.5299=教育
@@ -298,6 +309,7 @@ download.provider.mojang=官方(OptiFine 自动安装使用 BMCLAPI 下载源
download.provider.official=尽量使用官方源(最新,但可能加载慢)
download.provider.balanced=选择加载速度快的下载源(平衡,但可能不是最新)
download.provider.mirror=尽量使用镜像源(加载快,但可能不是最新)
download.java=下载 Java
download.javafx=正在下载必要的运行时组件……
download.javafx.notes=正在通过网络下载 HMCL 必要的运行时组件。\n点击“切换下载源”按钮查看详情以及选择下载源,点击“取消”按钮停止并退出。\n注意:若下载速度过慢,请尝试切换下载源
download.javafx.component=正在下载模块 %s
@@ -316,13 +328,19 @@ extension.ps1=PowerShell 脚本
extension.sh=Bash 脚本
fatal.javafx.incompatible=缺少 JavaFX 运行环境。\nHMCL 无法在低于 Java 11 且缺少 JavaFX 的 Java 环境上自行补全 JavaFX 运行环境。\n请更换如 Oracle Java 8 等包含 JavaFX 的 Java 运行环境,或者更新到 Java 11 或更高版本。
fatal.javafx.incompatible.loongson=缺少 JavaFX 运行环境。\n请使用龙芯 JDK 8 (http://www.loongnix.cn/zh/api/java/downloads-jdk8/index.html) 启动 HMCL。
fatal.javafx.missing=缺少 JavaFX 运行环境。\n如果您使用的是 Java 11 或更高版本,请降级到 Oracle JRE 8(java.com),或者安装 BellSoft Liberica Full JRE(bell-sw.com/pages/downloads/?package=jre-full)。\n如果您使用的是其他 OpenJDK 构建,请确保其包含 OpenJFX!
fatal.missing_dst_root_ca_x3=当前 Java 平台缺少 DST Root CA X3 证书。\n您依然可以使用 Hello Minecraft! Launcher,但将无法连接到部分站点(如使用 Lets Encrypt 证书的站点),这可能会使 HMCL 无法正常工作。\n请将您的 Java 升级到 8u101 以上以解决此问题。
fatal.config_loading_failure=Hello Minecraft! Launcher 无法加载配置文件\n请确保 Hello Minecraft! Launcher 对 "%s" 目录及该目录下的文件拥有读写权限!
fatal.config_change_owner_root=你正在使用 root 账户启动 Hello Minecraft! Launcher, 这可能导致你未来无法正常使用其他账户正常启动 Hello Minecraft! Launcher。\n是否继续启动?
fatal.config_loading_failure=Hello Minecraft! Launcher 无法加载配置文件\n请确保 Hello Minecraft! Launcher 对 "%s" 目录及该目录下的文件拥有读写权限。
fatal.config_loading_failure.unix=Hello Minecraft! Launcher 无法加载配置文件,因为配置文件是由用户 %1$s 创建的。\n请使用 root 账户启动 HMCL (不推荐),或在终端中执行以下命令将配置文件的所有权变更为当前用户:\n%2$s
fatal.migration_requires_manual_reboot=Hello Minecraft! Launcher 即将完成升级,请重新打开 Hello Minecraft! Launcher。
fatal.apply_update_failure=我们很抱歉 Hello Minecraft! Launcher 无法自动完成升级,因为出现了一些问题……\n但你依可以从 %s 处手动下载 Hello Minecraft! Launcher 来完成升级\n请考虑向我们反馈该问题!
fatal.samba=如果您正在通过 Samba 共享的文件夹中运行 HMCL,HMCL 可能无法正常工作,请尝试更新您的 Java 或在本地文件夹内运行 HMCL。
fatal.illegal_char=您的用户文件夹路径中存在非法字符‘=’。HMCL 能够运行,但可能某些功能无法正常使用!\n你将无法使用外置登录账户以及离线登录更换皮肤功能,并且在进行多人游戏时可能存在更大的安全隐患!
fatal.unsupported_platform=Minecraft 尚未为您的平台提供完善支持,所以可能影响游戏体验或无法启动游戏。\n若无法启动 Minecraft 1.17 及以上版本,可以尝试在版本设置中打开“使用 OpenGL 软渲染器”选项,使用 CPU 渲染以获得更好的兼容性。
fatal.unsupported_platform.osx_arm64=HMCL 已为 Apple Silicon 平台提供支持,使用 ARM 原生 Java 启动游戏以获得更流畅的游戏体验。\n如果你在游戏中遭遇问题,使用 x86-64 架构的 Java 启动游戏可能有更好的兼容性。
fatal.unsupported_platform.windows_arm64=HMCL 已为 Windows on Arm 平台提供原生支持。如果你在游戏中遭遇问题,请尝试使用 x86 架构的 Java 启动游戏。\n\n如果你正在使用<b>高通</b>平台,你可能需要安装 <a href="ms-windows-store://pdp/?productid=9NQPSL29BFFF">OpenGL 兼容包</a>后才能进行游戏。点击链接前往 Microsoft Store 安装兼容包。
feedback=反馈
feedback.add=新增反馈
@@ -361,11 +379,11 @@ folder.saves=存档文件夹
folder.screenshots=截图文件夹
game=游戏
game.crash.feedback=查看了日志发现该问题很常见?在反馈页面或 Github Issues 提交反馈,可丰富崩溃分析系统!
game.crash.feedback=查看了日志发现该问题很常见?在 <a href="https://discord.gg/jVvC7HfM6U">Discord</a> 或 <a href="https://kook.top/Kx7n3t">KOOK 群</a>提交反馈,以丰富崩溃分析系统!
game.crash.info=游戏信息
game.crash.reason=崩溃原因
game.crash.reason.analyzing=分析中……
game.crash.reason.block=当前游戏因为某个方块不能正常工作,无法继续运行。\n你可以尝试通过 MCEdit(podshot.github.io/MCEdit-Unified)工具编辑存档删除该方块,或者直接删除相应的 Mod。\n方块类型:%1$s\n方块坐标:%2$s
game.crash.reason.block=当前游戏因为某个方块不能正常工作,无法继续运行。\n你可以尝试通过 <a href="https://podshot.github.io/MCEdit-Unified">MCEdit</a> 工具编辑存档删除该方块,或者直接删除相应的 Mod。\n方块类型:%1$s\n方块坐标:%2$s
game.crash.reason.bootstrap_failed=当前游戏因为模组 %1$s 错误,无法继续运行。\n你可以尝试删除或更新该模组以解决问题。
game.crash.reason.config=当前游戏因为无法解析模组配置文件,无法继续运行\n模组 %1$s 的配置文件 %2$s 无法被解析。
game.crash.reason.debug_crash=当前游戏因为手动触发崩溃,无法继续运行。\n事实上游戏并没有问题,问题都是你造成的!
@@ -376,14 +394,14 @@ game.crash.reason.fabric_warnings=Fabric 提供了一些警告信息:\n%1$s
game.crash.reason.file_already_exists=当前游戏因为文件 %1$s 已经存在,无法继续运行。\n如果你认为这个文件可以删除,你可以在备份这个文件后尝试删除它,并重新启动游戏。
game.crash.reason.file_changed=当前游戏因为文件校验失败,无法继续运行。\n如果你手动修改了 Minecraft.jar 文件,你需要回退修改,或者重新下载游戏。
game.crash.reason.gl_operation_failure=当前游戏因为你使用的某些 Mod、光影包、材质包,无法继续运行。\n请先尝试禁用你所使用的Mod/光影包/材质包再试。
game.crash.reason.graphics_driver=当前游戏因为你的显卡驱动存在问题崩溃了。\n\
请尝试升级你的显卡驱动到最新版本后再尝试启动游戏。\n\
game.crash.reason.graphics_driver=当前游戏因为你的显卡驱动存在问题崩溃了,请尝试升级你的显卡驱动到最新版本后再尝试启动游戏。\n\
如果你的电脑存在独立显卡,你需要检查游戏是否使用集成/核芯显卡启动。如果是,请尝试使用独立显卡启动 HMCL 与游戏。如果仍有问题,你可能需要考虑换一个新显卡或新电脑……\n\
如果你确实需要使用核芯显卡,请检查你的电脑的 CPU 是否是 Intel(R) Core(TM) 3000 系列或更旧的处理器,如果是,对于 Minecraft 1.16.5 及更旧版本,请你将游戏所使用的 Java 版本降级至 1.8.0_51 及以下版本 <a href="https://www.oracle.com/java/technologies/javase/javase8-archive-downloads.html">Java 1.8.0 历史版本</a> ,否则你必须更换独立显卡或新电脑。\n\
详情请点击 <a href="https://hmcl.huangyuhui.net/help/game/graphics-card">此处</a> 查看
如果你确实需要使用核芯显卡,请检查你的电脑的 CPU 是否是 Intel(R) Core(TM) 3000 系列或更旧的处理器,如果是,对于 Minecraft 1.16.5 及更旧版本,请你将游戏所使用的 Java 版本降级至 1.8.0_51 及以下版本 <a href="https://www.oracle.com/java/technologies/javase/javase8-archive-downloads.html">Java 1.8.0 历史版本</a> ,否则你需要更换独立显卡或新电脑。\n\
在版本设置中打开“使用 OpenGL 软渲染器”选项也可以解决此问题,但打开此选项后在 CPU 性能不足的情况下帧数会显著降低,仅推荐以调试为目的或应急时开启。\n\
可在 <a href="https://discord.gg/jVvC7HfM6U">Discord</a> 或 <a href="https://kook.top/Kx7n3t">KOOK 群</a>寻求帮助
game.crash.reason.illegal_access_error=当前游戏因为某些 Mod 的问题,无法继续运行。\n如果你认识:%1$s,你可以更新或删除对应 Mod 再试……
game.crash.reason.jdk_9=当前游戏因为 Java 版本过高,无法继续运行。\n你需要下载安装 Java 8,并在游戏设置中将 Java 设置为 1.8 的版本。
game.crash.reason.jvm_32bit=当前游戏因为内存分配过大,超过了 32 位 Java 内存限制,无法继续运行。\n如果你的电脑是 64 位系统,请下载安装并更换 64 位 Java。如果你的电脑是 32 位系统,你或许可以重新安装 64 位系统,或换一台新电脑。\n或者,你可以关闭游戏内存的自动分配,并且把内存限制调节为 1024 MB 或以下。
game.crash.reason.jvm_32bit=当前游戏因为内存分配过大,超过了 32 位 Java 内存限制,无法继续运行。\n如果你的电脑是 64 位系统,请下载安装并更换 64 位 Java。如果你的电脑是 32 位系统,你或许可以重新安装 64 位系统,或换一台新电脑。\n或者,你可以关闭游戏内存的自动分配,并且把内存限制调节为 1024 MB 或以下。可在 <a href="https://discord.gg/jVvC7HfM6U">Discord</a> 或 <a href="https://kook.top/Kx7n3t">KOOK 群</a>寻求帮助
game.crash.reason.loading_crashed_forge=当前游戏因为模组 %1$s (%2$s) 错误,无法继续运行。\n你可以尝试删除或更新该模组以解决问题。
game.crash.reason.loading_crashed_fabric=当前游戏因为模组 %1$s 错误,无法继续运行。\n你可以尝试删除或更新该模组以解决问题。
game.crash.reason.memory_exceeded=当前游戏因为分配的内存过大,无法继续运行。\n该问题是由于系统页面文件太小导致的。\n你需要在游戏设置中关闭游戏内存的自动分配,并将游戏内存调低至游戏能正常启动为止。\n你还可以尝试调大系统的页面大小。
@@ -395,16 +413,17 @@ game.crash.reason.mod_resolution_missing=当前游戏因为缺少 Mod 前置,
game.crash.reason.mod_resolution_missing_minecraft=当前游戏因为 Mod 和 Minecraft 游戏版本不匹配,无法继续运行。\n%1$s 需要 Minecraft %2$s 才能运行。\n如果你要继续使用你已经安装的 Mod,你可以选择安装对应的 Minecraft 版本;如果你要继续使用当前 Minecraft 版本,你需要安装对应版本的 Mod。
game.crash.reason.mod_resolution_mod_version=%1$s (版本号 %2$s)
game.crash.reason.mod_resolution_mod_version.any=%1$s (任意版本)
game.crash.reason.modlauncher_8=当前游戏因为您所使用的 Forge 版本与当前使用的 Java 冲突崩溃。请尝试更新 Forge,或使用 Java 8u312/11.0.13/17.0.1 及更早版本启动\n8u312 及更早版本下载:\noracle.com/java/technologies/javase/javase8u211-later-archive-downloads.html\n11.0.13 及更早版本下载:\noracle.com/java/technologies/javase/jdk11-archive-downloads.html\n17.0.1 及更早版本下载:\noracle.com/java/technologies/javase/jdk17-archive-downloads.html
game.crash.reason.modlauncher_8=当前游戏因为您所使用的 Forge 版本与当前使用的 Java 冲突崩溃。请尝试更新 Forge,或使用 Java 8u312/11.0.13/17.0.1 及更早版本启动\n <a href="https://oracle.com/java/technologies/javase/javase8u211-later-archive-downloads.html">8u312 及更早版本下载</a> <a href="https://oracle.com/java/technologies/javase/jdk11-archive-downloads.html">11.0.13 及更早版本下载</a> <a href="https://oracle.com/java/technologies/javase/jdk17-archive-downloads.html">17.0.1 及更早版本下载</a>\n可在 <a href="https://discord.gg/jVvC7HfM6U">Discord</a> 或 <a href="https://kook.top/Kx7n3t">KOOK 群</a>寻求帮助
game.crash.reason.no_class_def_found_error=当前游戏因为代码不完整,无法继续运行。\n你的游戏可能缺失了某个 Mod,或者某些 Mod 文件不完整,或者 Mod 与游戏的版本不匹配。\n你可能需要重新安装游戏和 Mod,或请求他人帮助。\n缺失:%1$s
game.crash.reason.no_such_method_error=当前游戏因为代码不完整,无法继续运行。\n你的游戏可能缺失了某个 Mod,或者某些 Mod 文件不完整,或者 Mod 与游戏的版本不匹配。\n你可能需要重新安装游戏和 Mod,或请求他人帮助。
game.crash.reason.opengl_not_supported=当前游戏因为你的显卡驱动存在问题,无法继续运行。\n原因是 OpenGL 不受支持,你现在是否在远程桌面或者串流模式下?如果是,请直接使用原电脑启动游戏。\n或者尝试升级你的显卡驱动到最新版本后再尝试启动游戏。如果你的电脑存在独立显卡,你需要检查游戏是否使用集成/核心显卡启动,如果是,请尝试使用独立显卡启动 HMCL 与游戏。如果仍有问题,你可能需要考虑换一个新显卡或新电脑。
game.crash.reason.openj9=当前游戏无法运行在 OpenJ9 虚拟机上,请你在游戏设置中更换 Hotspot Java 虚拟机,并重新启动游戏。如果没有下载安装,你可以在网上自行下载。
game.crash.reason.out_of_memory=当前游戏因为内存不足,无法继续运行。\n这可能是内存分配太小,或者 Mod 数量过多导致的。\n你可以在游戏设置中调大游戏内存分配值以允许游戏在更大的内存下运行。\n如果仍然出现该错误,你可能需要换一台更好的电脑。
game.crash.reason.processing_of_javaagent_failed=当前游戏因为加载 -javaagent 参数失败,无法继续运行。\n如果你在 Java 虚拟机参数 中添加了相关参数,请检查是否合法正确\n如果你没有添加相关参数或参数确认合法正确,请尝试:\n打开 控制面板 -- 时钟和区域 分类(选项为类别显示才有此选项,没有就跳过) -- 区域 -- 上方的 管理 选项卡 -- 下方的 更改系统区域设置 按钮 -- 在弹出的窗口中将 “使用 Unicode UTF-8 提供全球语言支持” 选项关闭,重启设备后再尝试启动游戏。<a href="https://gitcode.net/chearlai/f/-/raw/master/%E5%85%B3%E9%97%AD_%E4%BD%BF%E7%94%A8_Unicode_UTF-8_%E6%8F%90%E4%BE%9B%E5%85%A8%E7%90%83%E8%AF%AD%E8%A8%80%E6%94%AF%E6%8C%81_.png">操作详情</a>\n可在 <a href="https://discord.gg/jVvC7HfM6U">Discord</a> 或 <a href="https://kook.top/Kx7n3t">KOOK 群</a>寻求帮助
game.crash.reason.resolution_too_high=当前游戏因为材质包分辨率过高,无法继续运行\n你可以更换一个分辨率更低的材质,或者更换一个显存更大的显卡。
game.crash.reason.stacktrace=原因未知,请点击日志按钮查看详细信息。\n下面是一些关键词,其中可能包含 Mod 名称,你可以通过搜索的方式查找有关信息。\n%s
game.crash.reason.too_old_java=当前游戏因为 Java 虚拟机版本过低,无法继续运行。\n你需要在游戏设置中更换 Java %1$s 或更新版本的 Java 虚拟机,并重新启动游戏。如果没有下载安装,你可以点击 <a href="https://docs.microsoft.com/java/openjdk/download">此处</a> 下载微软 JDK。
game.crash.reason.unknown=原因未知,请点击日志按钮查看详细信息!\n<b>!!!请不要将本界面[截图]给他人!!!</b>如果你要求助他人,请你点击左下角导出游戏崩溃信息后将导出的文件发送给他人以供分析!!!\n查看了日志发现该问题很常见?你可以向我们提供游戏崩溃日志在反馈页面或 Github Issues 提交反馈以提升 HMCL 的日志分析能力
game.crash.reason.too_old_java=当前游戏因为 Java 虚拟机版本过低,无法继续运行。\n你需要在游戏设置中更换 Java %1$s 或更新版本的 Java 虚拟机,并重新启动游戏。如果没有下载安装,你可以点击 <a href="https://docs.microsoft.com/java/openjdk/download">此处</a> 下载微软 JDK。\n可在 <a href="https://discord.gg/jVvC7HfM6U">Discord</a> 或 <a href="https://kook.top/Kx7n3t">KOOK 群</a>寻求帮助
game.crash.reason.unknown=原因未知,请点击日志按钮查看详细信息!\n<b>!!!请不要将本界面【截图】给他人!!!</b>如果你要求助他人,请你点击左下角导出游戏崩溃信息后将导出的文件发送给他人以供分析!!!
game.crash.reason.unsatisfied_link_error=当前游戏因为缺少本地库,无法继续运行。\n这些本地库缺失:%1$s。\n如果你在游戏设置中修改了本地库路径选项,请你修改回预设模式。\n如果已经在预设模式下,请检查本地库缺失是否是 Mod 引起的,或由 HMCL 引起的。如果你确定是 HMCL 引起的,建议你向我们反馈。\n如果你确实需要自定义本地库路径,你需要保证其中包含缺失的本地库!
game.crash.title=游戏意外退出
game.directory=游戏路径
@@ -449,6 +468,8 @@ install.installer.install_online.tooltip=支持安装 Fabric、Forge、OptiFine
install.installer.liteloader=LiteLoader
install.installer.not_installed=不安装
install.installer.optifine=OptiFine
install.installer.quilt=Quilt
install.installer.quilt-api=QSL/QFAPI
install.installer.version=%s
install.modpack=安装整合包
install.new_game=安装新游戏版本
@@ -478,8 +499,7 @@ launch.advice.not_enough_space=您设置的内存大小过大,由于超过了
launch.advice.require_newer_java_version=Minecraft %1$s 仅能运行在 Java %2$s 或更高版本上,但 HMCL 未能找到该 Java 版本,你可以点击“是”,HMCL会自动下载他,是否下载?
launch.advice.too_large_memory_for_32bit=您设置的内存大小过大,由于可能超过了 32 位 Java 的内存分配限制,所以可能无法启动游戏,请将内存调至 1024MB 或更小。是否继续启动?
launch.advice.vanilla_linux_java_8=对于 Linux x86-64 平台,Minecraft 1.12.2 及以下版本仅支持 Java 8。\n请到 java.com 或其他途径下载 Java8!\n(可将 Java 路径选择至“自动选择合适的 Java”,启动时会自动下载该 Java)\nJava 9+ 版本会无法加载 32 位的 liblwjgl.so
launch.advice.vanilla_x86=Minecraft 官方尚未提供对非 x86-64 平台的支持。\n您可以尝试下载您所用平台对应的本机库,在游戏设置的调试选项中指定其路径后再尝试运行。
launch.advice.vanilla_x86.translation=你的电脑中没有安装 X64 架构的 Java 虚拟机(JDK),你可以在 <a href="https://docs.microsoft.com/java/openjdk/download"> 这里 </a> 下载 <b> X64 </b> 架构的 Java 虚拟机。\nMinecraft 尚未提供对 ARM 平台的支持,不能在您目前使用的 ARM64 架构 JDK 上运行。因此 HMCL 会借助 Rosetta 2 转译执行 X64 架构的 JDK 来启动 Minecraft。
launch.advice.vanilla_x86.translation=Minecraft 尚未为您的平台提供完善支持,所以可能影响游戏体验或无法启动游戏。\n你可以在 <a href="https://docs.microsoft.com/java/openjdk/download"> 这里 </a> 下载 <b> X86-64 </b> 架构的 Java 以获得更完整的体验。\n是否继续启动?
launch.failed=启动失败
launch.failed.cannot_create_jvm=截获到无法创建 Java 虚拟机,可能是 Java 参数有问题,可以在设置中开启无参数模式启动。
launch.failed.creating_process=启动失败,在创建新进程时发生错误,可能是 Java 路径错误……
@@ -491,7 +511,7 @@ launch.failed.execution_policy=设置执行策略
launch.failed.execution_policy.failed_to_set=设置执行策略失败
launch.failed.execution_policy.hint=当前执行策略阻止您执行 PowerShell 脚本。\n点击“确定”允许当前用户执行本地 PowerShell 脚本,或点击“取消”保持现状。
launch.failed.exited_abnormally=游戏非正常退出,请查看日志文件,或联系他人寻求帮助。
launch.failed.no_accepted_java=找不到适合当前游戏使用的 Java。如果您认为实际存在合适的 Java,您可以在游戏设置中手动设置 Java。
launch.failed.no_accepted_java=找不到适合当前游戏使用的 Java,是否使用默认 Java 启动游戏?点击“是”使用默认 Java 继续启动游戏,\n或者请到游戏设置中选择一个合适的 Java 虚拟机版本。
launch.state.dependencies=处理游戏依赖
launch.state.done=启动完成
launch.state.java=检测 Java 版本
@@ -504,7 +524,7 @@ launcher=启动器
launcher.agreement=用户协议与免责声明
launcher.agreement.accept=同意
launcher.agreement.decline=拒绝
launcher.agreement.hint=同意本软件的用户协议与免责声明以使用本软件!
launcher.agreement.hint=同意本软件的用户协议与免责声明以使用本软件。
launcher.background=背景地址
launcher.background.choose=选择背景路径
launcher.background.classic=经典
@@ -576,7 +596,7 @@ modpack.files.scripts=MineTweaker 配置
modpack.files.servers_dat=多人游戏服务器列表
modpack.install=安装 %s 整合包
modpack.installing=正在安装整合包
modpack.introduction=支持 Curse、MultiMC、HMCL 整合包。
modpack.introduction=支持 Curse、Modrinth、MultiMC、MCBBS 整合包。
modpack.invalid=无效的整合包升级文件,可能是下载时出现问题……
modpack.mismatched_type=整合包类型不匹配,当前游戏是 %s 整合包,但是提供的整合包更新文件是 %s 整合包。
modpack.name=整合包名称
@@ -587,11 +607,11 @@ modpack.origin.mcbbs=MCBBS
modpack.origin.mcbbs.prompt=贴子 id
modpack.scan=解析整合包
modpack.task.install=导入整合包
modpack.task.install.error=无法识别该整合包,目前仅支持导入 Curse、Modrinth、MultiMC、HMCL 整合包。
modpack.task.install.error=无法识别该整合包,目前仅支持导入 Curse、Modrinth、MultiMC、MCBBS 整合包。
modpack.task.install.will=将会安装整合包:
modpack.type.curse=Curse
modpack.type.curse.tolerable_error=但未能完成 Curse 整合包所需的依赖下载,您可以在启动该游戏版本时继续 Curse 整合包文件的下载。由于网络问题,您可能需要重试多次……
modpack.type.curse.error=未能完成 Curse 整合包所需的依赖下载,请多次重试或设置代理
modpack.type.curse.tolerable_error=但未能完成该整合包所需的依赖下载,您可以在启动该游戏版本时继续该整合包文件的下载。由于网络问题,您可能需要重试多次……
modpack.type.curse.error=未能完成该整合包所需的依赖下载,请多次重试或设置代理……
modpack.type.curse.not_found=部分必需文件已经在网络中被删除并且再也无法下载,请尝试该整合包的最新版本或者安装其他整合包。
modpack.type.manual.warning=您大概需要直接解压该整合包,并使用其自带的启动器即可开始游戏,而不需要导入整合包!该整合包不是由启动器导出的整合包,而是人工打包 .minecraft 文件夹而来的,这类整合包通常附带游戏启动器。HMCL 可以尝试导入该整合包,但不保证可用性,是否继续?
modpack.type.mcbbs=我的世界中文论坛整合包标准
@@ -602,7 +622,7 @@ modpack.type.multimc.export=可以被 Hello Minecraft! Launcher (HMCL) 和 Multi
modpack.type.server=服务器自动更新整合包
modpack.type.server.export=允许服务器管理员远程更新游戏客户端
modpack.type.server.malformed=服务器整合包配置格式错误,请联系服务器管理员解决此问题
modpack.unsupported=该整合包不被支持。仅 HMCL、MultiMC、Curse 整合包受支持!
modpack.unsupported=该整合包不被支持。仅 Curse、Modrinth、MultiMC、MCBBS 整合包受支持!
modpack.update=正在升级整合包
modpack.wizard=导出整合包向导
modpack.wizard.step.1=基本设置
@@ -619,17 +639,23 @@ modpack.wizard.step.initialization.warning=在制作整合包前,请您确认
modpack.wizard.step.initialization.server=点击此处查看有关服务器自动更新整合包的制作教程
modrinth.category.adventure=冒险
modrinth.category.challenging=高难度
modrinth.category.combat=战斗
modrinth.category.cursed=Cursed
modrinth.category.decoration=装饰
modrinth.category.equipment=装备
modrinth.category.fabric=Fabric
modrinth.category.food=食物
modrinth.category.forge=Forge
modrinth.category.kitchen-sink=大杂烩
modrinth.category.library=支持库
modrinth.category.lightweight=轻量
modrinth.category.magic=魔法
modrinth.category.misc=其他
modrinth.category.modloader=Modloader
modrinth.category.multiplayer=多人
modrinth.category.optimization=优化
modrinth.category.quests=任务
modrinth.category.quilt=Quilt
modrinth.category.rift=Rift
modrinth.category.storage=存储
@@ -668,87 +694,66 @@ mods.restore=回退
mods.url=官方页面
multiplayer=多人联机
multiplayer.agreement.prompt=使用多人联机功能前,你需要先同意多人联机服务提供方 ioi 系列作品的用户协议与免责声明。\n用户使用联机服务的行为,将被视为无条件同意该用户协议与免责声明。
multiplayer.download=正在下载依赖
multiplayer.download.failed=初始化失败,部分文件未能完成下载
multiplayer.download.success=多人联机初始化完成
multiplayer.download.unsupported=多人联机依赖不支持当前系统或平台
multiplayer.exit.after_ready=多人联机会话意外退出,退出码 %d
multiplayer.exit.before_ready=多人联机房间创建失败,cato 退出码 %d
multiplayer.exit.timeout.static_token=无法连接多人联机服务,你的凭证可能无法正常工作,你可以清空凭证再试。\n你可以联系在线管理员询问鉴权服务器是否正常工作,或者耐心等待十分钟。
multiplayer.exit.timeout.dynamic_token=无法连接多人联机服务,可能是鉴权服务器被人占满,请等待每个半点!鉴权服务器会自动刷新一次\n没有耐心且有闲钱的可以考虑购买联机凭证,不受鉴权服务器影响
multiplayer.hint=多人联机功能处于实验阶段,如果有问题请前往 mcer.cn 反馈
multiplayer.nat=网络检测
multiplayer.nat.failed=检测失败
multiplayer.nat.hint=执行网络检测可以让你更清楚你的网络状况是否符合联机功能的需求\n若检测结果为 差 或 检测失败 的网络可能导致联机失败!
multiplayer.nat.latency=延迟
multiplayer.nat.not_yet_tested=尚未检测
multiplayer.nat.packet_loss_ratio=丢包率
multiplayer.nat.testing=检测中
multiplayer.nat.type=NAT 类型
multiplayer.nat.type.blocked_udp=极差(网络禁止 UDP 协议)
multiplayer.nat.type.full_cone=好(完全圆锥型)
multiplayer.nat.type.open_access=好(公网开放型)
multiplayer.nat.type.port_restricted_cone=中(端口受限圆锥型)
multiplayer.nat.type.restricted_cone=中(受限圆锥型)
multiplayer.nat.type.symmetric=差(对称型)
multiplayer.nat.type.symmetric_udp_firewall=差(对称型+防火墙)
multiplayer.nat.type.unknown=未知
multiplayer.powered_by=多人联机服务由 (<a href="https://mcer.cn">mcer.cn</a>) 提供 <a href="https://hmcl.huangyuhui.net/api/redirect/multiplayer-agreement">用户协议与免责声明</a>
multiplayer.relay=桥接服务
multiplayer.relay.hint=Cato 面向较差网络提供的联机质量优化解决方案|无法联机时可在 mcer.cn 兑换凭证后启用
multiplayer.agreement.prompt=多人联机功能由 速聚 提供。使用前,你需要先同意多人联机服务提供方 速聚 的用户协议与免责声明。\n你需要了解,HMCL 仅为 速聚 提供多人联机服务入口,使用中遇到的任何问题由 速聚 负责处理。\n您在使用多人联机服务过程中所遇到的任何问题与纠纷(包括其付费业务)均与 HMCL 无关,请与 速聚 协商解决。
multiplayer.download=正在下载依赖……
multiplayer.download.failed=初始化失败,部分文件未能完成下载……
multiplayer.download.success=多人联机初始化完成√
multiplayer.download.unsupported=多人联机依赖不支持当前系统或平台!
multiplayer.error.failed_get_device=HiPer 无法创建网络设备,可能是 HiPer 正在运行中。请关闭正在运行中的其他启动器,或通过任务管理器终止 HiPer。
multiplayer.error.failed_load_config=HiPer 初始化失败,可能是联机索引码存在问题或索引码已过期,请检查索引码是否输入正确!你可向多人联机提供方联系寻求帮助。
multiplayer.error.failed_sudo.linux=HiPer 需要管理员权限才能运行,你可以通过设置环境变量 HMCL_ASKPASS 配置 HiPer 如何申请权限。\n若将 HMCL_ASKPASS 设置为 'false',请通过配置 sudoers 文件允许 '%s' 免密获取 root 权限,重启后再次启动 HMCL 即可;\n若将 HMCL_ASKPASS 设置为 'user',请先配置环境变量 SUDO_ASKPASS,HMCL 将使用 sudo --askpass 启动 HiPer (具体请参见 man sudo)。
multiplayer.error.failed_sudo.mac=HiPer 需要管理员权限才能运行。是否要授予 HiPer 管理员权限?\n点击“是”授予 HiPer 管理员权限,然后重启计算机后再次打开启动器即可联机。
multiplayer.error.failed_sudo.windows=HiPer 需要管理员权限才能运行,请使用管理员权限重新启动 HMCL。是否查看教程?
multiplayer.error.file_not_found=已发现 HiPer 有可用的更新,请重新进入多人联机页面以更新 HiPer。
multiplayer.error.session_expired=本次使用时间已结束,若要继续使用,请更换联机索引码
multiplayer.exit=HiPer 意外退出,退出码 %d
multiplayer.help.1=管理员权限打开
multiplayer.help.2=多人联机教程
multiplayer.help.3=创建方帮助
multiplayer.help.4=参与者帮助
multiplayer.help.text=测试能否联机
multiplayer.hint=多人联机服务正在维护中。
multiplayer.hint.details=查看详情
multiplayer.persistence=授权信息管理
multiplayer.persistence.export=将授权信息导出至文件
multiplayer.persistence.export.button=导出授权文件
multiplayer.persistence.export.failed=导出授权文件失败,请检查您所选择的保存路径。
multiplayer.persistence.export.file_not_exists=获取授权文件失败,请检查索引码是否输入正确。
multiplayer.persistence.export.title=选择授权文件保存路径
multiplayer.persistence.hint=此功能为长期授权 (有效期超过 24 小时) 用户提供,如果你正在使用短期授权 (有效期不超过 24 小时),则无需使用本功能。\n当你使用长期授权时,请在获取授权后的 24 小时内使用索引码启动 HiPer,否则 HiPer 将无法获取授权信息。\n随后,你可以通过下方的“导出授权信息”功能保存授权文件。\n请注意妥善保管授权文件,在获取授权 24 小时后,该文件是你的长期授权的唯一凭证,丢失该文件将无法通过索引码进行联机。
multiplayer.persistence.import=从文件导入授权信息
multiplayer.persistence.import.button=导入授权文件
multiplayer.persistence.import.failed=导入授权文件失败。
multiplayer.persistence.import.file_already_exists=授权文件已经存在。
multiplayer.persistence.import.title=选择授权文件
multiplayer.persistence.import.token_not_match=你选择的授权文件可能与索引码不匹配,是否继续导入?
multiplayer.persistence.license_file=授权文件
multiplayer.powered_by=HMCL 多人联机由 (<a href="https://mcer.cn">速聚</a>) 授权提供 <a href\="https://docs.hmcl.net/multiplayer/#%E4%BD%BF%E7%94%A8%E6%8E%88%E6%9D%83">授权协议</a>
multiplayer.report=违法违规举报
multiplayer.session=房间
multiplayer.session.name.format=%1$s 的房间
multiplayer.session.name.motd=HMCL 多人联机房间 - %s
multiplayer.session.close=关闭房间
multiplayer.session.close.warning=关闭房间后,已经加入联机房间的玩家将会断开连接,是否继续?
multiplayer.session.copy_room_code=拷贝邀请码
multiplayer.session.create=创建房间
multiplayer.session.create.error.dynamic_token=创建联机房间失败,可能是服务器出现问题,请稍后再试……
multiplayer.session.create.error.static_token=创建联机房间失败,你的凭证可能无法正常工作,你可以清空凭证再试……\n你可以联系在线管理员询问鉴权服务器是否正常工作,或者耐心等待十分钟。
multiplayer.session.create.hint=创建联机房间前,你需要先在正在运行的游戏内的游戏菜单中选择 对局域网开放 选项,然后在下方的输入框中确认游戏内提示的端口号(通常是 5 位的数字)
multiplayer.session.create.join=连接申请
multiplayer.session.create.join.allow=自动接受所有连接申请(不启用时,需要手动同意申请,以免无关人士误连服务器)
multiplayer.session.create.join.prompt=玩家 %s 申请加入多人联机房间,是否接受?
multiplayer.session.create.members=成员
multiplayer.session.create.members.kick=踢出房间
multiplayer.session.create.members.kick.prompt=是否踢出该玩家?踢出后该玩家不能再参与该联机房间。
multiplayer.session.create.name=房间名称
multiplayer.session.create.port=端口号
multiplayer.session.create.port.error=无法检测游戏端口号,你须启动游戏并在游戏内 打开对局域网 开放选项方能启动联机!
multiplayer.session.create.token=凭证
multiplayer.session.create.token.apply=申请凭证
multiplayer.session.create.token.prompt=默认为无凭证。你可以点击旁边的“申请凭证”获得详情
multiplayer.session.error.already_started=本地已经开启 cato 服务,请检查是否有其他 HMCL 正在运行联机服务。或者你可以在任务管理器里杀掉 cato 进程以继续。
multiplayer.session.error.file_not_found=找不到 cato 程序。该程序应该在进入多人联机页面时完成下载。请重启HMCL再试。\n请检查你电脑的杀毒软件是否将 cato 标记为病毒,如果是,请恢复 cato。
multiplayer.session.expired=联机会话连续使用时间超过了 3 小时,你需要重新创建/加入房间以继续联机!
multiplayer.session.join=加入房间
multiplayer.session.join.error=加入房间失败。若你或对方网络类型是 差(对称型)或 检测失败,可能无法使用联机功能,你可以使用凭证开启桥接模式后再试……
multiplayer.session.join.error.connection=加入房间失败。无法与对方建立连接。请检查你和对方的HMCL版本是否一致。\n如果你或对方的网络类型是差(对称型),可能无法使用联机功能。
multiplayer.session.join.hint=你需要向已经创建好房间的玩家索要邀请码以便加入多人联机房间
multiplayer.session.join.invitation_code=邀请码
multiplayer.session.join.invitation_code.error=邀请码格式不合法!请向房主获取邀请码,且检查你和对方使用的 HMCL 版本是否一致!
multiplayer.session.join.kicked=你与房间失去连接:%s。
multiplayer.session.join.kicked.join_acceptance_timeout=对方未能即时同意你的加入申请
multiplayer.session.join.kicked.kicked=你被房主踢出房间。
multiplayer.session.join.kicked.version_not_matched=多人联机功能版本号不一致,请保证连接多人联机功能版本号一致。
multiplayer.session.join.lost_connection=你已与房间失去连接。这可能意味着房主已经解散房间(非桥接服务的房间每个半点服务器自动刷新),或者你无法连接至房间……
multiplayer.session.join.port.error=无法找到可用的本地网络端口,请确保 HMCL 拥有绑定本地端口的权限!
multiplayer.session.join.rejected=你被房主拒绝连接,或房主忘记同意……
multiplayer.session.join.wait=等待对方同意加入申请……
multiplayer.session.members=房间成员
multiplayer.session.quit=退出房间
multiplayer.session.quit.warning=退出房间后,你将会与服务器断开连接,是否继续?
multiplayer.session.username=用户名
multiplayer.state.connecting=连接中
multiplayer.state.disconnected=未创建/加入房间
multiplayer.state.disconnected.hint=多人联机功能需要先有一位玩家创建房间后,其他玩家加入房间后继续游戏。
multiplayer.state.master=你已创建房间:%1$s,端口号 %2$d
multiplayer.state.master.hint=创建房间后,你可以点击拷贝邀请码,并发送给你希望加入联机的玩家。这些玩家在进入 HMCL 多人联机页面后,点击加入房间并粘贴邀请码即可加入联机房间。
multiplayer.state.slave=你已加入房间: %1$s,地址为 %2$s
multiplayer.state.slave.copy=拷贝地址
multiplayer.state.slave.hint=加入房间后,你需要在 Minecraft 的多人游戏页面选择 HMCL 多人联机房间服务器,或者手动添加下方的地址的服务器。
multiplayer.token=索引码
multiplayer.token.apply=获取联机索引码
multiplayer.token.expired=HiPer 证书过期,请更换联机索引码!
multiplayer.token.format_invalid=索引码格式不正确
multiplayer.token.invalid=索引码不正确。
multiplayer.token.malformed=HiPer 配置文件无法解析,可能是输入的联机索引码有误,或是获取证书服务器宕机。\n请检查输入的联机索引码!你可向多人联机提供方联系寻求帮助。
multiplayer.token.prompt=你需要联机索引码才能使用多人联机!点击“获取联机索引码”查看详情
multiplayer.off.hint=由于需要注册系统网络服务权限,启动 HiPer 时将会向用户申请管理员权限。若出现认证提示,允许以启动 HiPer。
multiplayer.off.start=启动 HiPer
multiplayer.master=创建方提示
multiplayer.master.hint=1.启动游戏\n2.选择单人游戏模式进入一个存档\n3.在游戏选项菜单内选择 对局域网开放 选项,之后你可以在游戏聊天框内看到游戏提示的端口号(通常是 4~5 位数字)\n4.点击下方的生成服务器地址按钮,输入端口号,你就可以获得你的服务器地址了\n5.该地址需要提供给其他需要加入服务器的玩家用于添加服务器。
multiplayer.master.server_address=生成服务器地址
multiplayer.master.server_address.copy=拷贝
multiplayer.master.video_tutorial=创建方视频教程
multiplayer.master.port=游戏局域网开放端口号
multiplayer.master.port.validate=在游戏聊天框中出现的端口号 (0~65535)
multiplayer.slave=参与者提示
multiplayer.slave.hint=1.要求创建方按照上方的 创建方提示 操作\n2.启动游戏\n3.选择多人游戏模式,选择添加服务器\n4.游戏会要求你输入服务器地址,你只需要向创建方索要服务器地址并输入,并进入服务器即可。
multiplayer.slave.hint2=1.一般情况下,参与者的游戏账户必须是 微软账户 或 外置登录账户(如 Little Skin),否则你需要将服务器地址输入至下方的输入框中并点击“加入”,在游戏中选择多人游戏模式,进入局域网世界方可加入,具体操作方法详见左侧的 帮助 \n2.一般情况下,参与者的游戏版本、模组要必须与创建方的一致,否则加入失败。
multiplayer.slave.server_address=创建方服务器地址
multiplayer.slave.server_address.start=加入
multiplayer.slave.server_address.stop=退出
multiplayer.slave.video_tutorial=参与者视频教程
multiplayer.session.expiration=索引码到期时间
datapack=数据包
datapack.add=添加数据包
@@ -772,6 +777,34 @@ world.import.already_exists=此世界已经存在
world.import.choose=选择要导入的存档压缩包
world.import.failed=无法导入此世界:%s
world.import.invalid=无法识别该存档压缩包
world.info.title=世界 %s - 世界信息
world.info.basic=基本信息
world.info.allow_cheats=允许作弊
world.info.dimension.the_nether=下界
world.info.dimension.the_end=末地
world.info.difficulty=难度
world.info.difficulty.peaceful=和平
world.info.difficulty.easy=简单
world.info.difficulty.normal=普通
world.info.difficulty.hard=困难
world.info.game_version=游戏版本
world.info.last_played=上一次游戏时间
world.info.generate_features=生成建筑
world.info.player=玩家信息
world.info.player.food_level=饥饿值
world.info.player.game_type=游戏模式
world.info.player.game_type.adventure=冒险
world.info.player.game_type.creative=创造
world.info.player.game_type.spectator=旁观
world.info.player.game_type.survival=生存
world.info.player.health=生命值
world.info.player.last_death_location=上次死亡位置
world.info.player.location=位置
world.info.player.spawn=床/重生锚位置
world.info.player.xp_level=经验等级
world.info.random_seed=种子
world.info.time=游戏内时间
world.info.time.format=%s 天
world.manage=世界/数据包
world.name=世界名称
world.name.enter=输入世界名称
@@ -825,13 +858,16 @@ settings.advanced.custom_commands.hint=自定义命令被调用时将包含如
\ - $INST_FABRIC: 若安装了 Fabric,将会存在本环境变量
settings.advanced.dont_check_game_completeness=不检查游戏完整性
settings.advanced.dont_check_jvm_validity=不检查 JVM 与游戏的兼容性
settings.advanced.dont_patch_natives=不尝试自动替换本地库
settings.advanced.game_dir.default=默认(.minecraft/)
settings.advanced.game_dir.independent=各版本独立(存放在 .minecraft/versions/<版本名>/,除 assets、libraries 外)
settings.advanced.java_permanent_generation_space=内存永久保存区域
settings.advanced.java_permanent_generation_space.prompt=单位 MB
settings.advanced.jvm=Java 虚拟机设置
settings.advanced.jvm_args=Java 虚拟机参数
settings.advanced.jvm_args.prompt=填写此处可以覆盖默认设置
settings.advanced.jvm_args.prompt=- 若在“Java 虚拟机参数”输入的参数与默认参数相同,则不会添加\n\
- 在“Java 虚拟机参数”输入任何 GC 参数,默认参数的 G1 参数会禁用\n\
- 点击下方“不添加默认的 JVM 参数”可在启动游戏时不添加默认参数
settings.advanced.launcher_visibility.close=游戏启动后结束启动器
settings.advanced.launcher_visibility.hide=游戏启动后隐藏启动器
settings.advanced.launcher_visibility.hide_and_reopen=隐藏启动器并在游戏结束后重新打开
@@ -859,6 +895,7 @@ settings.advanced.server_ip=服务器地址
settings.advanced.server_ip.prompt=默认,启动游戏后可以直接进入对应服务器
settings.advanced.use_native_glfw=[Linux] 使用系统 GLFW
settings.advanced.use_native_openal=[Linux] 使用系统 OpenAL
settings.advanced.use_software_renderer=使用 OpenGL 软渲染器(兼容性更好,但性能较差)
settings.advanced.workaround=调试选项
settings.advanced.workaround.warning=调试选项仅提供给专业玩家使用。调试选项可能会导致游戏无法启动。除非你知道你在做什么,否则请你不要修改这些选项!
settings.advanced.wrapper_launcher=包装命令
@@ -952,13 +989,13 @@ update.changelog=更新日志
update.channel.dev=测试版
update.channel.dev.hint=你正在使用测试版。测试版包含一些未在正式版中包含的测试性功能,仅用于体验新功能。\n\
测试版功能未受充分验证,使用起来可能不稳定!<a href="https://hmcl.huangyuhui.net/download">下载稳定版</a>\n\
如果你遇到了使用问题,可以在设置的 <a href="hmcl://settings/feedback">反馈页面</a> 中进行反馈,或加入反馈页面中提供的 <a href="https://discord.gg/jVvC7HfM6U">Discord</a> 或 <a href="https://kaihei.co/Kx7n3t">开黑啦</a>群以反馈问题。欢迎关注 B 站账号 <a href="https://space.bilibili.com/1445341">huanghongxun</a> 以关注 HMCL 的开发进展。\n\n\
如果你遇到了使用问题,可以在设置的 <a href="hmcl://settings/feedback">反馈页面</a> 中进行反馈,或加入反馈页面中提供的 <a href="https://discord.gg/jVvC7HfM6U">Discord</a> 或 <a href="https://kook.top/Kx7n3t">KOOK</a>群以反馈问题。欢迎关注 B 站账号 <a href="https://space.bilibili.com/1445341">huanghongxun</a> 以关注 HMCL 的开发进展。\n\n\
你需要 <a href="https://hmcl.huangyuhui.net/api/redirect/sponsor">赞助</a> 或在反馈过程中作出贡献以隐藏本提示。
update.channel.dev.title=测试版提示
update.channel.nightly=预览版
update.channel.nightly.hint=你正在使用预览版。预览版可能会每天更新一次,包含一些未在正式版和测试版中包含的测试性功能,仅用于体验新功能。\n\
测试版功能未受充分验证,使用起来可能不稳定!<a href="https://hmcl.huangyuhui.net/download">下载稳定版</a>\n\
如果你遇到了使用问题,可以在设置的 <a href="hmcl://settings/feedback">反馈页面</a> 中进行反馈,或加入反馈页面中提供的 <a href="https://discord.gg/jVvC7HfM6U">Discord</a> 或 <a href="https://kaihei.co/Kx7n3t">开黑啦</a>群以反馈问题。欢迎关注 B 站账号 <a href="https://space.bilibili.com/1445341">huanghongxun</a> 以关注 HMCL 的开发进展。\n\n\
如果你遇到了使用问题,可以在设置的 <a href="hmcl://settings/feedback">反馈页面</a> 中进行反馈,或加入反馈页面中提供的 <a href="https://discord.gg/jVvC7HfM6U">Discord</a> 或 <a href="https://kook.top/Kx7n3t">KOOK</a>群以反馈问题。欢迎关注 B 站账号 <a href="https://space.bilibili.com/1445341">huanghongxun</a> 以关注 HMCL 的开发进展。\n\n\
你需要 <a href="https://hmcl.huangyuhui.net/api/redirect/sponsor">赞助</a> 或在反馈过程中作出贡献以隐藏本提示。
update.channel.nightly.title=预览版提示
update.channel.stable=推荐版本
File diff suppressed because it is too large. Load diff
@@ -1,69 +0,0 @@
/*
* Hello Minecraft! Launcher
* Copyright (C) 2020 huangyuhui <huanghongxun2008@126.com> and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.jackhuang.hmcl.ui.multiplayer;
import org.junit.Ignore;
import org.junit.Test;
import java.io.IOException;
import java.net.*;
import java.nio.charset.StandardCharsets;
import static org.jackhuang.hmcl.util.i18n.I18n.i18n;
public class LocalServerBroadcastTest {
@Test
@Ignore("for manually testing")
public void test() {
int port = 12345;
DatagramSocket socket;
InetAddress broadcastAddress;
try {
socket = new DatagramSocket();
broadcastAddress = InetAddress.getByName("224.0.2.60");
} catch (IOException e) {
e.printStackTrace();
return;
}
while (true) {
try {
byte[] data = String.format("[MOTD]%s[/MOTD][AD]%d[/AD]", i18n("multiplayer.session.name.motd", "Test server"), port).getBytes(StandardCharsets.UTF_8);
DatagramPacket packet = new DatagramPacket(data, 0, data.length, broadcastAddress, 4445);
socket.send(packet);
System.out.println("Broadcast server 127.0.0.1:" + port);
} catch (IOException e) {
e.printStackTrace();
}
try {
Thread.sleep(1500);
} catch (InterruptedException ignored) {
return;
}
}
}
@Test
@Ignore
public void printLocalAddress() throws IOException {
DatagramSocket socket = new DatagramSocket(new InetSocketAddress((InetAddress) null, 4444));
System.out.println(socket.getLocalAddress());
}
}
@@ -1,49 +0,0 @@
/*
* Hello Minecraft! Launcher
* Copyright (C) 2021 huangyuhui <huanghongxun2008@126.com> and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.jackhuang.hmcl.ui.multiplayer;
import org.jackhuang.hmcl.util.Lang;
import org.jackhuang.hmcl.util.Logging;
import org.junit.Ignore;
import org.junit.Test;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
public class LocalServerDetectorTest {
@Test
@Ignore("for manually testing")
public void test() {
try {
for (NetworkInterface networkInterface : Lang.toIterable(NetworkInterface.getNetworkInterfaces())) {
System.out.println(networkInterface.getName());
for (InetAddress address : Lang.toIterable(networkInterface.getInetAddresses())) {
System.out.println(address);
}
}
} catch (SocketException e) {
e.printStackTrace();
}
Logging.initForTest();
LocalServerDetector detector = new LocalServerDetector(3);
detector.run();
}
}
@@ -1,55 +0,0 @@
/*
* Hello Minecraft! Launcher
* Copyright (C) 2021 huangyuhui <huanghongxun2008@126.com> and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.jackhuang.hmcl.ui.multiplayer;
import org.jackhuang.hmcl.util.Logging;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import java.util.concurrent.atomic.AtomicBoolean;
public class MultiplayerClientServerTest {
@Test
@Ignore
public void startServer() throws Exception {
Logging.initForTest();
int localPort = MultiplayerManager.findAvailablePort();
MultiplayerServer server = new MultiplayerServer("SessionName", 1000, true);
server.startServer(localPort);
MultiplayerClient client = new MultiplayerClient("username", localPort);
client.start();
AtomicBoolean handshakeReceived = new AtomicBoolean(false);
server.onHandshake().register(event -> {
handshakeReceived.set(true);
});
server.onKeepAlive().register(event -> {
client.interrupt();
server.interrupt();
});
server.join();
Assert.assertTrue(handshakeReceived.get());
}
}
@@ -64,7 +64,7 @@ public abstract class Account implements Observable {
* Play offline.
* @return the specific offline player's info.
*/
public abstract Optional<AuthInfo> playOffline() throws AuthenticationException;
public abstract AuthInfo playOffline() throws AuthenticationException;
public abstract Map<Object, Object> toStorage();
@@ -30,16 +30,21 @@ import java.util.UUID;
*/
@Immutable
public class AuthInfo implements AutoCloseable {
public static final String USER_TYPE_MOJANG = "mojang";
public static final String USER_TYPE_LEGACY = "legacy";
private final String username;
private final UUID uuid;
private final String accessToken;
private final String userType;
private final String userProperties;
public AuthInfo(String username, UUID uuid, String accessToken, String userProperties) {
public AuthInfo(String username, UUID uuid, String accessToken, String userType, String userProperties) {
this.username = username;
this.uuid = uuid;
this.accessToken = accessToken;
this.userType = userType;
this.userProperties = userProperties;
}
@@ -55,6 +60,10 @@ public class AuthInfo implements AutoCloseable {
return accessToken;
}
public String getUserType() {
return userType;
}
/**
* Properties of this user.
* Don't know the difference between user properties and user property map.
@@ -0,0 +1,21 @@
/*
* Hello Minecraft! Launcher
* Copyright (C) 2020 huangyuhui <huanghongxun2008@126.com> and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.jackhuang.hmcl.auth;
public class NotLoggedInException extends AuthenticationException {
}
@@ -89,6 +89,7 @@ public class OAuth {
pair("grant_type", "authorization_code"), pair("client_secret", options.callback.getClientSecret()),
pair("redirect_uri", session.getRedirectURI()), pair("scope", options.scope))
.ignoreHttpCode()
.retry(5)
.getJson(AuthorizationResponse.class);
handleErrorResponse(response);
return new Result(response.accessToken, response.refreshToken);
@@ -98,6 +99,7 @@ public class OAuth {
DeviceTokenResponse deviceTokenResponse = HttpRequest.POST(deviceCodeURL)
.form(pair("client_id", options.callback.getClientId()), pair("scope", options.scope))
.ignoreHttpCode()
.retry(5)
.getJson(DeviceTokenResponse.class);
handleErrorResponse(deviceTokenResponse);
@@ -124,6 +126,7 @@ public class OAuth {
pair("code", deviceTokenResponse.deviceCode),
pair("client_id", options.callback.getClientId()))
.ignoreHttpCode()
.retry(5)
.getJson(TokenResponse.class);
if ("authorization_pending".equals(tokenResponse.error)) {
@@ -158,6 +161,7 @@ public class OAuth {
.form(query)
.accept("application/json")
.ignoreHttpCode()
.retry(5)
.getJson(RefreshResponse.class);
handleErrorResponse(response);
@@ -177,7 +181,7 @@ public class OAuth {
switch (response.error) {
case "invalid_grant":
if (response.errorDescription.contains("The user must sign in again and if needed grant the client application access to the requested scope")) {
if (response.errorDescription.contains("AADSTS70000")) {
throw new CredentialExpiredException();
}
break;
Loaded 100 of 173 files, more files were not shown because too many files have changed in this diff. Show more