Compare commits

..

910 Commits

Author SHA1 Message Date
janrupf
8369dbdcc0 GH-2584, GH-1663 Limit icon size to 512x512 2019-06-22 01:29:25 +02:00
Petr Mrázek
ce12f1a734 Merge pull request #2694 from Janrupf/fix-disabled-mods
Operate on copy of QString instead of appending
2019-06-17 23:21:26 +02:00
janrupf
c1953739d9 NOISSUE Don't append .disabled to string 2019-06-17 15:49:26 +02:00
Petr Mrázek
e8bf9cef24 Merge branch 'develop' of https://github.com/lelandliu/MultiMC5 into develop 2019-06-15 22:47:36 +02:00
Petr Mrázek
8aa4b9dac5 NOISSUE limit fabric intermediary selection options in UI by minecraft version 2019-06-15 22:45:56 +02:00
Petr Mrázek
4836ba22cd NOISSUE fix fabric tooltip string 2019-06-15 22:29:34 +02:00
Petr Mrázek
6c30076b6c GH-2639 Add simple fabric loader installation support 2019-06-15 21:25:23 +02:00
Petr Mrázek
83c48a0f1a Merge pull request #2690 from asiekierka/fabric-modparse
Add Fabric mod JSON parsing support
2019-06-15 20:41:42 +02:00
asie
d251097545 fix author name parsing 2019-06-15 16:36:13 +02:00
asie
c35dbd972e Add Fabric mod JSON parsing support 2019-06-15 13:54:20 +02:00
Leland Liu
0c5d121452 Fixed adding a disabled duplicate 2019-06-14 15:48:24 -04:00
Petr Mrázek
53ad5cb436 Merge pull request #2684 from isoraqathedh/patch-1
Pass command line arguments through to the executable
2019-06-08 15:53:01 +02:00
isoraqathedh
d87bd4b588 Update run.sh
Pass command line arguments through to the executable
2019-06-08 21:21:22 +08:00
Petr Mrázek
86850ef5d0 NOISSUE fix macOS build, remove bundled dependencies on linux
Your copy of MultiMC might stop working after this update
because we no longer bundle Qt and other system libraries.

Contact us at https://discord.gg/0k2zsXGNHs0fE4Wm if
you need help with installing Qt.

Qt 5.4.x or newer is required.
2019-06-08 15:08:24 +02:00
Petr Mrázek
30fba4d407 NOISSUE make the global settings button context sensitive 2019-06-01 18:05:42 +02:00
Petr Mrázek
932160818e NOISSUE add option to open global settings from instance settings
This should hopefully giude people towards using the right thing.
2019-06-01 12:28:53 +02:00
Petr Mrázek
59e1ed3d87 NOISSUE add the pocket fox icon 2019-06-01 00:59:02 +02:00
Petr Mrázek
3470a3df96 NOISSUE improve icon handling while importing and exporting instances
Now it handles formats other than png.
2019-05-31 21:53:58 +02:00
Petr Mrázek
61913daaf3 Merge pull request #2603 from AlexTMjugador/develop
Support launching profiler in offline mode
2019-04-14 23:34:10 +02:00
Alejandro González
cb71dfa605 Tweak strings as per peterix review 2019-04-14 23:02:01 +02:00
AlexTMjugador
2be98baaba Conform to existing code style 2019-04-15 00:44:59 +02:00
AlexTMjugador
0ce637bf0e Support launching profiler in offline mode
This commit adds the necessary GUI controls to let the user choose
whether they want to launch Minecraft in offline mode with a configured profiler.
2019-04-15 00:42:06 +02:00
Petr Mrázek
70ed30f9e6 GH-2591 less std::shared_ptr and more shared_qobject_ptr
This eliminates some weird crashes.
2019-04-07 23:59:04 +02:00
Petr Mrázek
414946cad9 Merge remote-tracking branch 'origin/feature/trim_server_details' into develop 2019-04-02 23:39:13 +02:00
Elise
1fc199697c GH-2551 Trim at serialization 2019-03-29 11:25:37 -04:00
Petr Mrázek
9292d846b6 Merge pull request #2565 from MultiMC/feature/deletion_harder
GH-2487 Make deleting instances harder
2019-03-23 14:23:45 +01:00
Elise
22db95ce3b Merge branch 'develop' into feature/deletion_harder 2019-03-19 16:29:40 -04:00
Elise
597fe50d37 GH-2551 Trim server name and IP strings 2019-03-19 13:28:11 -04:00
Petr Mrázek
bf93ba02e9 NOISSUE fix metadata URL 2019-03-08 02:04:08 +01:00
Petr Mrázek
07c1685ff1 NOISSUE create translations folder before starting to watch it for changes
Fixes issue where on first run, the translations don't show up.
2019-03-08 01:21:04 +01:00
Elise
a5e531d4f1 GH-2487 Make NO the default button 2019-02-26 16:56:08 -05:00
Petr Mrázek
ae956d8fd6 NOISSUE update changelog 2019-02-21 00:45:36 +01:00
Petr Mrázek
73e487a31e NOISSUE hide the game options screen again 2019-02-21 00:44:36 +01:00
Petr Mrázek
0b95d2b03f NOISSUE fix build 2019-02-19 01:11:54 +01:00
Petr Mrázek
9c82adaee5 GH-2209 Fix sounds in old (pre-1.6) versions 2019-02-19 01:00:03 +01:00
Petr Mrázek
0a99d037c4 Merge pull request #2532 from andersmmg/patch-1
Update title of Add Empty dialog
2019-02-05 08:44:07 +01:00
Joshua Anderson
6e8e4c5dfa Update title of Add Empty dialog 2019-02-05 00:06:29 -07:00
Petr Mrázek
e4599ee2d1 NOISSUE fix builds? 2019-01-30 01:12:21 +01:00
Petr Mrázek
62c9fcdc6c NOISSUE first step towards having game options management 2019-01-30 00:35:24 +01:00
Petr Mrázek
c1ea42d3d9 Merge branch 'stable' of https://github.com/Scotsguy/MultiMC5 into develop 2019-01-17 00:51:54 +01:00
AppleTheGolden
437dec91f9 Update Copyright Year 2019-01-16 21:14:24 +01:00
Petr Mrázek
7436c94976 NOISSUE Replace Quality with Completeness in language widget
Completeness does no imply quality.
2019-01-14 01:36:04 +01:00
Petr Mrázek
c08053d8b8 NOISSUE split out language selection widget, use it in settings 2019-01-09 04:38:35 +01:00
Petr Mrázek
e71786d7b9 NOISSUE language selection wizard improvements
Same needs to be applied to the application settings later.
2019-01-08 02:20:36 +01:00
Petr Mrázek
819503d530 NOISSUE bump version to 0.6.5 2019-01-06 22:56:05 +01:00
Petr Mrázek
d6ace374d8 NOISSUE update changelog some more 2019-01-06 22:54:00 +01:00
Petr Mrázek
6a21c043ce NOISSUE bump version to 0.6.4 and update changelog 2019-01-06 22:28:27 +01:00
Petr Mrázek
4474d269cc NOISSUE granular model updates for language model 2019-01-06 22:14:13 +01:00
Petr Mrázek
ec2732ccd1 NOISSUE update FTB URLs 2019-01-04 01:48:36 +01:00
Petr Mrázek
4b7971f60f NOISSUE hotloading of translations and use of local PO files
The hotloading is still inefficient
2019-01-02 01:41:07 +01:00
Petr Mrázek
4cbd1a7692 Fix version number 2018-12-26 02:44:07 +01:00
Petr Mrázek
f481940aeb NOISSUE fix up changelog formatting 2018-12-26 01:56:25 +01:00
Petr Mrázek
037fb6fdb7 NOISSUE update the changelog 2018-12-26 01:54:37 +01:00
Petr Mrázek
3e60e770b5 NOISSUE just don't use std::abs, it doesn't work 2018-12-24 14:49:53 +01:00
Petr Mrázek
70052b180c NOISSUE maybe fix macos build, pngcrush images 2018-12-24 14:31:34 +01:00
Petr Mrázek
2e58429b6a NOISSUE kitty cat in a silly hat! 2018-12-24 03:26:14 +01:00
Petr Mrázek
56a9b65efb NOISSUE add missing Q_OBJECT macros 2018-12-23 01:05:11 +01:00
Petr Mrázek
4a4ba954ed GH-2488 fix Qt's relative URL redirect problems some more 2018-12-14 02:48:55 +01:00
Petr Mrázek
14bb666a20 GH-2485 fix crash bug while creating instances 2018-12-14 01:18:18 +01:00
Petr Mrázek
075e173fbd NOISSUE fix build 2018-12-12 00:05:53 +01:00
Petr Mrázek
3fe9165201 NOISSUE fix logging for gametype 2018-12-11 23:54:29 +01:00
Petr Mrázek
13b293dd65 GH-2374 fix missing alternating backgrounds in worlds, add gametype column 2018-12-11 23:53:14 +01:00
Petr Mrázek
de568b32b8 NOISSUE model Task states as one enum instead of multiple flags
This adds Task::State::AbortedByUser as a possibility
2018-12-10 20:50:15 +01:00
Petr Mrázek
fb29e45bd0 NOISSUE make instance creation task abortable
This may or may not expose issues when it actually IS used.
2018-12-10 20:49:21 +01:00
Petr Mrázek
3018310be3 NOISSUE fix typo 2018-12-06 00:36:31 +01:00
Petr Mrázek
f111d1bc0c GH-2483 fix minor issue while checking for missing local files 2018-12-06 00:33:49 +01:00
Petr Mrázek
0ee915200b GH-2478 fix jarmods being detected as missing 2018-11-26 09:57:51 +01:00
Petr Mrázek
9eb456336d NOISSUE fix unit tests 2018-11-26 03:22:20 +01:00
Petr Mrázek
3f6aecf5a2 GH-2475 fix reporting missing local libraries on launch 2018-11-26 03:06:58 +01:00
Petr Mrázek
e8c382bede GH-2101 select everything when editing instance names 2018-11-23 21:47:23 +01:00
Petr Mrázek
54e857a7f5 NOISSUE proper inline editable instance names
Pretty!
2018-11-23 04:56:56 +01:00
Petr Mrázek
74c598d756 GH-2101 fix enter and double click activation of instances 2018-11-22 02:02:53 +01:00
Petr Mrázek
c214c13fb3 GH-2101 POC for inline renaming 2018-11-22 01:50:32 +01:00
Petr Mrázek
c4a472981f GH-2467 remove unused sorting indicators from version page 2018-11-21 00:55:40 +01:00
Petr Mrázek
33a7cc1890 NOISSUE fix up mod installation and add a lot of logging for it 2018-11-21 00:29:41 +01:00
Petr Mrázek
a8e77f0ecc NOISSUE remove some nonsense and dead code 2018-11-15 00:36:47 +01:00
Petr Mrázek
5603133822 GH-2384 when adding mods with the same filename, rotate the files
Current will be disabled and renamed to '$name-old'.
Old one, if present, will be removed.
2018-11-12 02:39:52 +01:00
Petr Mrázek
47b1f9a860 NOISSUE fix up unit test for the changed Library behavior
No more fallback for local libraries. They must be in the instance, always.
2018-11-12 02:02:07 +01:00
Petr Mrázek
0f0dc30729 GH-2144 Fix translatable string 2018-11-12 01:57:26 +01:00
janrupf
1648b34aed GH-1552 Hide PermGen when using an autodetected java version greater than 8 2018-11-12 01:50:04 +01:00
janrupf
4cc7329ce3 GH-2144 Append '(installed)' to the installed version name 2018-11-12 01:49:52 +01:00
janrupf
16df8d7b88 GH-2384 Replace existing mod files 2018-11-12 01:49:35 +01:00
janrupf
3d630c7856 GH-2452 Ask before deleting group 2018-11-12 01:48:53 +01:00
janrupf
51a6883737 NOISSUE Ignore stuff from CLion 2018-11-12 01:48:38 +01:00
Petr Mrázek
d6367407b0 NOISSUE Rename OneSixUpdate to MinecraftUpdate 2018-11-11 23:55:50 +01:00
Petr Mrázek
defa911705 NOISSUE fix groups not being updated in UI correctly
The model was not sending the appropriate signals.
2018-11-11 23:54:16 +01:00
Petr Mrázek
17e09a292d NOISSUE read local libraries only from the local location
This removes the fallback to global `libraries` folder for `local` libraries.
2018-11-11 23:50:36 +01:00
Petr Mrázek
8a7f1e405f NOISSUE take forge xz download url base from the metadata file
Instead of hardcoding it.
2018-11-04 13:41:21 +01:00
Petr Mrázek
58260da861 NOISSUE remove use of obsolete URL constants, simplify the rest 2018-11-04 13:18:35 +01:00
Chris Lane
16cc20aefd NOISSUE fix 404 with liteloader https url 2018-11-02 12:59:37 +00:00
Chris Lane
0572a1e4e6 NOISSUE use https more widely 2018-11-02 12:04:08 +00:00
Petr Mrázek
9b74e73ad3 NOISSUE use https for downloading assets 2018-11-02 10:28:50 +01:00
Petr Mrázek
24fd2918c7 NOISSUE fix more rhel 7.6 problems? 2018-11-01 23:30:13 +01:00
Petr Mrázek
9eb165bfee iNOISSUE fix build issue with pack200 on rhel 7.6 2018-11-01 22:08:15 +01:00
Petr Mrázek
e4ce74e622 GH-2382 fix exact version filter not being exact... 2018-11-01 00:34:31 +01:00
Petr Mrázek
59e2f52db7 GH-2238 fix issues with whitespace/newlines in folder and instance names 2018-11-01 00:18:49 +01:00
Petr Mrázek
d5037d4f79 GH-2412: collect dead processes on linux properly
Issues were caused by use of `popen()` with no `pclose()` counterpart...
2018-10-31 22:44:23 +01:00
Petr Mrázek
aef0ccb1a2 GH-2232 add gif icon support (not animated) 2018-10-31 21:54:22 +01:00
Noah
d9c1fc09e7 add game and minecraft keywords 2018-10-31 20:40:19 +01:00
Noah
8b56d77f5e add minecraft keyword 2018-10-31 20:40:19 +01:00
Petr Mrázek
e3ab393cec NOISSUE make LaunchStep::bind private
Static analysis was complaining about it.
2018-10-31 00:04:21 +01:00
Petr Mrázek
2c03c67c36 NOISSUE stop mentioning the translations server in README 2018-09-10 03:37:35 +02:00
Petr Mrázek
a279df8bda NOISSUE fix build on linux? 2018-08-02 01:12:41 +02:00
Petr Mrázek
5f2d3f014a NOISSUE get rid of remaining tabs 2018-08-02 01:01:55 +02:00
Jannis Lübke
6aada8adf7 NOISSUE FTB pack code implementation, cleaned up 2018-08-02 00:52:31 +02:00
Petr Mrázek
6cee50eac6 NOISSUE gate new mods page behind cheat code 2018-08-01 20:05:18 +02:00
Petr Mrázek
9cc93ae81d NOISSUE fix crash bug caused by urge to maker code pretty
Also added a note so this doesn't happen again...
2018-07-31 02:20:04 +02:00
Petr Mrázek
0c73ddee73 NOISSUE set groups for instances by not setting groups for instances
So simple. Better in every way.
2018-07-31 01:54:08 +02:00
Petr Mrázek
9965decd81 NOISSUE squish. 2018-07-28 22:12:57 +02:00
Petr Mrázek
9e7cdbfe11 NOISSUE pretty multi-line formatting... 2018-07-28 22:12:57 +02:00
Petr Mrázek
76d6ec91a4 NOISSUE simplify. 2018-07-28 22:12:57 +02:00
Petr Mrázek
7b439c85c0 SCRATCH things and stuff, related to grou saving 2018-07-28 22:12:57 +02:00
Petr Mrázek
12f2716f31 GH-2355 Do not allow instances to be created with whitespace prefix or suffix 2018-07-28 22:08:09 +02:00
Petr Mrázek
4169f53b19 NOISSUE fix build on macOS? 2018-07-28 00:00:04 +02:00
Petr Mrázek
e4c33458f2 GH-2352 Add Minecraft folder button for instances, rearrange buttons by importance 2018-07-27 23:57:09 +02:00
Petr Mrázek
14f85813c8 NOISSUE hide the new mods page 2018-07-22 09:06:31 +02:00
Petr Mrázek
bbb3b3e6f6 NOISSUE tabs -> spaces 2018-07-15 14:51:05 +02:00
Petr Mrázek
03280cc62e NOISSUE separate new mods model from the simple one
It should list mods in various locations...
2018-07-15 14:04:09 +02:00
Petr Mrázek
128bce6acb SCRATCH second mods page, placeholder 2018-07-15 12:48:41 +02:00
Petr Mrázek
8108c61745 NOISSUE fix unitialized data warning on Arch Linux 2018-07-06 19:46:28 +02:00
Petr Mrázek
a222c94d34 NOISSUE add cancel button to the new instance dialog 2018-06-30 19:44:30 +02:00
Petr Mrázek
a872085f9a NOISSUE remove refresh button from servers page 2018-06-30 19:44:21 +02:00
Petr Mrázek
8516a6646e NOISSUE fix saving the servers.dat file when it doesn't exist yet 2018-06-30 01:27:44 +02:00
Petr Mrázek
44381c09d7 NOISSUE more warnings 2018-06-28 23:51:26 +02:00
Petr Mrázek
bb599abf59 NOISSUE fix a bug with mutexes on Windows, more warnings 2018-06-28 23:42:44 +02:00
Petr Mrázek
07f7ec8eef NOISSUE fix some warnings so builds can go further 2018-06-28 23:35:04 +02:00
Petr Mrázek
7fe94ca7b4 NOISSUE fix all sorts of warnings, enable Werror and pedantic 2018-06-28 23:18:45 +02:00
Petr Mrázek
b5f636b3d5 NOISSUE do not keep downloads in memory, add (some) missing virtual dtors 2018-06-28 21:34:56 +02:00
Petr Mrázek
19bb50b872 NOISSUE sync up quazip merge commit 2018-06-05 01:01:04 +02:00
Sergey Shatunov
4d68c1b509 GH-2291 Fix build with Qt 5.11+ 2018-06-02 17:22:43 +07:00
Petr Mrázek
f0ff2db4e1 GH-2277 fix even more exception catches by value 2018-05-20 01:53:05 +02:00
Charles Milette
72c0002b45 Catch C++ exceptions by const reference
Fixes #2277
2018-05-19 19:18:26 -04:00
Petr Mrázek
b9fd381eee GH-2268 update the deb package to not depend on latest jre
* `openjdk-8-jre` is now recommended
* the package now depends on `desktop-file-utils`
* the desktop icon has been updated to the current one
2018-05-17 23:14:12 +02:00
Petr Mrázek
584f1e89b9 GH-2252 make URL drop signal use a queued connection instead of direct call
Hopefully this will fix the issues with stuck applications on Windows.
2018-04-23 08:45:58 +02:00
Petr Mrázek
72ff342d63 GH-2053 basics of the servers.dat management 2018-04-23 02:05:22 +02:00
Petr Mrázek
6284f070c1 NOISSUE update changelog for 0.6.2 2018-04-08 23:43:03 +02:00
Petr Mrázek
be9063317e NOISSUE hide the twitch platform page 2018-04-08 21:22:41 +02:00
Petr Mrázek
8ec36e2cb9 NOISSUE bump release version to 0.6.2 2018-04-08 21:22:07 +02:00
Petr Mrázek
8cefc76108 NOISSUE show release dates of the meta versions in version picker views 2018-04-08 19:49:02 +02:00
Petr Mrázek
172f83c7e2 NOISSUE and even more bad includes 2018-04-07 22:45:03 +02:00
Petr Mrázek
b1e0cbf852 NOISSUE add more missing includes 2018-04-07 22:42:01 +02:00
Petr Mrázek
9b7f82ff26 NOISSUE fix build problem with missing <functional> include 2018-04-07 22:36:57 +02:00
Petr Mrázek
67cef79d81 NOISSUE add logging to zip subfolder extraction 2018-04-07 22:33:26 +02:00
Janrupf
7e1c5d439a #2228, #2229 - Auto import pack icons and fixed to big version selection - Closes #2228, Closes #2229 2018-04-07 22:09:19 +02:00
Janrupf
38ed0c2a1f NOISSUE Fixed ftb downloads always latest version 2018-04-07 00:46:49 +02:00
Lukas Haigner
9b7564e967 NOISSUE Fixed progress dialog 2018-04-07 00:46:49 +02:00
Petr Mrázek
15926b2b4a NOISSUE make FTB pack selection fancier 2018-04-06 21:59:04 +02:00
Petr Mrázek
6323aae56f NOISSUE move FtbListModel to where it is actually used 2018-04-06 21:04:34 +02:00
Petr Mrázek
c9c6037f50 NOISSUE fix Qt moc warning 2018-04-06 21:02:37 +02:00
Janrupf
97b74ef56a NOISSUE Fixed code for PR 2018-04-06 19:39:12 +02:00
Janrupf
df6e66101c NOISSUE Added 3rd party pack support 2018-04-05 19:33:31 +02:00
Janrupf
bbd523acb8 NOISSUE Added FTB Pack logos to chooser and fixed some missing includes 2018-04-02 23:02:33 +02:00
Janrupf
67d2f283da NOISSUE Fixed compilation error, but needs to be revisited 2018-04-02 23:02:33 +02:00
Petr Mrázek
4530d9064b NOISSUE fix latent bugs in RWStorage 2018-04-02 22:58:54 +02:00
Petr Mrázek
3406335cd8 GH-2219 fix crash and bad view scaling in Java VersionSelectDialog 2018-04-02 22:58:02 +02:00
Petr Mrázek
c9832d0d86 GH-2208 fix FTB pack download caching 2018-03-29 20:55:47 +02:00
Petr Mrázek
fa8f19b046 GH-2211 fix crash in first launch wizard 2018-03-29 20:41:16 +02:00
Petr Mrázek
370bbada87 NOISSUE polish the new instance UI a bit more 2018-03-28 21:57:41 +02:00
Petr Mrázek
1ef416cb56 NOISSUE add pointless fun things, because. 2018-03-28 00:51:24 +02:00
Petr Mrázek
b46a34d0ae NOISSUE make vanilla refresh button work 2018-03-27 23:19:29 +02:00
Petr Mrázek
6188c577e3 NOISSUE fix page container spacing in UIs 2018-03-27 22:21:41 +02:00
Petr Mrázek
40a30b67f4 NOISSUE save the new instance dialog geometry when the dialog is accepted 2018-03-27 22:02:57 +02:00
Petr Mrázek
12b304ea73 NOISSUE fix crash in NewInstanceDialog 2018-03-27 21:05:41 +02:00
Petr Mrázek
8e44ab2338 NOISSUE redo new instance dialog 2018-03-27 09:25:36 +02:00
Petr Mrázek
4c7ea0f99a NOISSUE explain the custom commands better 2018-03-26 22:08:55 +02:00
Petr Mrázek
a1c713811c NOISSUE preserve minecraft.jar while migrating Legacy instances
It can be manually modded. It must be preserved when it's the only jar around.
2018-03-23 23:39:18 +01:00
Petr Mrázek
106155dd62 NOISSUE move modpack platform related files to 'modplatform' subfolders 2018-03-16 23:33:58 +01:00
Petr Mrázek
303842a19e NOISSUE Add Konami Code
Fun little thing for hiding extra debug options in the future.
2018-03-15 09:27:45 +01:00
Petr Mrázek
ea151ca9d4 NOISSUE pre-fill analytics ID and paste.ee API key for all new builds
This means custom builds now get the option of using analytics and
log upload without users having to fill in IDs.
2018-03-13 08:02:11 +01:00
Petr Mrázek
6e69370fbf NOISSUE disable useless broken unit test to fix win32 and osx64 builds 2018-03-13 01:41:33 +01:00
Petr Mrázek
82208be49e NOISSUE add linux distro name and release stats to analytics
Hopefully this can serve as some sort of guideline for focusing
effort towards the right distro packages to make.
2018-03-13 00:28:51 +01:00
Petr Mrázek
b497aee920 NOISSUE update logo in README.md 2018-03-12 22:53:10 +01:00
Janrupf
0812e3a87b NOISSUE Fixed code for PR 2018-03-12 15:09:07 +01:00
Janrupf
b8ca36372b GH-2124 First complete implementation, installing is working now! GH-2172 Added sorting 2018-03-11 19:30:47 +01:00
Petr Mrázek
2d295d5afb Merge pull request #1911 from maxnordlund/patch-1
Mention casing in ISSUE_TEMPLATE
2018-03-01 17:25:09 +01:00
Janrupf
ab3fe74c97 Added FTB pack selection ad download, WIP 2018-02-28 19:43:56 +01:00
Petr Mrázek
1a43f28297 NOISSUE do not censor player name in logs 2018-02-18 19:27:01 +01:00
Petr Mrázek
093dd22826 GH-2154 Ignore 'hidden' flag of insttance folders 2018-02-18 16:08:11 +01:00
Petr Mrázek
06ccff0f47 GH-2150 Separate Java settings UI used in the wizard into a widget 2018-02-18 12:39:35 +01:00
Petr Mrázek
65bca65489 GH-2150 Split out custom commands into a custom widget
Now it is used from a global page and from a sub-page in the instance settings.
2018-02-17 00:57:54 +01:00
Petr Mrázek
a7957f24ba GH-2134 Totally overengineer skin upload input validation
* It autocorrects local paths and file:// URLs to valid local paths.
* It recognizes other URL schemes as 'remote' and will show an error for them.
* The error dialogs have been fixed (they all had titles and content swapped).
2018-02-15 00:40:23 +01:00
Petr Mrázek
2ea22d407d GH-604 use the same font for 'Other Logs' as for the main log
This doesn't mean coloring, just the same font and font size.
2018-02-14 21:37:32 +01:00
Petr Mrázek
22b32fce12 GH-2143 Switch Mojang status icons to current set of services
This also removes the Web and Account web icons, because they are simply
not relevant to MultiMC (it does not use those). You can always
check their status by opening them in a browser.
2018-02-13 21:35:05 +01:00
Petr Mrázek
2c219df061 NOISSUE clean up and fix win32 includes in FileSystem implementation 2018-02-11 01:29:43 +01:00
Petr Mrázek
604295e6d5 NOISSUE fix some warnings 2018-02-11 01:21:32 +01:00
Petr Mrázek
f259e9f727 NOISSUE update copyright dates 2018-02-11 00:40:01 +01:00
Petr Mrázek
38e669dbf5 NOISSUE change FS::updateTimestamp to work with directories too, use it to fix icon issues on macOS 2018-02-11 00:35:56 +01:00
Petr Mrázek
ca11765436 NOISSUE split logo into 'logo' and 'multimc' 2018-02-10 19:13:59 +01:00
Petr Mrázek
354ed2e7f0 NOISSUE version the discord variant of the icon 2018-02-10 16:13:05 +01:00
Petr Mrázek
a08afb8172 NOISSUE update the MultiMC logo 2018-02-10 16:09:14 +01:00
Petr Mrázek
2dac9d02d8 GH-2134 fix model selection when uploading a skin 2018-02-10 11:54:59 +01:00
Petr Mrázek
b3fb437f8e NOISSUE When changing version of or installing a package, remove customized version 2018-02-09 00:54:17 +01:00
Petr Mrázek
f115bdf5b8 NOISSUE make visualvm work with relative paths (inside the MultiMC folder) 2018-02-06 01:51:22 +01:00
Petr Mrázek
41aef8414a NOISSUE add an 'open folder' button to the icon dialog 2018-02-05 02:01:12 +01:00
Petr Mrázek
83649b5d52 NOISSUE implement basic search in Other Logs page 2018-02-05 01:40:38 +01:00
Petr Mrázek
595d157180 NOISSUE fix changelog typo 2018-01-30 00:20:27 +01:00
Petr Mrázek
3843a4ddb9 NOISSUE change version to 0.6.1 and update the changelog 2018-01-29 23:56:03 +01:00
Petr Mrázek
088e8e0eff NOISSUE remove unneeded URL fixing code and fix up the exception thrown by invalid Flame URLs 2018-01-29 00:47:18 +01:00
Petr Mrázek
418251bd86 NOISSUE use a variable for binary build definitions 2018-01-28 19:04:39 +01:00
Petr Mrázek
0bcb24502e GH-2119 Update group view scrollbar when the size of rows doesn't change
Previously, it would only update when you resize the window horizontally
enough to change the number of icons that fit in a row.
2018-01-28 02:04:47 +01:00
Petr Mrázek
3277b820a7 NOISSUE fix the macOS bundle utilities problem 2018-01-27 23:53:10 +01:00
Petr Mrázek
d66ae206dd NOISSUE move bundle utilities magic back to the application folder
This may fix macOS issues?
2018-01-27 21:59:06 +01:00
Petr Mrázek
cd55674b36 NOISSUE do not install .a files for shared libraries on Windows 2018-01-27 02:42:27 +01:00
Petr Mrázek
166e5a03d6 NOISSUE rearrange build system
* Added install commands to the libraries instead of force installing files
* Most of the application cmake stuff moved to top level
* RPATH should now be set/cleared correctly
* Contains a fix for GH-1780
2018-01-27 02:00:20 +01:00
Petr Mrázek
0c2e2094ee NOISSUE clean up download redirects and handle their errors as fatal 2018-01-22 03:09:00 +01:00
Petr Mrázek
c33b4e252f NOISSUE fix bad redirect URLs provided by the curse CDN
MultiMC now parses the HTTP Location header in a (more) tolerant mode.
2018-01-21 03:49:54 +01:00
Samuel Rakitničan
0942867ecc GH-2103 Make /usr/local the default prefix for lin-system
/usr/local is a sane default since /usr is meant to be used by packages.
2018-01-18 12:09:03 +01:00
Petr Mrázek
e8336babad NOISSUE fix the installation prefix mess 2018-01-16 07:08:59 +01:00
Petr Mrázek
d0e58acd84 GH-2103 add suggested changes from the pull request 2018-01-16 06:48:10 +01:00
Carl Philipp Reh
360d877abf GH-2103 Take CMAKE_INSTALL_PREFIX into account in MULTIMC_JARS_LOCATION
When installing MultiMC with the lin-system layout and specifying an
install prefix that is not the empty string, then MultiMC looks for its
Jars in the wrong location. Fix this by appending CMAKE_INSTALL_PREFIX.
2018-01-16 06:47:58 +01:00
srakitnican
7ea1d68244 GH-2102 multimc.desktop: Remove deprecated entries 2018-01-14 08:23:17 +01:00
Petr Mrázek
b7f28a92d4 NOISSUE change default install layout on linux to lin-nodeps
This avoids issues with included bundle utilities on certain systems
and is a step in the intended direction (not distributing dependencies).
2018-01-08 01:42:50 +01:00
Petr Mrázek
1dbc4e16f7 NOISSUE remove the jar-modded jar after the instance finishes 2018-01-08 00:59:47 +01:00
Petr Mrázek
0636c03d7c GH-2087 remove the revert to vanilla functionality, add file download button to version page 2018-01-05 04:26:46 +01:00
Petr Mrázek
ee341b78ba GH-2089 update wording of the instance delete confirmation dialog 2018-01-04 04:16:31 +01:00
Petr Mrázek
9510a1bbf2 NOISSUE stop logging process environment and MC launch script 2018-01-04 03:50:05 +01:00
Petr Mrázek
03a93b8e4a NOISSUE Add mention of Nikki's and Dries007's work on CurseMeta 2018-01-03 02:04:23 +01:00
Petr Mrázek
b08ec1e97a NOISSUE fix changelog typos 2017-12-31 19:39:46 +01:00
Petr Mrázek
d7ed472e68 NOISSUE update changelog for 0.6.0 2017-12-31 07:21:14 +01:00
Petr Mrázek
7cd13302c5 NOISSUE only show pack import warnings when there are some 2017-12-31 07:20:28 +01:00
Petr Mrázek
4340068a84 NOISSUE add button for creating empty, properly registered, components 2017-12-31 01:37:50 +01:00
Petr Mrázek
c7032ce68a NOISSUE add missing QStringList include 2017-12-30 19:02:09 +01:00
Petr Mrázek
58ead6a1f4 NOISSUE handle 'folder' Flame packages by ignoring them, show warnings for minor Flame import problems 2017-12-30 18:57:46 +01:00
Petr Mrázek
5937b1c3d4 NOISSUE make the patreon button text slightly shorter
"Support MultiMC" instead of "Support us on Patreon!"
2017-12-30 05:18:09 +01:00
Petr Mrázek
6c30c84b11 NOISSUE switch MultiMC to the v1 meta endpoint 2017-12-29 03:32:22 +01:00
Petr Mrázek
75c0046f41 NOISSUE initial meta version will be 1, map 0 to 1
Metadata for version 1 will be at v1.meta.multimc.org
2017-12-29 01:51:00 +01:00
Petr Mrázek
719f3e863a NOISSUE add versioning to component metadata format and use it 2017-12-29 00:37:14 +01:00
Petr Mrázek
50ca6cbb4d NOISSUE fix crash bug in version page of instances
This was caused by generation of temporary component objects
when no such thing should have been happening.
2017-12-29 00:35:10 +01:00
Petr Mrázek
257f8ca9fd NOISSUE fix typo when deleting log files
"Do you really want to these files?" was missing "delete".
2017-12-25 13:06:38 +01:00
Petr Mrázek
642c3f1d09 NOISSUE sort export dialog contents in ascending order by default 2017-12-21 01:25:43 +01:00
Petr Mrázek
c2726037ce NOISSUE add missing world and help icons 2017-12-19 01:49:46 +01:00
Petr Mrázek
9eb0525dab NOISSUE preserve log page checkbox state when the instance window is closed
Only for a single session, not between sessions.
2017-12-18 01:19:43 +01:00
Petr Mrázek
fb7897a6f4 NOISSUE remopve instance settings button from the main window
This should steer new users to the main settings even more, while keeping
the instance settings still available.
2017-12-17 22:17:29 +01:00
Petr Mrázek
5858483592 NOISSUE ignore merge commits in dev build changelog 2017-12-17 21:08:20 +01:00
Petr Mrázek
6fd91be137 NOISSUE Revert "Removed workflowy link and info because no one uses it"
This reverts commit 16e390d2e7.
2017-12-17 21:07:34 +01:00
ask6155
245a19e9df Merge pull request #2069 from ask6155/develop
Removed workflowy link and info because no one uses it
2017-12-15 17:20:05 +05:30
ask6155
16e390d2e7 Removed workflowy link and info because no one uses it 2017-12-14 20:40:02 +05:30
Petr Mrázek
daf9d0eaa7 NOISSUE do not override already loaded metadata entities with partial data 2017-12-14 02:22:20 +01:00
Petr Mrázek
f18afd3d1e NOISSUE fix a bunch of warnings thrown by Qt internals
Badly connected signals/slots and similar things.
2017-12-14 00:29:00 +01:00
Petr Mrázek
ef2cbe16e6 NOISSUE when there is a version added already, preselect it in the version select dialog 2017-12-09 01:30:23 +01:00
Petr Mrázek
57accb1cbb NOISSUE Reorder and reword main toolbar actions to save space
```
Folder, Help, Check for Updates, Settings
  -> Folders, Settings, Help, Update
```
2017-12-06 02:01:42 +01:00
Petr Mrázek
6d034bda82 GH-2059 fix instance directory not being created on first launch 2017-12-05 09:52:04 +01:00
Petr Mrázek
44475350eb NOISSUE placeholder for proper 'change version' functionality
When using this on forge or liteloader, it now uses the 'install'
dialogs instead.
This will have to be done properly using the component version metadata
later.
2017-12-05 00:40:45 +01:00
Petr Mrázek
df1ec1f7c2 GH-2057 remove bundled libz 2017-12-04 21:26:49 +01:00
Petr Mrázek
00814830c4 NOISSUE bundle libproxy and libz on linux
This is an experiment...
2017-12-04 02:55:28 +01:00
Petr Mrázek
c2766e5c6e NOISSUE add the material icons license 2017-12-03 22:36:46 +01:00
Petr Mrázek
90a3997d2c NOISSUE add flat icon theme by Michael
It's the google icon font, all scalable and grey.
2017-12-03 21:52:40 +01:00
Petr Mrázek
d6fc37e486 NOISSUE make MultiMC respond to account manipulation better
* Setting and resetting default account will update the account list properly
* Removing the active account will now also reset it (previously, it would 'stay around')
* The accounts model is no longer reset by every action
2017-12-03 20:54:28 +01:00
Petr Mrázek
8eb1397a8a NOISSUE fix wrong look of checkboxes in the account list 2017-12-03 19:34:54 +01:00
Petr Mrázek
4bae6fe491 GH-2050 fix cancel button in file browse dialogs filling text fields 2017-12-03 19:21:04 +01:00
Petr Mrázek
95e6f37d39 NOISSUE force saving of any outstanding instance component state on exit 2017-12-03 18:36:28 +01:00
Petr Mrázek
e0bea1e46a NOISSUE watch added Component for changes in order to trigger ComponentList saves 2017-12-03 15:57:21 +01:00
Petr Mrázek
6a462d0778 GH-1082 allow disabling components
Currently only ones that are removable and aren't dep-only
2017-12-03 15:48:25 +01:00
Petr Mrázek
0a56b56286 NOISSUE in offline mode, do not contact the auth server if there is a valid account already 2017-12-03 14:05:35 +01:00
Petr Mrázek
30fad998a6 NOISSUE normalize instances path in FolderInstanceProvider
This resolves some issues with the instance export dialog when the instances folder
path contains '..' and '.', or involves symlinks.
2017-12-03 02:38:53 +01:00
Petr Mrázek
34de313feb NOISSUE disable the unfinished 'Packages' page in settings 2017-12-03 02:01:43 +01:00
Petr Mrázek
85ae710d40 GH-2026 implement changes necessary to support 1.13 snapshots 2017-12-03 01:22:34 +01:00
Petr Mrázek
17c8f31a09 NOISSUE split out the LaunchProfile out of the ComponentList 2017-11-17 15:44:13 +01:00
MinecraftZuriki
3470158943 Support for classic multiplayer via mpticket 2017-11-18 01:27:57 +11:00
Petr Mrázek
b000b33661 NOISSUE fix display of svg icons in instance toolbar 2017-11-14 01:03:32 +01:00
Petr Mrázek
322922e013 NOISSUE add svg instance icon support 2017-11-14 00:16:04 +01:00
Petr Mrázek
fede712a26 NOISSUE rename MinecraftProfile to ComponentList
It is realistically a list of components. The fact that it also holds the final
launch parameters is a design bug.
2017-11-04 15:23:49 +01:00
Petr Mrázek
87edaa7dcd NOISSUE and one more build for the build gods... ssl error catching again. 2017-11-01 23:21:00 +01:00
Petr Mrázek
e5da2e36c7 NOISSUE actually do catch the ssl errors 2017-11-01 23:04:49 +01:00
Petr Mrázek
e44a0cb944 NOISSUE catch and log SSL errors for Download(s) 2017-11-01 22:52:11 +01:00
Petr Mrázek
e6d734d9ac NOISSUE fix build some more 2017-10-29 12:28:26 +01:00
Petr Mrázek
1489720b90 NOISSUE fix build 2017-10-29 12:27:12 +01:00
Petr Mrázek
b76bdf9368 GH-2026 avoid using awt Dimension class to fix input issues on macOS 2017-10-29 12:24:49 +01:00
Petr Mrázek
7add9de1cf GH-2026 remove some macOS stuff from launcher part to fix input issues on 1.13 2017-10-29 10:02:01 +01:00
Petr Mrázek
a6a642eb7e GH-2026 only run versions with FirstThreadOnMacOS trait on first thread 2017-10-29 09:15:10 +01:00
Petr Mrázek
c78498f40c GH-2026 actually do the previous on macOS, not Windows 2017-10-28 23:29:18 +02:00
Petr Mrázek
4b80d34be4 GH-2026 start Minecraft on first thread on macOS
This should fix issues with the 1.13 snapshots
2017-10-28 22:56:18 +02:00
Petr Mrázek
d4b82f11ca GH-2026 fix failing library test case for native libraries 2017-10-28 22:21:49 +02:00
Petr Mrázek
a87d96349a NOISSUE show hidden files in instance export dialog (like .minecraft) 2017-10-28 21:44:29 +02:00
Petr Mrázek
3eebc641f9 GH-2026 fix native library downloads
If a single library had both native and java jars, they would randomly get confused.
2017-10-28 21:12:12 +02:00
Petr Mrázek
ab870648bd NOISSUE remove debug dump to file in paste upload 2017-10-11 09:13:26 +02:00
Petr Mrázek
1388751fd4 NOISSUE clean up and fix paste.ee upload 2017-10-11 08:55:42 +02:00
Petr Mrázek
eba8e61ce9 NOISSUE change behaviour of the +tweakers patch item
Patch application will either add tweakers, or move them
to the end if they are already present.

This allows fixing up tweaker order in subsequent version patches.
2017-10-08 02:02:52 +02:00
Petr Mrázek
b88206907e NOISSUE code comments 2017-10-08 02:02:34 +02:00
Petr Mrázek
4b90a078de NOISSUE add tooltips to new menu buttons and make them translateable 2017-10-04 02:35:28 +02:00
Petr Mrázek
d8c8a41dfa NOISSUE rearrange main toolbar for clarity
It is now set to text beside icons and many actions were moved to sub-menus.
2017-10-02 02:30:14 +02:00
Petr Mrázek
e2a4fbc589 NOISSUE disable the refresh action on the main toolbar 2017-10-02 01:34:01 +02:00
Petr Mrázek
edfca7da66 NOISSUE remove bogus duplicated toolbars 2017-10-02 01:33:30 +02:00
Petr Mrázek
a1d501d394 NOISSUE refactor the MainWindow UI creation
It was ugly generated code with no rhyme or reason to it.
Now all the relevant code is grouped and language switching works a little better.
2017-10-02 00:55:34 +02:00
Petr Mrázek
ea71281629 NOISSUE fix aspect ratio issues with the instance icon in the instance toolbar 2017-09-28 02:47:54 +02:00
Petr Mrázek
c51512f940 NOISSUE use classparser for importing Legacy instances with undecided Minecraft versions 2017-09-27 15:39:13 +02:00
Petr Mrázek
9a2d203c0d GH-1993 swap min/max memory settings when they are the wrong way around 2017-09-27 12:45:07 +02:00
Petr Mrázek
79d208795c GH-1997 fix off by one error in 8.3 path logic 2017-09-27 04:28:21 +02:00
Petr Mrázek
d276da1359 GH-1997 try to fix Windows build
Coding blind. Much !!FUN!!.
2017-09-27 04:10:09 +02:00
Petr Mrázek
464bc0f770 GH-1997 replace use of weird hacks with normal java arguments
This affects classpath and java.library.path.

The catch is that if the strings cannot be expressed in system codepage
on Windows, it tries to use 8.3 paths.
2017-09-27 04:04:19 +02:00
Petr Mrázek
0595a00090 NOISSUE discourage using java > 8 by sorting it below everything else 2017-09-26 19:16:46 +02:00
Petr Mrázek
1a38587877 NOISSUE Legacy migration success now closes the instance window 2017-09-26 19:04:37 +02:00
Petr Mrázek
719f112f64 NOISSUE add #testing discord channel link to Legacy instance migration page 2017-09-26 14:35:26 +02:00
Petr Mrázek
2b998bb8cc NOISSUE implement LEgacy instance migration 2017-09-26 13:38:34 +02:00
Petr Mrázek
eac892965e NOISSUE make sure MultiMC and Flame import is mutually exclusive 2017-09-26 01:39:39 +02:00
Petr Mrázek
678c7ab271 NOISSUE remove Flame manifest on import
This prevents treating the instance as a Flame pack later.
2017-09-26 01:37:50 +02:00
Petr Mrázek
f26ca143c4 NOISSUE do not fail when the Flame overrides folder is missing 2017-09-26 01:36:52 +02:00
Petr Mrázek
a269e0c92f NOISSUE force travis.ci to use precise, fix ppa for Qt 2017-09-25 12:14:28 +02:00
Petr Mrázek
f8c5cee982 NOISSUE ignore the 'Example Mod' mod name, use filename instead 2017-09-25 08:18:42 +02:00
Petr Mrázek
c82042dcfa GH-2000 translate 'required' from Flame pack manifests to '.disabled' 2017-09-25 08:06:23 +02:00
Petr Mrázek
b5b16d0972 NOISSUE make instance traits() const 2017-09-22 00:27:30 +02:00
Petr Mrázek
76c7e0fe1c NOISSUE remove some dead code from MinecraftInstance (moved elsewhere) 2017-09-22 00:13:07 +02:00
Petr Mrázek
fce2b0ce5f NOISSUE make the paste.ee links in settings clickable 2017-09-22 00:04:33 +02:00
Petr Mrázek
e9434fce3d NOISSUE prefer to use '.minecraft' instead of 'minecraft' folder 2017-09-20 23:58:39 +02:00
Petr Mrázek
c707042dd7 NOISSUE set haspaid parameter to true when launching old versions 2017-09-20 23:57:20 +02:00
Petr Mrázek
102804ef82 NOISSUE remove obsolete LWJGL folder setting 2017-09-20 23:43:55 +02:00
Petr Mrázek
ba3cbb7330 NOISSUE more work on Legacy migration 2017-09-20 23:38:31 +02:00
Petr Mrázek
9a6c2b0e2c NOISSUE Add back Legacy for migration purposes 2017-09-17 19:24:39 +02:00
Petr Mrázek
b2b0487600 NOISSUE clean up moc warnings 2017-09-10 13:25:32 +02:00
Petr Mrázek
9491396292 NOISSUE put back missing OneSix upgrade logic 2017-09-10 12:41:32 +02:00
Petr Mrázek
13628e7a82 NOISSUE merging of strategy into profile, onesix into minecraft 2017-09-09 19:19:05 +02:00
Petr Mrázek
b29382c748 NOISSUE Remove Legacy support 2017-09-09 18:30:22 +02:00
Petr Mrázek
4c01983f47 NOISSUE remove FTB integration 2017-09-09 18:29:52 +02:00
Petr Mrázek
3fb4ce713f NOISSUE add support for Flame packs with resource packs
And a bunch of undefined things we don't handle intentionally just yet...
2017-09-08 09:02:27 +02:00
Petr Mrázek
32a2cb5a0d NOISSUE fix hardcoded link color in other places 2017-09-07 01:20:11 +02:00
Petr Mrázek
a1ef043030 NOISSUE fix hardcoded link color in about dialog
Should respect theme colors now.
2017-09-07 00:53:09 +02:00
Petr Mrázek
b61407a75d NOISSUE retry committing instances if it fails a few times
This should fix issues with antivirus locking files/folders on Windows.
2017-09-05 23:38:17 +02:00
Petr Mrázek
d80382180e NOISSUE refactor pack import (extraction and paths)
It now:
* Doesn't extract until it knows the content format is good.
* Extracts in a predictable location, not requiring to use a second path for the actual pack root.
2017-09-04 08:17:25 +02:00
Petr Mrázek
b8adbb9b73 GH-1971 do not check filesystem boundaries when committing instances
The check wasn't very good and was breaking because it assumed uniform paths.
2017-09-02 13:58:57 +02:00
Petr Mrázek
6381bfdb88 NOISSUE handle error 201 in Auth code
This is something I ran into when one of my accounts stopped working.
The auth token probably expired.

This should now be handled as a normal auth error, not a network failure.
2017-09-02 13:37:12 +02:00
Petr Mrázek
3ed990861a NOISSUE simplify ProblemProvider 2017-08-28 22:09:53 +02:00
flcmc
2c1ca040f8 NOISSUE Update Instance-Version Help Page 2017-08-27 19:15:51 +02:00
Petr Mrázek
300aa9e6d6 NOISSUE update te logo in the README 2017-08-27 12:56:21 +02:00
Petr Mrázek
8227725adb NOISSUE update README to reference workflowy and discord 2017-08-27 11:41:02 +02:00
Petr Mrázek
53bf21ddcd NOISSUE select whole items in screenshot list
Items = rows. It should work properly now.
2017-08-26 21:08:43 +02:00
Joona
59b681a174 NOISSUE implement more error handling 2017-08-22 18:35:10 -07:00
Joona
6e25624623 NOISSUE remove debug statement 2017-08-22 18:12:23 -07:00
Joona
60d10201e9 NOISSUE Add GPU vendor and driver version 2017-08-22 18:02:03 -07:00
Joona
0cd55d943e CPU and GPU model on Linux 2017-08-22 17:47:06 -07:00
Joona
48274e889f move env cleaning and clean before java test 2017-08-22 15:23:35 -07:00
Joona
9d3a847555 forgot to remove debug statement 2017-08-22 22:38:01 +02:00
Joona
ced67a7400 remove public option 2017-08-22 22:38:01 +02:00
Joona
4d54d2662a switch to new paste.ee API 2017-08-22 22:38:01 +02:00
Petr Mrázek
140c31293c NOISSUE use rows when uploading screenshots
Using all indexes was quadrupling the uploaded items.
2017-08-19 23:14:06 +02:00
Petr Mrázek
8cf88ffc58 GH-1314 add UI for custom minecraft jar addition
Also changes the text of the jar mod addition button.
It should be clearer what it does and hopefully will not confuse
as many people.
2017-08-07 00:46:29 +02:00
Petr Mrázek
117bfef151 NOISSUE add JDK build dependency on Windows into BUILD.md 2017-07-29 16:22:53 +02:00
Petr Mrázek
632f232e36 NOISSUE update build instructions
It needs more. It needs a cleanup. And it needs someone to go and actually test that it works.
2017-07-29 16:06:38 +02:00
Petr Mrázek
bea1b5de5e GH-1929 do not allow non-current update task to affect the update process
Errors are handled by setting a flag and failing on the next call to next()
2017-07-21 08:49:58 +02:00
Petr Mrázek
c19f6d4dcd NOISSUE allow running legacy without the applet wrapper
Add 'noapplet' as a trait to do that.
2017-07-14 08:43:35 +02:00
Petr Mrázek
afb0db24a8 NOISSUE set max of java heap spinboxes to detected physical memory 2017-07-11 22:43:35 +02:00
Petr Mrázek
5ea170db78 GH-1927 fix potential issue with FMLLibrariesTask succeeding twice. 2017-07-07 19:50:24 +02:00
Petr Mrázek
e5b4b5d295 GH-1927 Add more specific task status logging
* Tasks are now described by class name and object name (or memory address).
* Tasks starts are logged.
* Aborted tasks are now treated just as the other cases.
2017-07-07 19:46:56 +02:00
Petr Mrázek
fbeceaa98c NOISSUE remove verbose dl progress logging 2017-07-07 18:16:09 +02:00
Petr Mrázek
50697735b5 NOISSUE fix jvisualvm website links 2017-07-07 01:28:58 +02:00
Petr Mrázek
1797f45e8f NOISSUE fix jumpy download progress bars
They are not as precise, the new logic gives every
download 1000 'units' instead of the actual (initially unknown) sizes.
2017-07-06 15:38:16 +02:00
Petr Mrázek
8dd9987a9c NOISSUE remove obsolete declaration for logger shutdown 2017-07-06 15:38:01 +02:00
Petr Mrázek
259021bc98 NOISSUE fix startup issues caused by code reorganization 2017-07-06 01:59:31 +02:00
Petr Mrázek
26f7f017d4 NOISSUE attept to detach from console on Windows
This only applies to MultiMC started from a console.
2017-07-05 19:45:10 +02:00
Petr Mrázek
71b129538b NOISSUE add disgnostic print to MultiMC destructor 2017-07-05 19:09:14 +02:00
Petr Mrázek
d6ab4b4a7f NOISSUE rearrange global initialization 2017-07-05 18:02:49 +02:00
Petr Mrázek
74c455ff35 NOISSUE add note to Job_Failed_Proceed
It should be removed, it just signifies that there is a system missing.
2017-06-27 08:20:12 +02:00
Petr Mrázek
36f3e24cf3 NOISSUE remove some bad code in various Task related classes 2017-06-27 04:32:53 +02:00
Petr Mrázek
89d3a66658 NOISSUE some safe refactors and changes of the task subsystem
Possibly also some bug fixes.
2017-06-26 01:14:32 +02:00
Max Nordlund
9583d0d8ee Mention casing in ISSUE_TEMPLATE 2017-06-17 23:31:21 +02:00
Petr Mrázek
2973b11d3e NOISSUE instance export filter should use covers, not contains 2017-05-31 09:37:45 +02:00
Petr Mrázek
8a1da91219 NOISSUE finish cleaning quazip
All LGPL code is back in the customized quazip fork
2017-05-31 09:20:24 +02:00
Petr Mrázek
cdc9bed83f NOISSUE move some zip utility functions back to quazip
It's not entirely clean yet.
2017-05-31 09:20:24 +02:00
Petr Mrázek
7acf1998eb NOISSUE split wrapper commands into command and args
This lets you use commands with parameters.
2017-05-29 01:36:01 +02:00
Petr Mrázek
50b8412a26 NOISSUE do not try to restore file permissions when importing modpacks 2017-05-25 01:24:27 +02:00
Petr Mrázek
2a81e21f5e GH-1876 Clarify license of GroupView
The LGPL code that came from KDE has been removed back in 2014.
It was replaced with a different implementation, made in
a separate repository.

See commits:
a17caba2c9
b82eb5873e
2017-05-22 23:50:20 +02:00
Petr Mrázek
3597a50854 NOISSUE log native extraction failures also to game log 2017-05-22 08:57:13 +02:00
Petr Mrázek
4133247bff NOISSUE and even more warnings gone 2017-05-21 22:30:53 +02:00
Petr Mrázek
c329bc73c0 NOISSUE more compiler warning removal 2017-05-21 22:24:06 +02:00
Petr Mrázek
d432d8ecfc NOISSUE get rid of some more compiler warnings 2017-05-21 22:14:40 +02:00
Petr Mrázek
8bd8be95f0 NOISSUE fix a bunch of compiler warnings 2017-05-21 20:20:37 +02:00
Petr Mrázek
572a6026b5 GH-1895 update LWJGL list during legacy instance update 2017-05-21 02:34:02 +02:00
Petr Mrázek
d70c783de8 NOISSUE bump version to 0.6.0 - MultiMC changed a lot since 0.5.x 2017-05-13 11:01:38 +02:00
Petr Mrázek
e1a03e8724 NOISSUE make the linux package binary name configurable and default to 'multimc' 2017-05-13 10:43:56 +02:00
Petr Mrázek
868669a497 NOISSUE add a linux system packaging install layout 2017-05-13 01:24:15 +02:00
Petr Mrázek
4cf4110d9d NOISSUE log even more about 'Flame' resolving issues 2017-05-09 21:56:33 +02:00
Petr Mrázek
e029b7764e NOISSUE log 'Flame' mod resolver parsing errors. 2017-05-09 21:49:36 +02:00
Petr Mrázek
8a526fab0e GH-1885 make FileSink save (even empty) files when the HTTP response is 200 or 203 2017-05-09 03:08:38 +02:00
Petr Mrázek
8fe18cfabc GH-1882 save UpdateDialog geometry 2017-05-09 01:54:28 +02:00
Petr Mrázek
0f311e12ee GH-1886 warn users about proxy settings not applying to the game 2017-05-08 23:37:36 +02:00
Petr Mrázek
01058b1db1 NOISSUE all Qt5 libraries are REQUIRED 2017-05-08 23:34:23 +02:00
Petr Mrázek
c407004e3a NOISSUE make qt.conf downloadable in presence of GH-1885
Now it has a single space inside.
2017-05-08 00:07:20 +02:00
Petr Mrázek
3fb15e4a4d NOISSUE include qt.conf in all bundles again
Looks like it just doesn't work properly without that.
2017-05-07 22:19:01 +02:00
Petr Mrázek
a379d43d7c NOISSUE replace bad symlink to COPYING.md with a relative path in qrc 2017-05-06 18:32:28 +02:00
Petr Mrázek
3263b52e0c GH-1876 replace ColumnResizer with a newer, BSD-3 licensed version
Also, keep licensing info only in one file.
The COPYING.md is now a resource and rendered to HTML in the About dialog.
2017-05-06 18:27:47 +02:00
Petr Mrázek
15c829fd3c GH-1876 Fork and update quazip
* It is added as a new submodule: https://github.com/MultiMC/quazip/tree/multimc-1
* Its build system has been entirely replaced to remove the existing issues with it
* It now has working unit tests
* No more patches needed
* It has a static linking exception in its license now, but we use it shared anyway
2017-05-06 17:36:57 +02:00
Petr Mrázek
349381cb2b NOISSUE remove debug symbols of Qt plugins from macOS bundle 2017-05-06 11:58:57 +02:00
Petr Mrázek
4183cc203f NOISSUE add back qt.conf on macOS
Looks like it doesn't start without this magical empty file.
Who would have guessed? Not me.
2017-05-06 03:41:11 +02:00
Petr Mrázek
2b3e87b7d1 NOISSUE reorganize build system to allow avoiding the bundle utilities 2017-05-06 03:11:38 +02:00
Petr Mrázek
e5147e6b65 NOISSUE remove (assumed) obsolete parts of the application cmake script 2017-05-05 23:09:26 +02:00
Petr Mrázek
9d4c188fd4 GH-1876 turn iconfix into a shared library 2017-05-05 09:43:20 +02:00
Petr Mrázek
e854894a3c GH-1876 turn pack200 into a shared library 2017-05-05 01:34:01 +02:00
Petr Mrázek
0ce44dbd41 GH-1864 fix imgur album creation 2017-05-04 22:58:22 +02:00
Petr Mrázek
35836c7709 NOISSUE herp derp custom icon theme support
* Put icon theme in iconthemes/custom/
* Select 'Custom' in the UI.
* ...
* Maybe it won't explode.
2017-05-04 00:03:47 +02:00
Petr Mrázek
e76e6329cd NOISSUE Revert all recent changes to NetAction and NetJob 2017-05-03 23:13:49 +02:00
Petr Mrázek
0efa714ba5 NOISSUE replace std::shared_ptr with shared_qobject_ptr for all download tasks 2017-05-03 21:09:36 +02:00
Petr Mrázek
907aa36704 GH-1874 Do not allow launching instances during an update 2017-05-02 23:29:47 +02:00
Petr Mrázek
6a8bb3691b GH-1874 do not allow updating while an instance is running
This is a nasty hack. Proper solution will require moving all
update related functionality out of the main window.

Running instances and updating should be mutually exclusive.
2017-05-02 01:43:18 +02:00
Affe Ali
0132fd9929 GH-1855 add launch offline button to instance UI 2017-05-01 23:18:00 +02:00
Petr Mrázek
9bde1c8512 GH-1874 do not pass instance launch args to updated MultiMC 2017-05-01 16:53:20 +02:00
Petr Mrázek
b20688a18d GH-1875 plug holes in instance/window refcount logic 2017-05-01 12:55:10 +02:00
Petr Mrázek
21df531db1 GH-1873 allow closing main window, fix window ref count 2017-05-01 01:27:10 +02:00
Petr Mrázek
f06ac02396 NOISSUE block use of "-XX-MaxHeapSize" and "-XX:InitialHeapSize" java args.
Synonyms for "-Xms" and "-Xmx" that I missed originally.
These are ALWAYS managed by MultiMC. Do not touch them.
2017-04-30 15:12:46 +02:00
Petr Mrázek
794102b32c NOISSUE less jumpy download progress bars and redirect URL fix 2017-04-30 02:54:37 +02:00
Petr Mrázek
1be99b075a NOISSUE more NetAction and NetJob cleanups 2017-04-29 21:34:36 +02:00
Petr Mrázek
e1465f4848 NOISSUE refactor NetAction to be based on Task
Still missing some things, this is part 1.
2017-04-29 02:24:00 +02:00
Petr Mrázek
243f7e4fb4 NOISSUE remove AA_UseHighDpiPixmaps 2017-04-26 22:57:02 +02:00
Petr Mrázek
edc25dab17 NOISSUE Set AA_EnableHighDpiScaling for Qt >= 5.6.0 2017-04-26 22:17:27 +02:00
Petr Mrázek
6dc1bc65e1 NOISSUE fix Mojang JSON format unit test on Qt 5.6 by dumping JSON to byte arrays 2017-04-25 23:33:19 +02:00
Petr Mrázek
6fe9258161 NOISSUE remove macOS SSL workarounds
Should not be necessary anymore...
2017-04-25 23:03:11 +02:00
Petr Mrázek
4fa3e2a714 GH-1856 Fix metadata version and list loading
Shouldn't crash anymore, shouldn't overwrite data in some bad way anymore either.
2017-04-24 01:30:51 +02:00
Petr Mrázek
d25a7ad3a6 NOISSUE accept URL drop events in GroiupView 2017-04-23 16:50:48 +02:00
Petr Mrázek
3f24c4cfe5 GH-1856 Make MultiMC fail hard when things are missing
Things like:
* jar mods
* valid version files
2017-04-23 02:34:16 +02:00
flcmc
b414bbe395 NOISSUE Update COPYING.MD Formatting 2017-04-22 21:31:43 +02:00
Petr Mrázek
8084f27ec8 NOISSUE do not write library display name twice 2017-04-22 20:27:00 +02:00
Petr Mrázek
249baf6fcf GH-1860 fix old jarmods
Names were not set for the libraries, making them return invalid things
2017-04-22 19:38:28 +02:00
Petr Mrázek
8ace5fa91d NOISSUE Add flame. 2017-04-22 18:51:04 +02:00
Petr Mrázek
30863a88ab NOISSUE add pack import using drag&drop
Straight from the browser or the downloads folder.
2017-04-22 06:11:26 +02:00
Petr Mrázek
77a1d39f6b NOISSUE fix problems in old curse packs
Added:
* jarmod importing
* fixing of bad minecraft versions
* mapping of undefined 'recommended' forge versions to something appropriate
* some fake guessing of pack icons
* fixes for some more issues found with the pack manifest format
2017-04-22 05:20:06 +02:00
Petr Mrázek
6a525db78d NOISSUE 'required' attribute of curse manifests is optional, libraries attribute reading 2017-04-22 00:29:24 +02:00
Petr Mrázek
1d71214d4a NOISSUE fix build: there is no qInfo in old Qt5. 2017-04-21 22:30:39 +02:00
Petr Mrázek
ab5045b54c NOISSUE finalize curse modpack import work 2017-04-21 22:23:31 +02:00
Petr Mrázek
f3c46dbf11 NOISSUE silly/simple implementation of mod metadata in OneSix version format 2017-04-21 22:23:00 +02:00
Petr Mrázek
581460dcf9 NOISSUE add missing log levels to MultiMC logging
Info and System are now recognized.
2017-04-21 22:08:33 +02:00
Petr Mrázek
6bd2605a79 NOISSUE add import from curse zip packs
Does not actually grab mods, but resolves them and prints the results in logs.
2017-04-20 05:22:04 +02:00
Petr Mrázek
e9a6199507 NOISSUE fix benign issue in pack200 unpacker binary. 2017-04-19 22:23:00 +02:00
Petr Mrázek
60777ad8ce GH-1856 always pull new versions of metadata when requested
The only block is if it's already happening.
2017-04-19 22:23:00 +02:00
Rafael Ristovski
88041783e6 Add missing <functional> include.
Compiling under Linux fails because of a missing include directive
Ref:
http://en.cppreference.com/w/cpp/utility/functional/bind
http://en.cppreference.com/w/cpp/utility/functional/placeholders
2017-04-19 22:11:12 +02:00
Petr Mrázek
47e075babd NOISSUE set metadata source to main 2017-04-18 17:55:05 +02:00
Petr Mrázek
5565a2f85e NOISSUE fix crash because of early destruction of java list load task 2017-04-18 16:45:58 +02:00
Petr Mrázek
c4c8e99681 NOISSUE jar mods as libraries, fix for customizing net.minecraft 2017-04-17 22:51:30 +02:00
Petr Mrázek
fc28aacdea NOISSUE stop using the path attributes from Mojang download info
It really should not dictate how are things stored and it just makes
the metadata bigger for no reason.
2017-04-15 11:40:22 +02:00
Petr Mrázek
07cde802e4 GH-1853 fix FTB and parsing of old version files 2017-04-14 12:33:54 +02:00
Petr Mrázek
2aaf9827a6 NOISSUE slightly refactor jarMod entry reading 2017-04-14 12:21:10 +02:00
Petr Mrázek
910766458d GH-1854 prevent a crash if the instance is closed while the kill confirmation dialog is open 2017-04-14 10:41:52 +02:00
Petr Mrázek
be53eb66f8 NOISSUE implement mainJar support in OneSix format
This allows customizing the main jar like any other library.
2017-04-13 09:28:25 +02:00
Petr Mrázek
db7357d008 Revert "NOISSUE disable version customization until further notice"
This reverts commit d864c95e2b.
2017-04-08 22:04:07 +02:00
Petr Mrázek
795889d934 Merge branch 'feature/meta' into develop 2017-04-07 00:27:24 +02:00
Petr Mrázek
8e58d61150 NOISSUE fix issue with the narrator feature by splitting java and native libraries 2017-04-07 00:20:02 +02:00
Petr Mrázek
dddc5cedf3 NOISSUE make a call to ensureBoolean in the JSON format code less ambiguous 2017-04-07 00:20:02 +02:00
Petr Mrázek
d864c95e2b NOISSUE disable version customization until further notice 2017-04-07 00:20:02 +02:00
Petr Mrázek
dff307557b NOISSUE fix liteloader uid where it is hardcoded hardcoded 2017-04-07 00:20:02 +02:00
Petr Mrázek
643d74f66c NOISSUE implement recommended versions using the new JSON format 2017-04-07 00:20:02 +02:00
Petr Mrázek
f565798650 NOISSUE remove unused version range filtering 2017-04-07 00:20:02 +02:00
Petr Mrázek
e0596d3c86 NOISSUE Make forge installable again 2017-04-07 00:20:02 +02:00
Petr Mrázek
2ac0edbbdb NOISSUE preview of LWJGL version changing
It still needs work - some LWJGL versions are exclusive to macOS.
This has to be encoded in the json.
2017-04-07 00:20:02 +02:00
Petr Mrázek
53188386b8 NOISSUE refactor builtin patch loading slightly 2017-04-07 00:20:02 +02:00
Petr Mrázek
af3384c649 NOISSUE add filename to newly created jar mod patches 2017-04-07 00:20:02 +02:00
Petr Mrázek
22735f275e NOISSUE remove dead code 2017-04-07 00:20:02 +02:00
Petr Mrázek
5fabb4f254 NOISSUE Rough refactor of ProfilePatch and VersionFile internals.
They are now distinct classes with distinct responsibilities.

* ProfilePatch is an entry in MinecraftProfile and can hold VersionFile or Meta::Version.
* VersionFile is the basic element that holds version information loaded from JSON.
* Meta::Version is the loader class for VersionFile(s) from a server.
2017-04-07 00:20:02 +02:00
Petr Mrázek
6f2a87167a NOISSUE remove some dead code from version related classes 2017-04-07 00:20:02 +02:00
Petr Mrázek
3aa28bd64a NOISSUE fix some warning on linux related to the GNU C library 2017-04-07 00:20:02 +02:00
Petr Mrázek
da4ae1bc1e NOISSUE reimplement package dependencies
It is now stored as a hashmap
There is also a parentUid to limit depsolving by encapsulating by version
2017-04-07 00:20:02 +02:00
Petr Mrázek
77f27a628f NOISSUE bring back instance creation 2017-04-07 00:20:02 +02:00
Petr Mrázek
f557c13679 NOISSUE stuff and things happened. Maybe. 2017-04-07 00:20:02 +02:00
Petr Mrázek
2660418d58 NOISSUE hack it together enough to get launching back
Meta index will now always return valid objects.
They just might never load if they don't exist on the server.
2017-04-07 00:20:02 +02:00
Petr Mrázek
e46aba9da5 NOISSUE sanitize loading and downloading of metadata files 2017-04-07 00:20:02 +02:00
Petr Mrázek
0060b50625 NOISSUE simplify. 2017-04-07 00:20:01 +02:00
Petr Mrázek
40cf38bc32 NOISSUE remove liteloader and forge 2017-04-07 00:20:01 +02:00
Petr Mrázek
f6eb8fa1e4 NOISSUE Remove hardcoded LWJGL (modern) 2017-04-07 00:20:01 +02:00
Petr Mrázek
2980322c3b NOISSUE Remove Minecraft version list and versions. 2017-04-07 00:20:01 +02:00
Petr Mrázek
8321187a20 NOISSUE fix downloading of metadata files 2017-04-07 00:20:01 +02:00
Petr Mrázek
ab868df50e NOISSUE Wonko is the new Meta
And then Wonko was the Meta.
2017-04-07 00:20:01 +02:00
Petr Mrázek
1fbe03f982 NOISSUE remove unused wonkoclient 2017-04-07 00:20:01 +02:00
Petr Mrázek
7382360771 NOISSUE remove builtin Minecraft versions 2017-04-07 00:19:56 +02:00
Petr Mrázek
8cbe13c656 NOISSUE remove legacy version blacklist 2017-04-07 00:19:51 +02:00
Petr Mrázek
160b5033a7 GH-1828 hardcode legacy assets location to fix legacy launch 2017-02-28 20:52:50 +01:00
Petr Mrázek
01cb5ebb35 GH-1828 do not load assets info from custom version files
Fixes issue where this causes the launcher to use the old assets URL
2017-02-28 20:37:51 +01:00
Petr Mrázek
aafac3934b NOISSUE update changelog 2017-02-11 22:53:03 +01:00
Petr Mrázek
17fac2e0df NOISSUE switch paste.ee over to https only 2017-02-08 21:30:39 +01:00
Petr Mrázek
8bbaab334c NOISSUE set line limit and overflow behaviour even for hidden console 2017-02-08 20:01:42 +01:00
Petr Mrázek
155de307bc GH-1802 fix log resize handling
The log could end up with many empty lines because the wrong maximum size was
used during the resize.
2017-02-08 01:59:16 +01:00
Petr Mrázek
2e8d8b60b0 GH-1807 fix 'loggging' typo 2017-02-01 00:44:21 +01:00
Petr Mrázek
c200301673 GH-1801 Do not print the launch script to MultiMC's log. 2017-01-24 08:20:16 +01:00
Petr Mrázek
0a6af3cff3 NOISSUE update changelog 2017-01-22 16:11:01 +01:00
Petr Mrázek
c7f89ec6b5 GH-1798 Do not enable skin upload button without selected account. 2017-01-22 15:45:57 +01:00
Petr Mrázek
cf43abc87e GH-1794 Only write to the instance.cfg once after copying FTB instances. 2017-01-22 15:20:05 +01:00
Petr Mrázek
c421134d49 NOISSUE set the instance settings page default tab back to the first 2017-01-21 20:15:07 +01:00
Petr Mrázek
782384f185 GH-1793 rearrange setup wizard logic to only check if they are needed once 2017-01-21 18:27:16 +01:00
Petr Mrázek
ceb5fc6d75 GH-1790 do not apply system theme on launch if it is selected
This prevents some ugly colors to show up on macOS in most cases.
It still looks ugly right after you switch to the it though.
2017-01-18 02:48:29 +01:00
Petr Mrázek
201d4ac317 GH-1789 fix icon deletion 2017-01-17 23:36:41 +01:00
Petr Mrázek
85320777c6 GH-1788 missed one call wrong call... this is the fix. 2017-01-17 21:19:38 +01:00
Petr Mrázek
ba38991c13 GH-1788 fix missing translation strings 2017-01-17 21:17:36 +01:00
Tim Flynn
98e17998fe GH-1065 Normalize usage of directory vs folder 2017-01-16 22:42:22 +01:00
Petr Mrázek
944ff256b2 NOISSUE add hack for system themes. Maybe it works? 2017-01-15 22:56:03 +01:00
Petr Mrázek
71584fb8cc NOISSUE temporarily disable themes to check if they cause issues on macOS 2017-01-15 20:32:55 +01:00
Petr Mrázek
b2dbaaa9e2 NOISSUE also preserve x.y.z version numbering in the application 2017-01-14 19:44:34 +01:00
Petr Mrázek
0a89b04afd GH-1665 Add line breaks to the fatal error dialogs.
Makes is slightly more readable.
2017-01-14 18:22:50 +01:00
Petr Mrázek
ffa8792c13 NOISSUE always include the hotfix version in the version string
It's 0.5.0, not 0.5.
2017-01-14 18:12:15 +01:00
Petr Mrázek
fbcbddd4d0 GH-1665 put the macOS hint into all of the new fatal error messages. 2017-01-14 16:51:08 +01:00
Petr Mrázek
a6ef0059cc GH-1665 attempt at workaround for MultiMC not starting on macOS Sierra
This tries to detect the issue and instructs the user to fix it by
moving the application to /Applications or ~/Applications.

In addition, several other previously poorly handled fatal errors
now show an error dialog.
2017-01-14 15:47:58 +01:00
Petr Mrázek
3e81e2cb5b NOISSUE do not show the analytics wizard page without analytics in the build 2017-01-13 02:12:40 +01:00
Petr Mrázek
858b490c74 GH-1778: Fix placement of modded Minecraft.jar in OneSix instances. 2017-01-10 23:03:00 +01:00
Petr Mrázek
12c3683ec0 NOISSUE set version to 0.5.0 2017-01-08 05:00:24 +01:00
Petr Mrázek
f530aae9d3 NOISSUE update all the Copyright comments and texts to include 2017 2017-01-08 04:58:05 +01:00
Petr Mrázek
5ea224f8f5 NOISSUE corrected changelog
Proofreading by Zekken and bvanseghi. Let's hope no error escaped.
2017-01-08 04:43:22 +01:00
Petr Mrázek
e033cf8974 NOISSUE change 'Upload' to 'Upload Skin' on tha Accounts page 2017-01-08 03:02:27 +01:00
Petr Mrázek
8e7330ae54 NOISSUE update changelog for 0.5.0 release. 2017-01-08 02:05:28 +01:00
Petr Mrázek
ccb524ed9f NOISSUE disable travis builds with Qt 5.6.2
It has a regression that breaks one of the unit tests.
MultiMC doesn't even use 5.6.x yet.
2017-01-07 23:40:14 +01:00
Petr Mrázek
cff34a14dc NOISSUE dump the json to log in MojangVersionFormatTest 2017-01-07 19:32:39 +01:00
Petr Mrázek
8421ef622d NOISSUE even more java polishing
* Memory minimums lowered to 128M in all Java settings UIs
* Changing the memory sizes on the wizard page does not automatically trigger checks if the executable doesn't have 'java' in the name
* Java detection on linux now scans some common JRE locations, not just /usr/bin/java
2017-01-07 18:11:41 +01:00
Petr Mrázek
c4ec6bc0f5 NOISSUE polish the java setup wizard page
* Added a button to check why Java failed
* It will now avoid automatically scanning binaries that do not have 'java' in their filename
* Fixed some crashes related to running too many Java checks (it only does one at a time now)
* It can now distinguish between more Java failure states (not there at all, crashing, returning nonsense)
* Changed '...' button to Browse button to match the wizard page subtitle
* Changing minimum and maximum memory will no longer trigger a java check twice
2017-01-07 06:52:09 +01:00
Petr Mrázek
705a658fef NOISSUE Do not log the analytics client ID into the application log. 2017-01-06 17:19:28 +01:00
Petr Mrázek
6f17183bf0 NOISSUE make the setup wizard use the main event loop
This should fix any issues with receiving events over IPC.
2017-01-06 06:08:45 +01:00
Petr Mrázek
0249bd9eea NOISSUE default to javaw on Windows 2017-01-05 14:20:37 +01:00
Petr Mrázek
e1bd1c6145 NOISSUE feature complete setup wizard 2017-01-05 04:05:08 +01:00
Petr Mrázek
4c0db2b99d NOISSUE fix travis.ci build
Qt 5.6 version needed incrementing to 5.6.2.
2017-01-02 16:15:40 +01:00
Petr Mrázek
9ca9addad3 NOISSUE create a dumb and ugly java setup wizard page
All it does is create the existing Java selection dialog
2017-01-02 16:02:54 +01:00
Petr Mrázek
64723f68e3 NOISSUE force SetupWizard into 'classic' look and feel and increment analytics version
This should force the dialog to show again.
If it still looks wrong on Windows 10, please report this on discord.
2017-01-02 08:23:03 +01:00
Petr Mrázek
a666dc0a1a NOISSUE fix up translation selection in settings and add OS/sys arch reporting 2017-01-01 20:04:08 +01:00
Petr Mrázek
722896d41f NOISSUE Translations model and initial setup wizard work 2017-01-01 20:04:08 +01:00
Petr Mrázek
46c5368a78 NOISSUE fix up analytics wizard page 2016-12-28 21:39:09 +01:00
Petr Mrázek
476d641841 NOISSUE add skeleton of the setup wizard
Very wizardly. Also very empty and opening on every start for now.
2016-12-28 21:39:09 +01:00
Petr Mrázek
374710a87b GH-1379 update nbt++ to allow renaming its library file 2016-12-28 21:14:44 +01:00
Petr Mrázek
2344ee2dcd GH-1379 rename shared libraries to avoid collisions with system libraries
It was unlikely, now it's impossible.
2016-12-28 17:23:48 +01:00
Petr Mrázek
481ecb178c NOISSUE fix credits entry for RoboSky 2016-12-26 12:45:30 +01:00
Petr Mrázek
123b59e63f NOISSUE Fix up Credits section in About dialog 2016-12-26 01:47:29 +01:00
Petr Mrázek
92bb001787 NOISSUE fix crash caused by missing instance view layout updates
Layout wasn't updated in some cases while deleting instances.
2016-12-19 00:35:57 +01:00
Taylor Smock
03d2858c62 BUILD: Remove extraneous " from CreateServerResourcePacksFolder.cpp (#1749)
NOISSUE Remove extraneous " from CreateServerResourcePacksFolder.cpp

This did not affect build, but was visible in logs.
2016-12-12 14:36:42 +01:00
Petr Mrázek
a6882787b0 GH-1745 fix crash when using path matching filter on copy operations
Copying instances without saves doesn't crash anymore.
2016-12-08 21:58:31 +01:00
Petr Mrázek
2517d2c84d GH-1743 selected instance can be null - do not assume it isn't
This fixes a crash when closing settings and not having any selected instance.
2016-12-07 01:19:03 +01:00
Petr Mrázek
035bdc7576 GH-1524 Regenerate Minecraft client token when the auth token is invalid
This makes the case where users copy MultiMC to other machines
easier to handle. It doesn't require manual intervention and the tokens
do not go in a desync loop.
2016-11-30 00:19:27 +01:00
Petr Mrázek
4ca6878743 GH-1670 Fix LWJGL list loading
Now it uses the standard Download class that supports redirects and SSL.
2016-11-27 01:45:55 +01:00
Petr Mrázek
ef73a2bd32 NOISSUE fix Windows kernel numbers and add unit test for them 2016-11-27 00:40:02 +01:00
Petr Mrázek
5994c47d7c NOISSUE add ganalytics and LocalPeer licenses 2016-11-26 23:53:56 +01:00
Petr Mrázek
66ffab71ae NOISSUE allow killing the instance from main window 2016-11-26 18:06:08 +01:00
Petr Mrázek
ce70407363 NOISSUE add button for opening the config folder from mods pages 2016-11-26 14:59:27 +01:00
Petr Mrázek
dccf9d7219 NOISSUE fix text of log upload, do not open browser on screenshot upload 2016-11-26 14:37:36 +01:00
Petr Mrázek
dd0c815396 NOISSUE fix macOS build (stray assignment to removed variable) 2016-11-26 02:22:40 +01:00
Petr Mrázek
55541c387c NOISSUE simplify system detection and user agent handling
Now it only checks OS kernel name/version.
User agent is 'MultiMC5/$version'.
Kernel info is passed through custom dimensions in analytics.
2016-11-26 02:18:05 +01:00
Petr Mrázek
d5fdc23eb2 NOISSUE dumb down Windows version detection...
Hopefully the analytics thing will accept it this time.
2016-11-25 00:39:15 +01:00
Petr Mrázek
a5fb931e8e NOISSUE fix build (OSVERSIONINFOW) 2016-11-24 23:32:21 +01:00
Petr Mrázek
486d653586 NOISSUE Better Windows version detection and user agent 2016-11-24 23:28:55 +01:00
Petr Mrázek
121e2fd46c NOISSUE add analytics settings (enable/disable) 2016-11-24 04:10:07 +01:00
Petr Mrázek
295c6e808a NOISSUE fix translation listing in settings and translation loading
It was impossible to select and load translations properly.
2016-11-23 02:25:49 +01:00
Petr Mrázek
7a14b63957 NOISSUE send custom analytics values
* System, Java and CPU architecture (either 32 or 64).
* Java version.
* System memory size in MB.
* Java min/max heap size in MB.
2016-11-22 02:46:18 +01:00
Petr Mrázek
44805145dc NOISSUE add implementations of system query functions
* system memory size in bytes
* system architecture is 64bit?
* CPU architecture is 64bit?
2016-11-22 02:46:18 +01:00
Petr Mrázek
00c4aebeaa GH-1731 more screenshot folder view hardening 2016-11-22 00:56:48 +01:00
Petr Mrázek
ee6f2f0a8e NOISSUE implement analytics IP anonymization 2016-11-21 21:18:30 +01:00
Petr Mrázek
95f961fb61 GH-1731 Do not show screenshots model if it can't be set up properly
Otherwise it would show all system drives instead of screenshots.
2016-11-21 09:17:01 +01:00
Petr Mrázek
ad25c89ac4 NOISSUE ifdef out unknown Apple system versions in analytics 2016-11-21 01:30:39 +01:00
Petr Mrázek
905bc2e440 NOISSUE most basic analytics integration possible 2016-11-21 01:19:34 +01:00
Petr Mrázek
2f8c752d1f NOISSUE reformat and sanitize ganalytics 2016-11-21 01:19:22 +01:00
Petr Mrázek
2ec15c32e4 NOISSUE import google analytics from third party
See: https://github.com/HSAnet/qt-google-analytics

Sadly, the API and its internals are not acceptable and it needs changes
upstream likely wouldn't allow.
2016-11-20 12:04:29 +01:00
Petr Mrázek
69be23c5f6 GH-1726 better failure detection for updates
Instead of just checking if the new version started, make sure
it is able to write its IPC key to a file and then use the key
to connect to the process.
2016-11-19 22:11:45 +01:00
Petr Mrázek
e974950d48 GH-1699 do not include libxcb.so* in linux builds 2016-11-19 22:11:41 +01:00
Petr Mrázek
9efdd7232c NOISSUE include json path in errors when FTB json is missing. 2016-11-17 04:40:07 +01:00
Petr Mrázek
9b41986634 GH-347 update timestamps of added mods 2016-11-17 04:09:24 +01:00
Petr Mrázek
b09fad9cbf GH-347 Add timestamp column to mod lists
It shows when the file was changed (in most cases added).
2016-11-17 02:55:02 +01:00
Petr Mrázek
fd34ca5a0f NOISSUE always run the ExtractNatives task during launch
The task now checks the conditions, giving the update process time
to supply all the metadata.
2016-11-17 01:21:49 +01:00
Petr Mrázek
9cf8b42d89 NOISSUE mark profile in use also on the main window profile button 2016-11-17 01:00:15 +01:00
Petr Mrázek
12f6534e77 NOISSUE mark used accounts/sessions in selection menus 2016-11-17 01:00:15 +01:00
Petr Mrázek
3769897be1 NOISSUE do not open browser window on log upload 2016-11-17 01:00:15 +01:00
44trent3
590ff82fd1 NOISSUE Add Windows instructions to build from command line. 2016-11-15 23:13:43 +01:00
Petr Mrázek
f9d94a45ee NOISSUE allow using icon themes for instances and instance badges 2016-11-10 02:54:53 +01:00
Petr Mrázek
27e26a656b NOISSUE remove unused hourglass icon 2016-11-10 00:19:04 +01:00
Petr Mrázek
b6f133f579 GH-1713 fix FTB loading crashes 2016-11-09 01:22:02 +01:00
Petr Mrázek
01649f761d NOISSUE remove some unused icons 2016-11-09 01:20:42 +01:00
Petr Mrázek
dae3b06885 NOISSUE fix horrible globals crash
FIXME: remove all globals.
2016-11-07 02:28:18 +01:00
Petr Mrázek
07589b5114 NOISSUE shut down logger when MultiMC exits
Prevents crash bugs...
2016-11-07 01:54:00 +01:00
Petr Mrázek
7cff5ba2e1 GH-1445 update page list when version and log pages need it 2016-11-07 00:18:27 +01:00
Petr Mrázek
1276ecdbb7 NOISSUE ask user if closing is OK when instances are still running 2016-11-06 23:06:49 +01:00
Petr Mrázek
8b952b3870 NOISSUE Refactor and sanitize MultiMC startup/shutdown
* Always create main window.
* Properly handle netowrk manager - it was created twice, leading to potential crashes.
2016-11-06 21:58:54 +01:00
Petr Mrázek
37cc59c04d GH-378 add a resource search path to custom themes
This allows adding images and other bits and pieces to themes.
2016-11-06 05:48:52 +01:00
Petr Mrázek
bc753859b5 GH-378 add basic custom theme support
Files you can customize are created in themes/custom/
2016-11-06 04:29:12 +01:00
Petr Mrázek
13b575f7a9 GH-1711 fix inactive element shading in Dark and Bright themes 2016-11-06 00:17:02 +01:00
Stefan
495e752f8a NOISSUE Point people to the wiki for the explanation about bug reports 2016-11-04 09:03:34 +01:00
Petr Mrázek
87dd951505 NOISSUE add a badge for crashed instances
Not persistent across MultiMC runs.
2016-11-04 01:19:04 +01:00
Petr Mrázek
3780a25d27 NOISSUE add an option to show console on error and default other options to false 2016-11-04 00:19:32 +01:00
Petr Mrázek
6ebf6e7785 NOISSUE ifdef the hell out of MCEdit launch on Windows
Setting the work directory was not enough.
2016-11-03 02:41:01 +01:00
Petr Mrázek
f4de049b13 NOISSUE Set working directory for MCEdit on Windows
It seems to require it, unlike the other versions.
2016-11-03 02:21:50 +01:00
Petr Mrázek
f0b71f989e NOISSUE use LoggedProcess to work around issues with QProcess on macOS 2016-11-03 01:11:57 +01:00
Petr Mrázek
ac66af6c13 NOISSUE fix reversed MCEdit check condition
It was causing fake errors.
2016-11-02 02:55:16 +01:00
Petr Mrázek
85b64ad767 NOISSUE MCEdit integration - remove old 'tool', replace with Worlds 2016-11-02 02:37:54 +01:00
Petr Mrázek
3a4304d89d NOISSUE simplify retranslation code of MainWindow 2016-11-02 01:17:19 +01:00
Petr Mrázek
a9c0d812a6 NOISSUE prefer shell script for running MCEdit on linux 2016-11-02 01:16:41 +01:00
Petr Mrázek
b6b2350e02 NOISSUE improve launch button interaction
Now has a drop-down arrow that actually works as expected.
2016-11-01 23:33:20 +01:00
Petr Mrázek
2e0a45cc2f NOISSUE add bright theme to complement the dark theme
Same style, different colors.
2016-11-01 09:04:37 +01:00
Petr Mrázek
fe68d59460 GH-1645 reimplement open/close instance window based on settings 2016-11-01 01:25:04 +01:00
Petr Mrázek
4b03dfcbd7 NOISSUE rearrange MultiMC.cpp to make it make more sense 2016-10-31 00:57:40 +01:00
Petr Mrázek
a36c962a31 NOISSUE use current directory for application ID
Using QDir(dataPath).absolutePath() for the path
2016-10-30 14:47:16 +01:00
Petr Mrázek
e9949e3a54 NOISSUE use absolute data path for application ID 2016-10-30 03:45:41 +01:00
Petr Mrázek
a717864013 NOISSUE fix the build even more - win32 types are weird 2016-10-30 03:03:49 +01:00
Petr Mrázek
54e0b9bc9b NOISSUE fix build some more - Windows 2016-10-30 02:53:13 +01:00
Petr Mrázek
249e5c13d7 NOISSUE fix build 2016-10-30 02:49:07 +01:00
Petr Mrázek
412855ae3d NOISSUE refactor window management and launch, make MultiMC a single instance application. 2016-10-30 02:37:38 +01:00
Petr Mrázek
deabfa78f8 GH-1652 set instance running status before notifying event listeners 2016-10-29 02:19:42 +02:00
Petr Mrázek
2b9017a69c NOISSUE clean up some bad/dead code 2016-10-29 01:34:43 +02:00
Petr Mrázek
172ff47a65 NOISSUE clarify linux build steps (add command line instructions) 2016-10-29 01:33:47 +02:00
Petr Mrázek
b5aaf88f12 NOISSUE remove unused 'test mode' 2016-10-28 21:54:12 +02:00
Petr Mrázek
8731318fef GH-1652 save all instance settings on launch if instance window is already open 2016-10-28 03:42:34 +02:00
Petr Mrázek
dd0e996081 GH-1697 always stale files tolerate errors if a local copy is present
This fixes the situation when liteloader snapshot site is broken
and there's an older local snapshot already present.
2016-10-28 02:19:19 +02:00
Petr Mrázek
3d94fb8d24 Revert "GH-1665 diagnostic build - check if log file has been created and opened"
This reverts commit 2597bde4f9.
2016-10-27 17:00:37 +02:00
Petr Mrázek
2c2c1b0a17 Revert "GH-1665 diagnostic build - disable file logging entirely"
This reverts commit 0493170936.
2016-10-27 17:00:34 +02:00
Petr Mrázek
0493170936 GH-1665 diagnostic build - disable file logging entirely 2016-10-27 13:40:53 +02:00
Petr Mrázek
2597bde4f9 GH-1665 diagnostic build - check if log file has been created and opened 2016-10-27 13:17:19 +02:00
Petr Mrázek
cee53f7f3c Revert "NOISSUE nuke builtin Minecraft versions"
This reverts commit 5ae3b2c114.

We need those builtin versions for now.
2016-10-26 18:23:39 +02:00
Petr Mrázek
1b4851a941 NOISSUE use QtConcurrent to run FS operations in worker threads
Not all operations - only the ones that aren't in error handling.
The API for QFuture is too nasty to do much more in a sensible way.
2016-10-26 18:21:25 +02:00
Petr Mrázek
d66fdcd4cc NOISSUE Granular instance reload 2016-10-26 18:21:24 +02:00
Petr Mrázek
bbe139dce5 GH-903 force Dark theme to use Fusion Qt style
Themes now include Qt styles.
2016-10-22 01:43:36 +02:00
Petr Mrázek
872cfe036d GH-903 simple theme switching and dark theme 2016-10-21 09:07:26 +02:00
Petr Mrázek
f07496ac6d GH-1675 reimplement suspesion of log watch 2016-10-11 21:34:02 +02:00
Petr Mrázek
6e80f03409 NOISSUE add instance-local library storage
Any libraries stored in $instanceroot/libraries/ will override
the libraries from MultiMC's global folders, as long as they are marked 'local'
in the json patch.
2016-10-02 00:26:10 +02:00
Petr Mrázek
69f3ab019d NOISSUE delete dead code 2016-09-18 22:53:37 +02:00
Petr Mrázek
eb747e08b7 NOISSUE fix minor memory leaks 2016-08-19 09:04:58 +02:00
Petr Mrázek
67eca08b22 NOISSUE use model/view for Minecraft log data 2016-08-19 08:05:43 +02:00
Petr Mrázek
9aff21c181 NOISSUE make progress dialog abort button resistant to accidental key presses 2016-08-17 23:09:33 +02:00
Petr Mrázek
ec05ca2775 SCRATCH make instance windows independent 2016-08-15 00:50:13 +02:00
Petr Mrázek
042f3ef55c GH-352 Make OneSix instance update downloads cancellable 2016-08-14 23:22:54 +02:00
Petr Mrázek
2f0441b3c1 GH-1433 with no default account, show profiles instead of accounts in selection dialog 2016-08-11 00:44:01 +02:00
Petr Mrázek
55544893a3 GH-1643 do not censor preferredLanguage in logs 2016-08-10 19:52:38 +02:00
Petr Mrázek
e2f3652a0f Revert "NOISSUE rework of minecraft log"
This reverts commit fc198dd308.
2016-08-10 08:41:58 +02:00
Petr Mrázek
c60db13af7 NOISSUE Do not kill running instances when MultiMC shuts down 2016-08-10 00:28:33 +02:00
Petr Mrázek
fc198dd308 NOISSUE rework of minecraft log
Now uses a model and a list view instead of text
This lets mmc keep track of the contents regardless of whether the instance windows are open

This is currently missing a way to select and copy text from the log.
2016-08-10 00:28:33 +02:00
Petr Mrázek
74b4343c43 GH-1642 fix instance launch from console 2016-08-09 22:29:17 +02:00
Petr Mrázek
877d1020db GH-1641 we use Qt 5.4.1, not 5.5.1 2016-08-08 22:33:25 +02:00
Petr Mrázek
bc6d1b5304 GH-338, GH-513, GH-700 Unify edit instance with console window
* The resulting instance window can be closed at any point.
* Main window is kept open and running instances are marked with a badge.
* Multiple instances can now run from the same MultiMC - it's even more **multi** now.
* MultiMC can be entirely closed, keeping Minecraft(s) running.
2016-08-07 11:48:15 +02:00
Petr Mrázek
c44d41ee9b NOISSUE do not attempt to stop watching world folders if they are not being watched 2016-08-07 11:44:42 +02:00
Petr Mrázek
cf0694a0cb NOISSUE allow user to sort mod list by clicking on column headers 2016-08-05 00:10:33 +02:00
Petr Mrázek
b76d4573cd GH-589 GH-842 GH-901 GH-1117 allow mass-enabling/disabling of mods 2016-08-04 23:16:03 +02:00
Petr Mrázek
6ec2652b45 GH-1273 allow extended selection in mod lists 2016-08-04 22:57:16 +02:00
Petr Mrázek
eec87db86a GH-1635 add filter bar to mod list pages 2016-08-04 21:54:25 +02:00
Petr Mrázek
42a98c3661 NOISSUE move creation of server resource pack folder to a separate task 2016-08-01 21:15:08 +02:00
Petr Mrázek
1f2bed2ef1 NOISSUE implement direct java launch
Just running the Java process and giving it params on the command line
2016-08-01 21:15:08 +02:00
Mrazek, Petr
57c84ec2b1 NOISSUE more travis issues
There is no Qt 5.7 build for Ubuntu Precise
2016-07-09 05:31:35 +02:00
Mrazek, Petr
2164dc13f4 NOISSUE fix up travis builds
Qt 5.6 -> 5.6.1
+ Qt 5.7
2016-07-08 21:18:57 +02:00
FyberOptic
f626fd02c7 GH-1610 Make Forge installs only use newer list to fix older version downloads 2016-07-08 14:08:07 -04:00
Benjamin Hoffmeyer
7da70a75eb Merge pull request #1590 from Heufneutje/patch-1
Point people to the wiki for attaching logs to issues
2016-06-17 14:48:15 -04:00
Petr Mrázek
969418f01f NOISSUE make liteloader version list pretty and usable 2016-06-14 02:08:56 +02:00
Petr Mrázek
6ecfe8546f NOISSUE implement support for liteloader snapshots 2016-06-13 22:00:09 +02:00
Petr Mrázek
8b74f6dcf0 NOISSUE reset wroteAnyData flag when resetting FileSink
This fixes files getting overwritten with null content when stale cache
and redirects are combined
2016-06-13 21:56:22 +02:00
Petr Mrázek
d4109938fe NOISSUE implement 'always-stale' cache entries 2016-06-13 21:53:56 +02:00
Stefan
be89024d4e NOISSUE Point people to the wiki for attaching logs to issues
A lot of people miss this and you just end up with a bunch of clutter in the actual issue, often hard or impossible to read because of the lack of backticks.
2016-06-13 08:42:41 +02:00
Petr Mrázek
56394f93e5 NOISSUE log which file couldn't be copied during recursive copy 2016-06-10 00:58:30 +02:00
Petr Mrázek
e07456f4bf GH-1586 Windows: attach to the parent process console if there is any, so command line output gets printed there 2016-06-10 00:58:30 +02:00
Petr Mrázek
54e5a98da0 NOISSUE refactor liteloader version file creation
It no longer implements yet another version file format serialization
2016-06-07 01:23:31 +02:00
Petr Mrázek
a1abbd9e05 NOISSUE refactor *Download into more, smaller pieces
* Download is now Download.
* Download uses Sink subclasses to process various events.
* Validators can be used to further customize the Sink behaviour.
2016-06-05 23:55:39 +02:00
Petr Mrázek
a750f6e63c NOISSUE remove excessive build notifications from travis.ci 2016-05-15 23:37:58 +02:00
Petr Mrázek
4440f68e59 GH-575 Add back file drop support to ModList 2016-05-15 23:27:06 +02:00
Petr Mrázek
67b22c8105 GH-575 clean up ModList - remove all legacy and obsolete parts 2016-05-15 22:56:14 +02:00
Petr Mrázek
12413f722d GH-575 separate legacy jar mod list from mod list 2016-05-15 22:56:14 +02:00
Petr Mrázek
5aff10d51d NOISSUE Update travis CI
Remove Qt < 5.4
Add Qt 5.6
2016-05-15 22:50:53 +02:00
Alexia
377316999e GH-767 Basic skin upload 2016-05-15 16:01:05 +02:00
Petr Mrázek
f9791a5cc8 GH-1560 trim whitespace from instance name on rename 2016-05-04 00:31:27 +02:00
Petr Mrázek
603b0408ab GH-1560 trim whitespace from instance names when creating instances 2016-05-04 00:29:40 +02:00
Mrazek, Petr
ecd5d3a2db NOISSUE do not scan extra folders for libraries 2016-05-03 18:26:17 +02:00
Mrazek, Petr
898e3cd4e7 GH-1559 Export IIconList from logic API 2016-05-03 17:49:56 +02:00
Petr Mrázek
e1a530f84d GH-1559 Fix FTB icons
This was caused by separation of GUI and logic. Now logic has an interface that GUI implements.
It should be expanded upon later.
2016-05-03 00:27:28 +02:00
Petr Mrázek
c50b3cdeec NOISSUE fix silly path issue with folders and files with the same names 2016-05-01 04:06:24 +02:00
Petr Mrázek
b0bfffcd90 NOISSUE revert to dumping all build artifacts to the root
This fixes unit tests on Windows... Windows has no mechanism to set library lookup path.
2016-05-01 03:49:46 +02:00
Petr Mrázek
80b28e7d49 NOISSUE add nbt lib to bundle utilities search path 2016-05-01 02:05:21 +02:00
Petr Mrázek
16650790d0 NOISSUE fix dll export for IconList 2016-05-01 00:45:48 +02:00
Petr Mrázek
e32d7238c9 NOISSUE tell bundle utilities about more places where libraries hide
It was super effective.
2016-05-01 00:02:15 +02:00
Petr Mrázek
771dd6f9ab NOISSUE reorganize unit tests to be placed next to the code they test. Nuke more dead tests. 2016-05-01 00:02:15 +02:00
Petr Mrázek
e8ba5dafc6 NOISSUE remove dead unit tests and reorganize CMake code related to unit tests 2016-05-01 00:01:39 +02:00
Petr Mrázek
ed3884fd38 NOISSUE move Java and Minecraft launch tasks to the proper places
Minecraft and Java are not generic.
2016-05-01 00:00:24 +02:00
Petr Mrázek
1be7d57332 NOISSUE re/move some dead code and unused build system parts 2016-05-01 00:00:24 +02:00
Petr Mrázek
aa4842a91d NOISSUE make travis.ci shut up about fancy QJsonObject initialization in Wonko parser 2016-05-01 00:00:24 +02:00
Petr Mrázek
b6d455a02b NOISSUE reorganize and document libraries 2016-05-01 00:00:14 +02:00
Petr Mrázek
47e37635f5 NOISSUE split GUI stuff from logic library 2016-04-30 23:59:23 +02:00
Petr Mrázek
fcd4a482f7 NOISSUE tiny skeleton for a CLI wonko client 2016-04-30 23:59:23 +02:00
Jan Dalheimer
00e5968bd2 NOISSUE Add a skeleton of the wonko system 2016-04-30 23:59:23 +02:00
Petr Mrázek
5ae3b2c114 NOISSUE nuke builtin Minecraft versions
Use upstream Mojang versions.
2016-04-30 23:59:03 +02:00
Petr Mrázek
4392abfb8d GH-1556 disable export for tracked FTB instances 2016-04-28 00:04:37 +02:00
Petr Mrázek
72c92893a5 GH-1556 do not crash when instance has no update task while creating an instance 2016-04-27 23:55:18 +02:00
TheDoctorsLife
0890a81695 NOISSUE: Add double spaces between each section in issue template.
Makes it look pretty once filed out.
2016-04-17 11:15:00 -04:00
Petr Mrázek
432ec74174 GH-1404 allow deleting groups and creating instances in groups directly using context menu 2016-04-11 01:30:50 +02:00
Petr Mrázek
b795ad5209 NOISSUE add line wrapping checkbox to log page 2016-04-10 21:52:01 +02:00
TheDoctorsLife
c44e85c765 NOISSUE: Move the issue template file out of project root to help make it just a little more clean. 2016-04-05 20:38:31 -04:00
Petr Mrázek
b29ef49415 NOISSUE fix some forge version processing issues 2016-04-03 22:17:06 +02:00
Petr Mrázek
f184eff71a NOISSUE write +libraries instead of libraries to stay compatible 2016-04-03 21:53:46 +02:00
Benjamin Hoffmeyer
b3e3a6fc88 NOISSUE Make formatting pretty Idiot proof 2016-04-01 15:06:03 -04:00
Benjamin Hoffmeyer
0ff6f3a036 NOISSUE Make formatting little easier to understand 2016-04-01 15:01:55 -04:00
Benjamin Hoffmeyer
bf0f27bd60 NOISSUE Remove formatting for help section 2016-04-01 14:59:28 -04:00
Benjamin Hoffmeyer
dd5b07e38d NOISSUE Make the notes to the user not show up if not deleted.
Also add a line about formatting.
2016-04-01 14:55:32 -04:00
Alexia
ea685651a1 NOISSUE Quick fix for icons being required 2016-03-28 16:45:52 -04:00
Petr Mrázek
53b4bd019f NOISSUE fix bug in unpacking of forge pack200 jar files
This caused failed downloads and broken files to be used.
2016-03-28 20:52:14 +02:00
Petr Mrázek
f032e32133 NOISSUE finalize support for new mojang version format 2016-03-27 22:35:06 +02:00
Petr Mrázek
d587720010 NOISSUE use new mojang assets locations 2016-03-26 17:05:27 +01:00
Petr Mrázek
2929ca7413 NOISSUE use unique_ptr for cached download's QSaveFile 2016-03-26 17:05:27 +01:00
Petr Mrázek
ff8f495d44 NOISSUE remove unused 'INetworkValidator' 2016-03-26 17:05:27 +01:00
Petr Mrázek
f56983e5ca NOISSUE do not write 'time' and 'releaseTime' when they are null 2016-03-26 17:05:27 +01:00
Petr Mrázek
ec6204e447 NOISSUE share logic for new attributes between mojang and onesix format 2016-03-26 17:05:27 +01:00
Petr Mrázek
9e3534f2f6 NOISSUE stop update task when it can't read version files 2016-03-26 17:05:27 +01:00
Petr Mrázek
b7d8e512f4 NOISSUE Use patch problems and problem levels instead of exceptions for minecraft profiles. 2016-03-26 17:05:27 +01:00
Petr Mrázek
fb9dfcb951 NOISSUE stop referring to the minecraft profile as 'version' 2016-03-26 17:05:27 +01:00
Petr Mrázek
010e07eb45 NOISSUE clean up forge installer 2016-03-26 17:05:27 +01:00
Petr Mrázek
576d808d71 NOISSUE resolve library activeness during application to profile 2016-03-26 17:05:27 +01:00
Petr Mrázek
f63d1bc99c NOISSUE revert attempt to use normal binary output locations 2016-03-26 17:05:27 +01:00
Petr Mrázek
02c1df2c3c NOISSUE continue version file format refactors 2016-03-26 17:05:27 +01:00
Alexia
1854e05e1b NOISSUE Fix building when embedded in another project 2016-03-26 17:01:20 +01:00
Loetkolben
0c06ab364c NOISSUE Remove tr(...) where unnecessary. 2016-03-23 12:42:38 +01:00
Petr Mrázek
07608ebc4c GH-1521 When json editor is custom, actually pass the filename to it 2016-03-17 13:25:57 +01:00
Spencer Burris
36f3813ce5 NOISSUE: Change text to also refer to later java versions 2016-03-16 21:22:13 -07:00
Spencer Burris
f96d20b6f7 NOISSUE: Add note about Java 8 settings permgen automatically 2016-03-15 09:19:16 -07:00
Petr Mrázek
ead4c17d0a NOISSUE hide mojang structs inside the mojang format entirely 2016-03-07 22:26:44 +01:00
Petr Mrázek
d4eacb56b3 NOISSUE make new Mojang version format pass through MultiMC structures
Not yet used effectively, but it is read and written properly
2016-03-07 02:03:36 +01:00
Petr Mrázek
3d8728f52f NOISSUE no issue. with unit tests. 2016-03-03 22:47:41 +01:00
Petr Mrázek
2e4fa7ec13 NOISSUE Fix bad unit test data path and usage of std::abs 2016-03-03 02:13:07 +01:00
Petr Mrázek
fd2103d6ee NOISSUE disable complex variant of mojang version format test 2016-03-03 01:59:47 +01:00
Petr Mrázek
94d4684809 NOISSUE add basic unit tests for MojangVersionFormat reading/writing
will have to make them pass now
2016-03-03 01:40:12 +01:00
Petr Mrázek
b54839b897 NOISSUE eliminate timestamp strings 2016-03-02 09:16:58 +01:00
Petr Mrázek
80b81c2c1e SCRATCH some version file member variables commented 2016-03-01 09:47:12 +01:00
Petr Mrázek
f53cd55fbb NOISSUE bump version number and update changelog for next release 2016-02-29 09:08:35 +01:00
Petr Mrázek
a3cd3d5ff1 NOISSUE update changelog 2016-02-28 20:08:59 +01:00
Petr Mrázek
1a9793197f GH-1502 move launch script generation to the Minecraft launch step 2016-02-28 19:33:05 +01:00
Petr Mrázek
9497b7e96c NOISSUE even more version file refactors
There is no end to them in sight
2016-02-28 19:01:54 +01:00
Petr Mrázek
a0b47aee5b NOISSUE move version file reading and writing to dedicated namespaces 2016-02-27 22:02:56 +01:00
Petr Mrázek
17ad1e64f8 NOISSUE move files into paths that make more sense 2016-02-27 19:58:40 +01:00
Petr Mrázek
71e4b147ec NOISSUE remove OneSixLibrary 2016-02-26 02:04:21 +01:00
Petr Mrázek
f6b2ccb110 NOISSUE remove old unused version file features 2016-02-25 00:29:50 +01:00
Petr Mrázek
c943019ab5 NOISSUE fix a benign leak in FTB implementation 2016-02-25 00:29:08 +01:00
Spencer Burris
fc43fd1105 NOISSUE Add issue template 2016-02-21 14:53:53 -08:00
Petr Mrázek
401d5b698f GH-1453 handle certain version loading corner cases better, clean up FTB 2016-02-21 05:51:36 +01:00
Petr Mrázek
1a0bbdd9ac GH-1453 report version file problems in the version page 2016-02-21 01:44:27 +01:00
Petr Mrázek
495d320ce2 Revert "Update libnbtplusplus with magical changes"
This reverts commit 6e6e2bf262.
2016-02-20 09:11:10 +01:00
Petr Mrázek
5e737f42bf GH-1410 use libc++ on OSX 2016-02-19 00:57:46 +01:00
Petr Mrázek
6e6e2bf262 Update libnbtplusplus with magical changes 2016-02-19 00:02:57 +01:00
Petr Mrázek
163a3095b1 GH-1453 separate out Mojang version reading, use version file URLs 2016-02-17 08:23:57 +01:00
Petr Mrázek
a20e2590da GH-1453 React to the minimum version change - 18 2016-02-13 17:34:27 +01:00
Petr Mrázek
1978078662 NOISSUE remove dead code from MC version list 2016-02-13 17:32:14 +01:00
Petr Mrázek
ea08ede4c3 GH-1483 Use the new version index URL 2016-02-13 16:41:26 +01:00
Petr Mrázek
b7f75637fa GH-1451 add make install step to OSX build instructions 2016-02-11 21:04:10 +01:00
Petr Mrázek
4ee1900201 Merge branch 'patch-1' of git://github.com/iarspider/MultiMC5 into develop 2016-02-03 19:24:51 +01:00
Petr Mrázek
ab67d763f4 NOISSUE bump release number 2016-02-03 19:22:55 +01:00
Petr Mrázek
7ca9f92343 GH-1422 bump version to 0.4.10 and update changelog 2016-01-22 02:00:20 +01:00
Petr Mrázek
cbd4b88e91 GH-1422 remove bearer plugins again. 2016-01-21 20:16:57 +01:00
Petr Mrázek
0958bb2fcc NOISSUE bump version number to 0.4.9 2016-01-21 01:28:39 +01:00
iarspider
fbec48080b NOISSUE Do not ask to overwrite existing file twice when exporting instances 2016-01-20 21:11:58 +03:00
Petr Mrázek
33b6222f9f NOISSUE update changelog 2016-01-20 04:08:29 +01:00
Petr Mrázek
5ecaed21b5 GH-1411 fail if pre-launch and post-exit commands return non-zero values 2016-01-20 03:23:19 +01:00
Petr Mrázek
9fd66b3bb1 GH-1362 Put timestamps into the log when it is copied or uploaded 2016-01-20 03:10:02 +01:00
Petr Mrázek
47ea2a71c0 GH-1408 add bearer plugins
This should fix wifi issues on Windows
2016-01-20 02:44:57 +01:00
Petr Mrázek
2c2b960ab4 GH-1055 fix more types in changelog 2016-01-17 14:43:51 +01:00
Petr Mrázek
ce326ccdff GH-1055 fix typo and missing description 2016-01-17 13:24:59 +01:00
Petr Mrázek
1ed86bfe1a GH-1055 update changelog for 0.4.8 2016-01-17 13:04:07 +01:00
Petr Mrázek
781e53cccb GH-1402 add a hack for updater to respect renamed binary on Windows 2016-01-12 06:52:29 +01:00
Petr Mrázek
25991c36af GH-1280 modpack import: make the progress dialog say what is being downloaded 2016-01-12 05:30:03 +01:00
Petr Mrázek
5ccfbba435 NOISSUE select modpack field content on focus in new instance dialog 2016-01-12 04:37:30 +01:00
Petr Mrázek
1f0e76a3c1 GH-1397 add discord icon to MultiMC toolbar 2016-01-09 01:39:51 +01:00
Petr Mrázek
d8b1ae38fb GH-1379 fix build on win32 2016-01-07 06:47:07 +01:00
Petr Mrázek
59e6b4ed55 GH-1379 fix build with Qt 5.2.1 on ubuntu64 2016-01-07 06:40:26 +01:00
Petr Mrázek
5ff9f90ce9 Merge pull request #1393 from MultiMC/feature/travis-older-qt
GH-1393 Add more qt versions to travis
2016-01-06 11:28:44 +01:00
Jan Dalheimer
34bf4ccdc7 NOISSUE Add more qt versions to travis
5.0, 5.1 and 5.2 are currently marked as "allow failure". If they can be made
to pass they should be removed from this list, if not they should be removed
entirely.
2016-01-06 10:33:47 +01:00
Petr Mrázek
aa8103adf2 GH-1390 improve linux runner script more
* use `-q` while calling dnf to avoid garbage in output
2016-01-05 08:50:47 +01:00
Petr Mrázek
b300c4956c GH-1390 improve linux runner script
* include fedora dnf package manager
* output of the missing dependency lookup is now passed through `sort -u`
2016-01-05 08:40:30 +01:00
Petr Mrázek
4d0caf6254 GH-1389 wrap QDesktopServices and QProcess::startDetached
Essentially do not pass some environment variables to subprocesses:
* LD_PRELOAD
* LD_LIBRARY_PATH
* LD_DEBUG
* QT_PLUGIN_PATH
* QT_FONTPATH
2016-01-05 07:32:52 +01:00
Petr Mrázek
d1e344f28f GH-1389 Revert "GH-1389 remove use of LD_LIBRARY_PATH for mmc libs"
This reverts commit 6f92ca843e.
2016-01-04 02:00:24 +01:00
Petr Mrázek
e0a9970d59 NOISSUE Revert "NOISSUE remove old BundleUtilities. 2014 called and wants its cmake scripts back."
This reverts commit 8cf23bd5aa.
2016-01-04 01:42:48 +01:00
Petr Mrázek
6f92ca843e GH-1389 remove use of LD_LIBRARY_PATH for mmc libs 2016-01-04 01:37:46 +01:00
Petr Mrázek
8cf23bd5aa NOISSUE remove old BundleUtilities. 2014 called and wants its cmake scripts back. 2016-01-03 22:49:31 +01:00
Petr Mrázek
c6afa7d73e GH-1378 fix libpng path matcher for bundle fixup 2016-01-03 16:04:26 +01:00
Petr Mrázek
dcb4e0fa6f GH-1313 tweak the window title to be easier to translate 2016-01-03 16:03:49 +01:00
Petr Mrázek
15aaded80b GH-1313 remove or disable some translateable strings 2016-01-03 03:15:12 +01:00
Petr Mrázek
b9b5a82c2e GH-1313 remove translatable strings from MCModInfoFrame 2016-01-02 04:01:00 +01:00
Petr Mrázek
da2af5e449 GH-1365 fix java detection build on windows 2016-01-02 01:16:44 +01:00
Petr Mrázek
1363b1d364 GH-1365 fix java detection OS ifdefs 2016-01-02 01:13:42 +01:00
Petr Mrázek
a008efd24e GH-1365 rework java version parsing and sorting 2016-01-02 00:35:54 +01:00
Petr Mrázek
5f57df8110 GH-1365 Revert "GH-1365 use the first part of the java version number as the major version - native extraction"
This reverts commit b437988d7b.
2015-12-30 14:24:56 +01:00
Petr Mrázek
b437988d7b GH-1365 use the first part of the java version number as the major version - native extraction 2015-12-28 19:06:03 +01:00
Petr Mrázek
07449e514a GH-1360 fix some typos 2015-12-28 06:00:36 +01:00
Petr Mrázek
bd2843952a NOISSUE export more stuff from Json 2015-12-28 05:47:11 +01:00
Petr Mrázek
5402acb3c6 GH-1360 add basic changelog based on github API, fix update dialog buttons 2015-12-28 05:36:17 +01:00
Petr Mrázek
e8063d193d GH-1308 remove use of static data (translations) and root (notifications.json) paths. 2015-12-27 03:34:03 +01:00
Petr Mrázek
7670d72bd9 GH-1178 sanitize mod paths while installing folder mods 2015-12-26 03:20:41 +01:00
Petr Mrázek
c64a7940c1 GH-1178 add failing test 2015-12-26 03:20:19 +01:00
Petr Mrázek
243c5d1cfb NOISSUE add a basic test for FS::copy 2015-12-26 02:44:33 +01:00
Petr Mrázek
478ff11485 GH-1355 do not allow setting LD_LIBRARY_PATh for Minecraft to the MultiMC bin folder 2015-12-18 05:43:44 +01:00
Soni L
2db4a595dd GH-1355 Fix MMC env propagating to MC after update
This closes GH-1355
2015-12-17 19:38:14 -02:00
Petr Mrázek
2da3162206 GH-1320 do not fail when launcher part can't change sys_paths 2015-12-03 23:27:26 +01:00
Petr Mrázek
a5b8f22eab GH-1339 do not destroy console window while screenshot upload is active 2015-12-03 23:00:51 +01:00
Petr Mrázek
b5902b739e GH-1338: mark asset index as stale during instance update
This forces an update for assets changing on mojang servers
2015-11-19 22:20:40 +01:00
Petr Mrázek
11afc61426 GH-1322 fix mod description ... button popping up multiple dialogs 2015-11-13 00:50:38 +01:00
Petr Mrázek
384c03c9c5 NOISSUE travis: just force it to work. 2015-11-13 00:32:23 +01:00
Petr Mrázek
21490a42bd Revert "NOISSUE travis: use a ppa for cmake 3.2.3"
This reverts commit d855f4905d.
2015-11-13 00:30:40 +01:00
Petr Mrázek
d855f4905d NOISSUE travis: use a ppa for cmake 3.2.3 2015-11-13 00:24:07 +01:00
Petr Mrázek
12c7b11fe6 NOISSUE fix bad patch.exe link and formatting in BUILD document 2015-11-13 00:14:12 +01:00
Petr Mrázek
055774dd58 NOISSUE reword and reformat the README 2015-11-09 00:27:57 +01:00
Petr Mrázek
fdbe431d6b NOISSUE update versions in build how-to 2015-11-09 00:27:24 +01:00
Petr Mrázek
9c01b2294f GH-1319 add patch.exe mention to the build how-to 2015-11-09 00:24:43 +01:00
Petr Mrázek
895d8ab469 GH-1300 call application quit when direct launch instance quits 2015-10-24 00:57:54 +02:00
Petr Mrázek
8a4fd8c468 GH-1301 fix linux runner script argument escaping 2015-10-23 20:01:33 +02:00
Petr Mrázek
61ad480588 NOISSUE update travis to use Qt 5.5.1 2015-10-20 17:42:22 +02:00
Petr Mrázek
79ae4ef2f7 NOISSUE reformat MainWindow with new clang_format settings 2015-10-20 17:22:13 +02:00
Petr Mrázek
125abf5027 NOISSUE rename QObjectPtr to shared_qobject_ptr, introduce unique_qobject_ptr, refactor MainWindow to match 2015-10-20 17:18:53 +02:00
Petr Mrázek
9ad99ac481 NOISSUE raise formatting column limit to 160 2015-10-20 17:02:12 +02:00
Petr Mrázek
69989ab54e GH-1274 update the licenses, the dirty way 2015-10-20 01:50:29 +02:00
Petr Mrázek
7ef1f88de7 NOISSUE fix non-zero exit code from minecraft not being a 'crash' 2015-10-18 02:35:47 +02:00
Petr Mrázek
432e812da1 GH-1275 create server-resource-packs folder on launch
This is a workaround for Minecraft bug MCL-3732
2015-10-12 17:55:10 +02:00
Petr Mrázek
d5aee5fd23 NOISSUE maybe less evil... 2015-10-11 20:06:46 +02:00
Petr Mrázek
457dd2e94e NOISSUE make the compiler more evil 2015-10-11 19:56:31 +02:00
Petr Mrázek
44db72ead5 GH-93 add an option to not copy saves on instance copy 2015-10-10 05:55:55 +02:00
Petr Mrázek
4fbcb3efb9 GH-1268 ... and catch the inevitable errors 2015-10-05 23:52:23 +02:00
Petr Mrázek
439c6b43a3 GH-1268 simplify and fix instance group file IO 2015-10-05 23:48:38 +02:00
Petr Mrázek
db926a546e NOISSUE there is too much ifdef involved... 2015-10-05 02:00:03 +02:00
Petr Mrázek
4a900a58d4 NOISSUE missed a few places... 2015-10-05 01:53:09 +02:00
Petr Mrázek
f93f867c3d NOISSUE dissolve util library 2015-10-05 01:47:27 +02:00
Petr Mrázek
7459eb627c GH-1266 fix ubuntu run script 2015-10-02 23:06:22 +02:00
Petr Mrázek
ae4216de61 GH-719 implement paste.ee API keys 2015-10-02 00:12:53 +02:00
Petr Mrázek
ac8ff88061 GH-729 use mod mmc_id as name when name is empty 2015-09-30 23:30:55 +02:00
Petr Mrázek
477a1a88c6 GH-1262 fix relative paths for java binaries 2015-09-30 22:52:55 +02:00
Petr Mrázek
cf0308c970 GH-1263 update build instructions 2015-09-30 22:00:31 +02:00
Petr Mrázek
e2fd299fc5 GH-253 implement launching instances from command line 2015-09-30 00:11:00 +02:00
Petr Mrázek
e993b1152d GH-1202 rebuild SSL certs on start on OSX - part 4 2015-09-29 01:42:45 +02:00
Petr Mrázek
877240524d GH-1202 rebuild SSL certs on start on OSX - part 3 2015-09-29 01:21:04 +02:00
Petr Mrázek
b7ff8a4c1c GH-1202 rebuild SSL certs on start on OSX - part 2 2015-09-29 01:06:26 +02:00
Petr Mrázek
22c0d5cf46 GH-1202 rebuild SSL certs on start on OSX 2015-09-29 00:49:54 +02:00
Petr Mrázek
12b14c3400 GH-1179 incorporate fixes for comments from linked changeset
Use SSL for downloads
Use XDG dirs for storage
Do not run from deploy function
2015-09-28 23:28:40 +02:00
Petr Mrázek
00994a425e GH-1238 add reddit button 2015-09-28 22:47:02 +02:00
Petr Mrázek
ccb5fc6f4a GH-1072 use crafatar for grabbing the user skin 2015-09-28 22:43:57 +02:00
Petr Mrázek
1cbe543b39 NOISSUE and even more: forgot to remove export from IconResourceHandler 2015-09-28 21:28:46 +02:00
Petr Mrázek
260a2cea59 NOISSUE more cmake tweakery 2015-09-28 21:20:27 +02:00
Petr Mrázek
143e24fa04 NOISSUE clean up some old cmake messes 2015-09-28 20:53:46 +02:00
Petr Mrázek
33c3850b40 NOISSUE add missing files 2015-09-27 22:31:52 +02:00
Petr Mrázek
271ad9e4fd GH-1072 split resource system to UI and logic parts 2015-09-26 13:45:29 +02:00
Petr Mrázek
cca6700134 NOISSUE fix all clang warnings 2015-09-26 04:04:09 +02:00
Petr Mrázek
0af04dc060 NOISSUE attempt to fix NBT lib options not applying 2015-09-26 01:22:37 +02:00
Petr Mrázek
e4df8165f7 NOISSUE and even more 2015-09-26 00:44:52 +02:00
Petr Mrázek
1ab26ef2ad NOISSUE fix travis not notifying IRC, again 2015-09-26 00:39:24 +02:00
Petr Mrázek
5d5bee4992 GH-1238 re-integrate nbt library 2015-09-23 01:21:19 +02:00
Petr Mrázek
e60a652b78 GH-1217 reset time played on zip pack import 2015-09-22 01:25:34 +02:00
Petr Mrázek
9ba1cd15e7 GH-1217 add simple instance play time tracking
Not reliable in the face of crashes... but what is?
2015-09-22 01:06:45 +02:00
Petr Mrázek
b107617112 GH-1121 select instance after creating it 2015-09-16 00:21:50 +02:00
Petr Mrázek
0a187d0ad3 GH-1227 protect world from corruption 2015-09-15 22:51:10 +02:00
Petr Mrázek
8d3f13c447 GH-1227 add world copy and rename 2015-09-14 23:49:32 +02:00
Petr Mrázek
dd8eacee1b GH-1227 renam GZip functions to not collide with zlib macros 2015-09-14 02:36:03 +02:00
Petr Mrázek
e38cc1d480 GH-1227 add GZip compress function and a unit test fo GZip 2015-09-14 02:25:47 +02:00
Petr Mrázek
cfd5976471 GH-1227 display some messages when MCEdit isn't setup or fails 2015-09-14 02:23:40 +02:00
Petr Mrázek
8ef07ec634 GH-1227 allow structured world zip import and drag and drop out of MultiMC 2015-09-13 04:21:26 +02:00
Petr Mrázek
2315f463a8 GH-1237 make mod info clickable and selectable 2015-09-12 03:08:36 +02:00
Petr Mrázek
38901ed21d NOISSUE use whole zip base filename for default instance name 2015-09-12 03:07:41 +02:00
Petr Mrázek
ec3472f21d GH-1232 try to export the primitive tag template instantiations explicitly 2015-09-10 08:39:41 +02:00
Petr Mrázek
bd96a25f7a Revert "GH-1232 attempt to fix reading NBT longs on OSX"
This reverts commit 877fc94f50.
2015-09-10 00:41:12 +02:00
Petr Mrázek
877fc94f50 GH-1232 attempt to fix reading NBT longs on OSX
EXPORT ALL THE THINGS
2015-09-10 00:16:33 +02:00
Petr Mrázek
db5816b0a2 GH-1227 fix zlib nonsense on Windows 2015-09-10 00:02:02 +02:00
Petr Mrázek
a1fd50e920 GH-1227: World import using drag and drop - zip files and folders 2015-09-09 23:53:33 +02:00
Petr Mrázek
51070a13f7 GH-1231 add libpng to packages 2015-09-08 22:09:08 +02:00
Petr Mrázek
36dbf1fb43 GH-1233 do not load worlds when not needed 2015-09-08 21:22:23 +02:00
Petr Mrázek
1ca9fc8961 NOISSUE catch more errors from nbt lib 2015-09-08 09:28:14 +02:00
Petr Mrázek
b8cdcdb96b GH-1047 build fixes 2015-09-06 23:46:38 +02:00
Petr Mrázek
38693e1d6c GH-1047 parse world files and integrate MCEdit with world page 2015-09-06 23:35:58 +02:00
Petr Mrázek
40b233448c Use default Yes/No buttons for confirmation 2015-09-06 16:00:07 +02:00
Petr Mrázek
7d8c71aad8 Just use an oxygen icon for the worlds folder... 2015-09-06 16:00:07 +02:00
Alex
498dc8fc03 Add confirmation dialog for world deletion 2015-09-06 16:00:07 +02:00
Petr Mrázek
c3480d6fe4 Icon 2015-09-06 16:00:07 +02:00
Alex
b5d5490714 Copyright fixes for new code 2015-09-06 16:00:07 +02:00
Alex
83434a9be5 Comment changes and general cleanup 2015-09-06 16:00:07 +02:00
Alex
583e5946f4 GH-1047 World management for instances. Removal only currently. 2015-09-06 16:00:07 +02:00
Petr Mrázek
16df6c16f3 Merge pull request #1225 from iambob314/patch-1
Fixed overwriting of wrapper command
2015-09-06 07:26:11 +02:00
iambob314
6148023ad6 Fixed overwriting of wrapper command
Fixed "WrapperCommand" setting being overwritten by the value of "PreLaunchCommand".
2015-09-05 19:39:13 -04:00
Petr Mrázek
6496c65285 SCRATCH do not export the pure template 2015-09-05 19:23:46 +02:00
Petr Mrázek
db5e55e026 SCRATCH NetAction fix 2015-09-05 19:10:03 +02:00
Petr Mrázek
23d0bd8edd NOISSUE make shared logic library ... shared 2015-09-05 18:46:57 +02:00
Petr Mrázek
cd108fd029 GH-1223 fix override settings
They now work more like passthrough settings, except not passing through set and reset
2015-09-04 02:10:29 +02:00
Petr Mrázek
151a0ca11e GH-1124 tell user which java path is wrong. 2015-08-24 09:38:05 +02:00
Petr Mrázek
bc917668ff GH-1133 fix bad java path detection some more 2015-08-24 00:56:45 +02:00
Petr Mrázek
961c1c61b8 GH-1206 fix deleting files during update
Backups weren't created properly which led to failure to update
2015-08-23 22:33:59 +02:00
Petr Mrázek
0d15247247 NOISSUE remoce the old WM_CLASS workaround 2015-08-23 16:05:53 +02:00
Petr Mrázek
b6ec2ac4b0 GH-1140 mark cached modpack dls as stale so it checks the server 2015-08-22 00:52:50 +02:00
Petr Mrázek
c5bb33c716 GH-1158 generate client uuid for yggdrasil auth 2015-08-22 00:42:40 +02:00
Petr Mrázek
40ed2654c7 GH-1148 New instance name is either version or modpack 'base name'
Default names now use the placeholder text in the new instance dialog.
2015-08-21 09:00:35 +02:00
Petr Mrázek
875c707358 NOISSUE fix librainbow some more 2015-08-21 07:40:39 +02:00
Mrazek, Petr
e5f7676622 NOISSUE fix librainbow 2015-08-20 15:27:51 +02:00
Mrazek, Petr
cc4d0a0a8e GH-1149 add irc notification to travis 2015-08-20 12:29:33 +02:00
Petr Mrázek
d0e88011dc GH-1197 finish color stuff 2015-08-20 01:49:03 +02:00
Petr Mrázek
6858f1dd62 GH-1197 add console log color adaptation
rainbow library was part of KDE - KGuiAddons
2015-08-19 23:52:53 +02:00
Petr Mrázek
9681f724e5 NOISSUE revamp the minecraft log exception detection 2015-08-19 23:50:36 +02:00
Petr Mrázek
5bc29b06a9 NOISSUE fix log-related legacy instance crash and show hidden log files 2015-08-19 02:04:56 +02:00
Petr Mrázek
96fdaebb5c GH-926 implement log cleaning functionality
Also adds gzip compressed log support
2015-08-18 08:51:12 +02:00
Petr Mrázek
4e3af265da GH-1164 make sure the censor filter never contains empty keys 2015-08-16 02:17:50 +02:00
Petr Mrázek
d7b3887fe1 Revert "NOISSUE redo the launcher part"
This reverts commit c1f7dda8fe.
2015-08-14 23:30:12 +02:00
Petr Mrázek
0adb572a07 NOISSUE improve account UI 2015-08-14 02:27:01 +02:00
Petr Mrázek
8ed10c5b81 NOISSUE fix build on windows - pid -> processId 2015-08-14 01:01:50 +02:00
Petr Mrázek
d8caab515a GH-1053 add back update progress dialog 2015-07-26 17:55:29 +02:00
Petr Mrázek
6310f6569c GH-1053 move guessLevel to instances 2015-07-22 09:01:04 +02:00
Petr Mrázek
2fc18921b0 GH-1053 add launch step creation to legacy instances 2015-07-21 09:21:59 +02:00
Petr Mrázek
61c5a67777 GH-1053 explode launch task into many small steps, each a Task 2015-07-21 02:38:15 +02:00
Petr Mrázek
8e7caf4e25 GH-1053 move launch related things and rename them 2015-07-10 01:11:06 +02:00
Petr Mrázek
5dd48e89f5 GH-1034 do jar modding separate from update 2015-07-10 00:06:05 +02:00
Petr Mrázek
5133b0f34f GH-1053 cleanup 2015-07-05 02:47:22 +02:00
Petr Mrázek
5f41886d76 GH-1053 split settings dialog creation to its own namespace 2015-07-05 02:29:41 +02:00
Petr Mrázek
7f1320390c GH-1053 move launch process UI to a separate class 2015-07-05 01:54:30 +02:00
Petr Mrázek
526a511f45 GH-1053 move instance update into the launch task (BaseLauncher) 2015-07-04 20:02:43 +02:00
Petr Mrázek
5628d3d379 SCRATCH squash MinecraftLauncher into BaseLauncher
needs to be split differently
needs to be squashed together with the logic from MainWindow
2015-06-30 07:16:20 +02:00
Petr Mrázek
f86a39c21c SCRATCH fix BaseLauncher 2015-06-30 07:16:20 +02:00
Petr Mrázek
34ddfc7ecc GH-1053 base process and launch refactor, part 1 2015-06-30 07:16:20 +02:00
Jan Dalheimer
d14a61b0df GH-1100 Fix issues with LD_* variables when restarting on updates 2015-06-29 20:22:04 +02:00
Petr Mrázek
bbba63eca5 GH-1096 make ubuntu package work on both 32bit and 64bit machines 2015-06-28 22:44:53 +02:00
Petr Mrázek
d403d12d6a GH-1096 simple debian/ubuntu wrapper package
Built with `fakeroot dpkg-deb --build multimc_1.0-1`
2015-06-28 11:25:32 +02:00
Petr Mrázek
b343434f99 GH-1068 update changelog 2015-06-13 02:22:12 +02:00
Petr Mrázek
f723721bd0 GH-1069 env hack/passthhrough for LD_PRELOAD and LD_LIBRARY_PATH 2015-06-12 09:40:41 +02:00
Petr Mrázek
b427a652ad GH-1009 use .sh instead of .pyc - .pyc doesn't work at all 2015-06-11 02:33:02 +02:00
Petr Mrázek
9684d3b0a0 GH-1008 implement log window max line count
Defaults to 100k lines
2015-06-11 01:50:20 +02:00
Petr Mrázek
1feb4bb387 GH-1009 add mcedit.pyc as a valid mcedit 'executable' 2015-06-10 23:51:05 +02:00
Petr Mrázek
dd97ea8029 GH-1060 ugly XP hack is ugly 2015-06-10 03:06:29 +02:00
Petr Mrázek
88f5c8d347 GH-1060 create and delete update dir 2015-06-10 00:46:45 +02:00
Petr Mrázek
15b7c3039a GH-1060 update tweaks
* download to multimc folder hierarchy
* use rename, not copy
* keep backup after update
* clean previous backup before update
* it's not 'copy', it's 'replace'
2015-06-09 23:30:28 +02:00
Petr Mrázek
22c5ced5dc GH-1060 add a lot of error checking and reporting to the inner updater 2015-06-09 20:58:19 +02:00
Petr Mrázek
64b70acac1 GH-1060 tweaks to new update mechanism - logging 2015-06-09 00:48:25 +02:00
Petr Mrázek
82e05661d2 GH-1060 implement very basic updater (only linux and maybe osx right now) 2015-06-09 00:03:42 +02:00
Petr Mrázek
166813cb91 GH-1060 remove some old updater bits and pieces 2015-06-09 00:03:42 +02:00
Petr Mrázek
38e42ad794 GH-1049 fix bad ifdefs that prevent linux-specific env blacklisting 2015-06-08 23:54:30 +02:00
Petr Mrázek
6d7bff2476 GH-1060 remove updater code 2015-06-07 21:10:18 +02:00
Petr Mrázek
977e11ef8d GH-1051 ignore CDPATH 2015-06-06 23:40:13 +02:00
Jan Dalheimer
634bdcdbcb GH-1033 Set up travis for C++14 setup
No clang, no OSX, nothing
2015-06-06 23:27:58 +02:00
Jan Dalheimer
1e51b62c88 NOISSUE Comment and bugfix the Resource system 2015-06-06 21:23:05 +02:00
Petr Mrázek
24db645167 NOISSUE sanitize Json
Removes magical parameter madness.
All require* can throw
All ensure* need a default value and never throw
2015-06-06 21:23:05 +02:00
Petr Mrázek
dde35a0eb8 NOISSUE remove StandardTask 2015-06-06 21:23:05 +02:00
Petr Mrázek
57b75dfcf7 NOISSUE document exceptions a bit more 2015-06-06 21:23:05 +02:00
Petr Mrázek
06a67fbd38 NOISSUE use FS a bit more 2015-06-06 21:23:05 +02:00
Jan Dalheimer
3a8b238052 NOISSUE Various changes from multiauth that are unrelated to it 2015-06-06 21:23:05 +02:00
Petr Mrázek
161dc66c2c GH-1052 try using c++1y on OSX 2015-06-06 21:00:37 +02:00
Petr Mrázek
678da0b639 GH-1052 switch over to C++14 everywhere 2015-06-06 19:56:51 +02:00
Jan Dalheimer
db69a3dacd NOISSUE Don't attempt to package the accessible plugins on Qt >= 5.4 2015-06-06 15:10:19 +02:00
Petr Mrázek
47f919173e NOISSUE begin working on 0.4.8 and update changelog 2015-06-02 01:11:31 +02:00
Alex
c1f7dda8fe NOISSUE redo the launcher part 2015-06-02 00:11:09 +02:00
1239 changed files with 88258 additions and 110211 deletions

View File

@@ -1,5 +1,5 @@
{
"project_id": "MultiMC5",
"conduit_uri": "http://ph.multimc.org"
"project_id": "MultiMC5",
"conduit_uri": "http://ph.multimc.org"
}

View File

@@ -1,4 +1,4 @@
UseTab: true
UseTab: false
IndentWidth: 4
TabWidth: 4
ConstructorInitializerIndentWidth: 4
@@ -10,7 +10,7 @@ NamespaceIndentation: None
BreakBeforeBraces: Allman
AllowShortIfStatementsOnASingleLine: false
AllowShortFunctionsOnASingleLine: None
ColumnLimit: 96
ColumnLimit: 160
MaxEmptyLinesToKeep: 1
Standard: Cpp11

1
.gitattributes vendored
View File

@@ -1 +1,2 @@
*.pem -crlf
**/testdata/** -text -diff

51
.github/ISSUE_TEMPLATE.md vendored Normal file
View File

@@ -0,0 +1,51 @@
<!--
Before submitting this issue, please make sure you have:
1. Filled out this form completely, the only optional field is "additional info".
- Use as many details as possible and state the problem clearly.
2. Proof-read your ENTIRE issue report.
- Grammar and spelling mistakes make issue reports harder to understand.
3. Made sure your problem is not caused by an issue in your own modpack.
- We provide support for MultiMC, not your modpack. Problems with your modpack will be ignored.
4. Given the issue a descriptive title.
- A good title includes a brief summary of the issue and avoids things such as "Help" and "What?!".
Use of UPPERCASE is discouraged, as it reads like someone is screaming.
5. Place all information below the ---- of lines.
- It makes the issue look pretty
If you believe your issue to be a bug, please make sure you check the wiki page: https://github.com/MultiMC/MultiMC5/wiki/Report-a-Bug
-->
System Information
-----------------------------
MultiMC version:
Operating System:
Summary of the issue or suggestion:
----------------------------------------------
What should happen:
------------------------------
Steps to reproduce the issue (Add more if needed):
-------------------------------------------------------------
1.
2.
3.
Suspected cause:
---------------------------
Logs/Screenshots:
----------------------------
[//]: # (Please refer to https://github.com/MultiMC/MultiMC5/wiki/Log-Upload for instructions on how to attach your logs.)
Additional Info:
---------------------------

2
.gitignore vendored
View File

@@ -15,6 +15,8 @@ CMakeLists.txt.user
CMakeLists.txt.user.*
/.project
/.settings
/.idea
cmake-build-*/
# Build dirs
build

6
.gitmodules vendored Normal file
View File

@@ -0,0 +1,6 @@
[submodule "depends/libnbtplusplus"]
path = libraries/libnbtplusplus
url = https://github.com/MultiMC/libnbtplusplus.git
[submodule "libraries/quazip"]
path = libraries/quazip
url = https://github.com/MultiMC/quazip.git

View File

@@ -1,23 +1,38 @@
# General set up
language: cpp
compiler:
- gcc
- clang
cache: apt
before_install:
- sudo apt-add-repository -y ppa:beineri/opt-qt532
- sudo apt-add-repository -y ppa:kalakris/cmake
- sudo add-apt-repository -y ppa:ubuntu-toolchain-r/test
- sudo apt-get update -qq
matrix:
include:
- os: linux
dist: precise
sudo: required
compiler: gcc
env: TRAVIS_DIST=precise QT_VERSION=5.4.2
- os: linux
dist: precise
sudo: required
compiler: gcc
env: TRAVIS_DIST=precise QT_VERSION=5.6.2
- os: linux
dist: trusty
sudo: required
compiler: gcc
env: TRAVIS_DIST=trusty QT_VERSION=5.4.2
- os: linux
dist: trusty
sudo: required
compiler: gcc
env: TRAVIS_DIST=trusty QT_VERSION=5.6.2
# Install dependencies
install:
- sudo apt-get install -y -qq cmake qt53base qt53svg qt53tools qt53x11extras qt53webkit
- sudo apt-get install -y -qq g++-4.8
- if [ "$CXX" = "g++" ]; then export CXX="g++-4.8" CC="gcc-4.8"; fi
- source travis/prepare.sh # installs qt and cmake. need to source because some env vars are set from there
# Actual work
before_script:
- mkdir build
- cd build
- cmake -DCMAKE_PREFIX_PATH=/opt/qt53/lib/cmake ..
- cmake -DCMAKE_PREFIX_PATH=$CMAKE_PREFIX_PATH ..
script:
- make -j4
- make test ARGS="-V"
notifications:
email: false
- make -j4 && make test ARGS="-V"

164
BUILD.md
View File

@@ -2,7 +2,9 @@ Build Instructions
==================
# Contents
* [Note](#note)
* [Getting the source](#source)
* [Linux](#linux)
* [Windows](#windows)
* [OS X](#os-x)
@@ -14,60 +16,90 @@ That would be anything outside your home folder. Before runing `make install`, m
you set the install path to something you have write access to. Never build this under
an administrator/root level account. Don't use `sudo`. It won't work and it's not supposed to work.
# Getting the source
Clone the source code using git and grab all the submodules:
```
git clone git@github.com:MultiMC/MultiMC5.git
git submodule init
git submodule update
```
# Linux
Getting the project to build and run on Linux is easy if you use Ubuntu 13.10 (or 13.04) and Qt's IDE, Qt Creator.
Getting the project to build and run on Linux is easy if you use any modern and up-to-date linux distribution.
## Dependencies
* Qt 5.1.1+ Development tools (http://qt-project.org/downloads) ("Qt Online Installer for Linux (64 bit)")
* A copy of the MultiMC source (clone it with git)
* cmake
* build-essential
* zlib (for example, zlib1g-dev)
* java (for example, openjdk-7-jdk)
* GL headers (for example, libgl1-mesa-dev)
## Build dependencies
* A C++ compiler capable of building C++11 code.
* Qt 5.6+ Development tools (http://qt-project.org/downloads) ("Qt Online Installer for Linux (64 bit)") or the equivalent from your package manager. It is always better to use the Qt from your distribution, as long as it has a new enough version.
* cmake 3.1 or newer
* zlib (for example, `zlib1g-dev`)
* Java JDK 8 (for example, `openjdk-8-jdk`)
* GL headers (for example, `libgl1-mesa-dev`)
## Getting set up
### Building from command line
You need a source folder, a build folder and an install folder.
### Installing dependencies
Just run `sudo apt-get install <dependency>` for each dependency (other than Qt and the MultiMC source) from above.
Let's say you want everything in `~/MultiMC/`:
### Installing Qt
1. Run the Qt installer
2. Choose a place to install Qt,
3. Choose the components you want to install
- You need Qt 5.1.1/gcc 64-bit ticked,
- You need Tools/Qt Creator ticked,
```
# make all the folders
mkdir ~/MultiMC && cd ~/MultiMC
mkdir build
mkdir install
# clone the complete source
git clone --recursive git@github.com:MultiMC/MultiMC5.git src
# configure the project
cd build
cmake -DCMAKE_INSTALL_PREFIX=../install ../src
# build & install (use -j with the number of cores your CPU has)
make -j8 install
```
You can use IDEs like KDevelop or QtCreator to open the CMake project if you want to work on the code.
### Installing Qt using the installer (optional)
1. Run the Qt installer.
2. Choose a place to install Qt.
3. Choose the components you want to install.
- You need Qt 5.6.x 64-bit ticked.
- You need Tools/Qt Creator ticked.
- Other components are selected by default, you can untick them if you don't need them.
4. Accept the license agreements,
5. Double check the install details and then click "Install"
4. Accept the license agreements.
5. Double check the install details and then click "Install".
- Installation can take a very long time, go grab a cup of tea or something and let it work.
### Loading the project
1. Open Qt Creator,
2. Choose File->Open File or Project,
3. Navigate to the MultiMC5 source folder you cloned and choose CMakeLists.txt,
4. Read the instructions that just popped up about a build location and choose one,
5. You should see "Run CMake" in the window,
- Make sure that Generator is set to "Unix Generator (Desktop Qt 5.1.1 GCC 64bit)",
- Hit the "Run CMake" button,
### Loading the project in Qt Creator (optional)
1. Open Qt Creator.
2. Choose `File->Open File or Project`.
3. Navigate to the MultiMC5 source folder you cloned and choose CMakeLists.txt.
4. Read the instructions that just popped up about a build location and choose one.
5. You should see "Run CMake" in the window.
- Make sure that Generator is set to "Unix Generator (Desktop Qt 5.6.x GCC 64bit)".
- Hit the "Run CMake" button.
- You'll see warnings and it might not be clear that it succeeded until you scroll to the bottom of the window.
- Hit "Finish" if CMake ran successfully.
6. Cross your fingers and press the Run button (bottom left of Qt Creator)!
6. Cross your fingers and press the Run button (bottom left of Qt Creator).
- If the project builds successfully it will run and the MultiMC5 window will pop up.
*These build instructions worked for me (Drayshak) on a fresh Ubuntu 13.10 x64 install. If they don't work for you, let us know on IRC (Esper/#MultiMC)!*
**If this doesn't work for you, let us know on IRC ([Esper/#MultiMC](http://webchat.esper.net/?nick=&channels=MultiMC))!**
# Windows
Getting the project to build and run on Windows is easy if you use Qt's IDE, Qt Creator. The project will simply not compile using VC's build tools as it uses some C++11 features that aren't implemented in it at the time of writing.
Getting the project to build and run on Windows is easy if you use Qt's IDE, Qt Creator. The project will simply not compile using Microsoft build tools, because that's not something we do. If it does compile, it is by chance only.
## Dependencies
* Qt 5.1.1+ Development tools (http://qt-project.org/downloads) ("Qt Online Installer for Windows")
* OpenSSL (http://slproweb.com/products/Win32OpenSSL.html) ("Win32 OpenSSL \<version\> Light")
- Microsoft Visual C++ 2008 Redist. is required for this, there's a link on the OpenSSL download page above next to the main download.
* CMake (http://www.cmake.org/cmake/resources/software.html) ("Windows (Win32 Installer)")
* A copy of the MultiMC source (clone it with git)
* [Qt 5.6+ Development tools](http://qt-project.org/downloads) -- Qt Online Installer for Windows
* [OpenSSL](http://slproweb.com/products/Win32OpenSSL.html) -- Newest Win32 OpenSSL Light
- Microsoft Visual C++ 2008 Redist is required for this, there's a link on the OpenSSL download page above next to the main download.
- We use a custom build of OpenSSL that doesn't have this dependency. For normal development, the custom build is not necessary though.
* [zlib 1.2+](http://gnuwin32.sourceforge.net/packages/zlib.htm) - the Setup is fine
* [Java JDK 8](http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html)
* [CMake](http://www.cmake.org/cmake/resources/software.html) -- Windows (Win32 Installer)
Put it somewhere on the `PATH`, so that it is accessible from the console.
## Getting set up
@@ -75,7 +107,7 @@ Getting the project to build and run on Windows is easy if you use Qt's IDE, Qt
1. Run the Qt installer
2. Choose a place to install Qt (C:\Qt is the default),
3. Choose the components you want to install
- You need Qt 5.1.1/MinGW 4.8 (32 bit) ticked,
- You need Qt 5.6 (32 bit) ticked,
- You need Tools/Qt Creator ticked,
- Other components are selected by default, you can untick them if you don't need them.
4. Accept the license agreements,
@@ -84,8 +116,8 @@ Getting the project to build and run on Windows is easy if you use Qt's IDE, Qt
### Installing OpenSSL
1. Run the OpenSSL installer,
2. It's best to choose the option to copy OpenSSL DLLs to the /bin directory
- If you do this you'll need to add that directory (the default being C:\OpenSSL-Win32\bin) to your PATH system variable (Google how to do this, or use this guide for Java: http://www.java.com/en/download/help/path.xml).
2. It's best to choose the option to copy OpenSSL DLLs to the `/bin` directory
- If you do this you'll need to add that directory (the default being `C:\OpenSSL-Win32\bin`) to your PATH system variable (Google how to do this, or use this guide for Java: http://www.java.com/en/download/help/path.xml).
### Installing CMake
1. Run the CMake installer,
@@ -100,7 +132,7 @@ Getting the project to build and run on Windows is easy if you use Qt's IDE, Qt
5. If you chose not to add CMake to the system PATH, tell Qt Creator where you installed it,
- Otherwise you can skip this step.
6. You should see "Run CMake" in the window,
- Make sure that Generator is set to "MinGW Generator (Desktop Qt 5.1.1 MinGW 32bit)",
- Make sure that Generator is set to "MinGW Generator (Desktop Qt 5.6.x MinGW 32bit)",
- Hit the "Run CMake" button,
- You'll see warnings and it might not be clear that it succeeded until you scroll to the bottom of the window.
- Hit "Finish" if CMake ran successfully.
@@ -108,26 +140,46 @@ Getting the project to build and run on Windows is easy if you use Qt's IDE, Qt
- If the project builds successfully it will run and the MultiMC5 window will pop up,
- Test OpenSSL by making an instance and trying to log in. If Qt Creator couldn't find OpenSSL during the CMake stage, login will fail and you'll get an error.
*These build instructions worked for me (Drayshak) on a fresh Windows 8 x64 Professional install. If they don't work for you, let us know on IRC (Esper/#MultiMC)!*
**These build instructions worked for me (Drayshak) on a fresh Windows 8 x64 Professional install. If they don't work for you, let us know on IRC ([Esper/#MultiMC](http://webchat.esper.net/?nick=&channels=MultiMC))!**
### Compile from command line on Windows
1. If you installed Qt with the web installer, there should be a shortcut called `Qt 5.4 for Desktop (MinGW 4.9 32-bit)` in the Start menu on Windows 7 and 10. Best way to find it is to search for it. Do note you cannot just use cmd.exe, you have to use the shortcut, otherwise the proper MinGW software will not be on the PATH.
2. Once that is open, change into your user directory, and clone MultiMC by doing `git clone --recursive https://github.com/MultiMC/MultiMC5.git`, and change directory to the folder you cloned to.
3. Make a build directory, and change directory to the directory and do `cmake -G "MinGW Makefiles" -DCMAKE_INSTALL_PREFIX=C:\Path\that\makes\sense\for\you`. By default, it will install to C:\Program Files (x86), which you might not want, if you want a local installation. If you want to install it to that directory, make sure to run the command window as administrator.
3. Do `mingw32-make -jX`, where X is the number of cores your CPU has plus one.
4. Now to wait for it to compile. This could take some time. Hopefully it compiles properly.
5. Run the command `mingw32-make install`, and it should install MultiMC, to whatever the `-DCMAKE_INSTALL_PREFIX` was.
6. In most cases, whenever compiling, the OpenSSL dll's aren't put into the directory to where MultiMC installs, meaning you cannot log in. The best way to fix this is just to do `copy C:\OpenSSL-Win32\*.dll C:\Where\you\installed\MultiMC\to`. This should copy the required OpenSSL dll's to log in.
# OS X
### Install prerequisites:
1. install homebrew
2. brew install qt5
3. brew tap homebrew/versions
4. brew install gcc48
5. brew install cmake
* install homebrew
* then:
```
brew install qt5
brew tap homebrew/versions
brew install gcc48
brew install cmake
```
### Build
1. git clone https://github.com/MultiMC/MultiMC5.git
2. cd MultiMC5
3. mkdir build
4. cd build
5. export CMAKE_PREFIX_PATH=/usr/local/opt/qt5
6. export CC=/usr/local/bin/gcc-4.8
7. export CXX=/usr/local/bin/g++-4.8
8. cmake ..
9. make
Pick an installation path - this is where the final `.app` will be constructed when you run `make install`. Supply it as the `CMAKE_INSTALL_PREFIX` argument during CMake configuration.
```
git clone https://github.com/MultiMC/MultiMC5.git
git submodule init
git submodule update
cd MultiMC5
mkdir build
cd build
export CMAKE_PREFIX_PATH=/usr/local/opt/qt5
export CC=/usr/local/bin/gcc-4.8
export CXX=/usr/local/bin/g++-4.8
cmake .. -DCMAKE_INSTALL_PREFIX:PATH=/Users/YOU/some/path/that/makes/sense/
make
make install
```
*These build instructions were taken and adapted from https://gist.github.com/number5/7250865 If they don't work for you, let us know on IRC (Esper/#MultiMC)!*
**These build instructions were taken and adapted from https://gist.github.com/number5/7250865 If they don't work for you, let us know on IRC ([Esper/#MultiMC](http://webchat.esper.net/?nick=&channels=MultiMC))!**

View File

@@ -1,44 +1,82 @@
cmake_minimum_required(VERSION 2.8.9)
cmake_minimum_required(VERSION 3.1)
string(COMPARE EQUAL "${CMAKE_SOURCE_DIR}" "${CMAKE_BUILD_DIR}" IS_IN_SOURCE_BUILD)
if(IS_IN_SOURCE_BUILD)
message(AUTHOR_WARNING "You are building MultiMC in-source. This is NOT recommended!")
message(AUTHOR_WARNING "You are building MultiMC in-source. This is NOT recommended!")
endif()
if(WIN32)
# In Qt 5.1+ we have our own main() function, don't autolink to qtmain on Windows
cmake_policy(SET CMP0020 OLD)
# In Qt 5.1+ we have our own main() function, don't autolink to qtmain on Windows
cmake_policy(SET CMP0020 OLD)
endif()
project(Megatron)
project(MultiMC)
enable_testing()
######## Set CMake options ########
##################################### Set CMake options #####################################
set(CMAKE_AUTOMOC ON)
set(CMAKE_INCLUDE_CURRENT_DIR ON)
######## Set module path ########
set(CMAKE_MODULE_PATH "${PROJECT_SOURCE_DIR}/cmake/")
set(MMC_SRC "${PROJECT_SOURCE_DIR}")
set(MMC_BIN "${PROJECT_BINARY_DIR}")
# Output all executables and shared libs in the main build folder, not in subfolders.
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR})
if(UNIX)
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR})
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR})
endif()
set(CMAKE_JAVA_TARGET_OUTPUT_DIR ${PROJECT_BINARY_DIR}/jars)
######## Set compiler flags ########
include(UseCXX11)
include(Coverage)
set(CMAKE_CXX_FLAGS " -Wall ${CMAKE_CXX_FLAGS}")
set(CMAKE_CXX_STANDARD_REQUIRED true)
set(CMAKE_C_STANDARD_REQUIRED true)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_C_STANDARD 11)
include(GenerateExportHeader)
set(CMAKE_CXX_FLAGS " -Wall -pedantic -Werror -D_GLIBCXX_USE_CXX11_ABI=0 -fstack-protector-strong --param=ssp-buffer-size=4 -O3 -D_FORTIFY_SOURCE=2 ${CMAKE_CXX_FLAGS}")
if(UNIX AND APPLE)
set(CMAKE_CXX_FLAGS " -stdlib=libc++ ${CMAKE_CXX_FLAGS}")
endif()
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -Werror=return-type")
# cmake code needed for the coverity scan upload
include(Coverity)
##################################### Set Application options #####################################
######## Set URLs ########
set(MultiMC_NEWS_RSS_URL "https://multimc.org/rss.xml" CACHE STRING "URL to fetch MultiMC's news RSS feed from.")
######## Set version numbers ########
set(MultiMC_VERSION_MAJOR 0)
set(MultiMC_VERSION_MINOR 6)
set(MultiMC_VERSION_HOTFIX 5)
# Build number
set(MultiMC_VERSION_BUILD -1 CACHE STRING "Build number. -1 for no build number.")
# Build platform.
set(MultiMC_BUILD_PLATFORM "" CACHE STRING "A short string identifying the platform that this build was built for. Only used by the notification system and to display in the about dialog.")
# Channel list URL
set(MultiMC_CHANLIST_URL "" CACHE STRING "URL for the channel list.")
# Notification URL
set(MultiMC_NOTIFICATION_URL "" CACHE STRING "URL for checking for notifications.")
# paste.ee API key
set(MultiMC_PASTE_EE_API_KEY "utLvciUouSURFzfjPxLBf5W4ISsUX4pwBDF7N1AfZ" CACHE STRING "API key you can get from paste.ee when you register an account")
# Google analytics ID
set(MultiMC_ANALYTICS_ID "UA-87731965-2" CACHE STRING "ID you can get from Google analytics")
#### Check the current Git commit and branch
include(GetGitRevisionDescription)
get_git_head_revision(MultiMC_GIT_REFSPEC MultiMC_GIT_COMMIT)
message(STATUS "Git commit: ${MultiMC_GIT_COMMIT}")
message(STATUS "Git refspec: ${MultiMC_GIT_REFSPEC}")
set(MultiMC_RELEASE_VERSION_NAME "${MultiMC_VERSION_MAJOR}.${MultiMC_VERSION_MINOR}.${MultiMC_VERSION_HOTFIX}")
#### Custom target to just print the version.
add_custom_target(version echo "Version: ${MultiMC_RELEASE_VERSION_NAME}")
################################ 3rd Party Libs ################################
@@ -50,15 +88,6 @@ find_package(Qt5Network REQUIRED)
find_package(Qt5Test REQUIRED)
find_package(Qt5Xml REQUIRED)
include_directories(
${Qt5Core_INCLUDE_DIRS}
${Qt5Widgets_INCLUDE_DIRS}
${Qt5Concurrent_INCLUDE_DIRS}
${Qt5Test_INCLUDE_DIRS}
${Qt5Network_INCLUDE_DIRS}
${Qt5Xml_INCLUDE_DIRS}
)
# The Qt5 cmake files don't provide its install paths, so ask qmake.
include(QMakeQuery)
query_qmake(QT_INSTALL_PLUGINS QT_PLUGINS_DIR)
@@ -72,69 +101,162 @@ if (Qt5_POSITION_INDEPENDENT_CODE)
SET(CMAKE_POSITION_INDEPENDENT_CODE ON)
endif()
####################################### Install layout #######################################
# How to install the build results
set(MultiMC_LAYOUT "auto" CACHE STRING "The layout for MultiMC installation (auto, win-bundle, lin-bundle, lin-nodeps, lin-system, mac-bundle)")
set_property(CACHE MultiMC_LAYOUT PROPERTY STRINGS auto win-bundle lin-bundle lin-nodeps lin-system mac-bundle)
if(MultiMC_LAYOUT STREQUAL "auto")
if(UNIX AND APPLE)
set(MultiMC_LAYOUT_REAL "mac-bundle")
elseif(UNIX)
set(MultiMC_LAYOUT_REAL "lin-nodeps")
elseif(WIN32)
set(MultiMC_LAYOUT_REAL "win-bundle")
else()
message(FATAL_ERROR "Cannot choose a sensible install layout for your platform.")
endif()
else()
set(MultiMC_LAYOUT_REAL ${MultiMC_LAYOUT})
endif()
if(MultiMC_LAYOUT_REAL STREQUAL "mac-bundle")
set(BINARY_DEST_DIR "MultiMC.app/Contents/MacOS")
set(LIBRARY_DEST_DIR "MultiMC.app/Contents/MacOS")
set(PLUGIN_DEST_DIR "MultiMC.app/Contents/MacOS")
set(RESOURCES_DEST_DIR "MultiMC.app/Contents/Resources")
set(JARS_DEST_DIR "MultiMC.app/Contents/MacOS/jars")
set(BUNDLE_DEST_DIR ".")
# Apps to bundle
set(APPS "\${CMAKE_INSTALL_PREFIX}/MultiMC.app")
# Mac bundle settings
set(MACOSX_BUNDLE_BUNDLE_NAME "MultiMC")
set(MACOSX_BUNDLE_INFO_STRING "MultiMC Minecraft launcher and management utility.")
set(MACOSX_BUNDLE_GUI_IDENTIFIER "org.multimc.MultiMC5")
set(MACOSX_BUNDLE_BUNDLE_VERSION "${MultiMC_VERSION_MAJOR}.${MultiMC_VERSION_MINOR}.${MultiMC_VERSION_HOTFIX}.${MultiMC_VERSION_BUILD}")
set(MACOSX_BUNDLE_SHORT_VERSION_STRING "${MultiMC_VERSION_MAJOR}.${MultiMC_VERSION_MINOR}.${MultiMC_VERSION_HOTFIX}.${MultiMC_VERSION_BUILD}")
set(MACOSX_BUNDLE_LONG_VERSION_STRING "${MultiMC_VERSION_MAJOR}.${MultiMC_VERSION_MINOR}.${MultiMC_VERSION_HOTFIX}.${MultiMC_VERSION_BUILD}")
set(MACOSX_BUNDLE_ICON_FILE MultiMC.icns)
set(MACOSX_BUNDLE_COPYRIGHT "Copyright 2015-2019 MultiMC Contributors")
# directories to look for dependencies
set(DIRS ${QT_LIBS_DIR} ${QT_LIBEXECS_DIR} ${CMAKE_LIBRARY_OUTPUT_DIRECTORY} ${CMAKE_RUNTIME_OUTPUT_DIRECTORY})
# install as bundle
set(INSTALL_BUNDLE "full")
# Add the icon
install(FILES application/resources/MultiMC.icns DESTINATION ${RESOURCES_DEST_DIR})
elseif(MultiMC_LAYOUT_REAL STREQUAL "lin-bundle")
set(BINARY_DEST_DIR "bin")
set(LIBRARY_DEST_DIR "bin")
set(PLUGIN_DEST_DIR "plugins")
set(BUNDLE_DEST_DIR ".")
set(RESOURCES_DEST_DIR ".")
set(JARS_DEST_DIR "bin/jars")
# Apps to bundle
set(APPS "\${CMAKE_INSTALL_PREFIX}/bin/MultiMC")
# directories to look for dependencies
set(DIRS ${QT_LIBS_DIR} ${QT_LIBEXECS_DIR} ${CMAKE_LIBRARY_OUTPUT_DIRECTORY} ${CMAKE_RUNTIME_OUTPUT_DIRECTORY})
# install as bundle
set(INSTALL_BUNDLE "full")
# Set RPATH
SET(MultiMC_BINARY_RPATH "$ORIGIN/")
# Install basic runner script
install(PROGRAMS application/package/linux/MultiMC DESTINATION ${BUNDLE_DEST_DIR})
elseif(MultiMC_LAYOUT_REAL STREQUAL "lin-nodeps")
set(BINARY_DEST_DIR "bin")
set(LIBRARY_DEST_DIR "bin")
set(PLUGIN_DEST_DIR "plugins")
set(BUNDLE_DEST_DIR ".")
set(RESOURCES_DEST_DIR ".")
set(JARS_DEST_DIR "bin/jars")
# install as bundle with no dependencies included
set(INSTALL_BUNDLE "nodeps")
# Set RPATH
SET(MultiMC_BINARY_RPATH "$ORIGIN/")
# Install basic runner script
install(PROGRAMS application/package/linux/MultiMC DESTINATION ${BUNDLE_DEST_DIR})
elseif(MultiMC_LAYOUT_REAL STREQUAL "lin-system")
set(MultiMC_APP_BINARY_NAME "multimc" CACHE STRING "Name of the MultiMC binary")
set(MultiMC_BINARY_DEST_DIR "bin" CACHE STRING "Path to the binary directory")
set(MultiMC_LIBRARY_DEST_DIR "lib${LIB_SUFFIX}" CACHE STRING "Path to the library directory")
set(MultiMC_SHARE_DEST_DIR "share/multimc" CACHE STRING "Path to the shared data directory")
set(JARS_DEST_DIR "${MultiMC_SHARE_DEST_DIR}/jars")
set(BINARY_DEST_DIR ${MultiMC_BINARY_DEST_DIR})
set(LIBRARY_DEST_DIR ${MultiMC_LIBRARY_DEST_DIR})
MESSAGE(STATUS "Compiling for linux system with ${MultiMC_SHARE_DEST_DIR} and MULTIMC_LINUX_DATADIR")
SET(MultiMC_APP_BINARY_DEFS "-DMULTIMC_JARS_LOCATION=${CMAKE_INSTALL_PREFIX}/${JARS_DEST_DIR}" "-DMULTIMC_LINUX_DATADIR")
# install as bundle with no dependencies included
set(INSTALL_BUNDLE "nodeps")
elseif(MultiMC_LAYOUT_REAL STREQUAL "win-bundle")
set(BINARY_DEST_DIR ".")
set(LIBRARY_DEST_DIR ".")
set(PLUGIN_DEST_DIR ".")
set(BUNDLE_DEST_DIR ".")
set(RESOURCES_DEST_DIR ".")
set(JARS_DEST_DIR "jars")
# Apps to bundle
set(APPS "\${CMAKE_INSTALL_PREFIX}/MultiMC.exe")
# directories to look for dependencies
set(DIRS ${QT_LIBS_DIR} ${QT_LIBEXECS_DIR} ${CMAKE_LIBRARY_OUTPUT_DIRECTORY} ${CMAKE_RUNTIME_OUTPUT_DIRECTORY})
# install as bundle
set(INSTALL_BUNDLE "full")
else()
message(FATAL_ERROR "No sensible install layout set.")
endif()
################################ Included Libs ################################
include(ExternalProject)
set_directory_properties(PROPERTIES EP_BASE External)
# Add quazip
add_definitions(-DQUAZIP_STATIC)
set(QUAZIP_VERSION "0.7.1")
if(NOT EXISTS ${CMAKE_BINARY_DIR}/quazip-${QUAZIP_VERSION}.tar.gz)
file(DOWNLOAD http://downloads.sourceforge.net/project/quazip/quazip/${QUAZIP_VERSION}/quazip-${QUAZIP_VERSION}.tar.gz ${CMAKE_BINARY_DIR}/quazip-${QUAZIP_VERSION}.tar.gz)
endif()
ExternalProject_Add(QuaZIP
SOURCE_DIR <BINARY_DIR>/../Source/quazip-${QUAZIP_VERSION}
DOWNLOAD_COMMAND ${CMAKE_COMMAND} -E chdir <SOURCE_DIR>/.. ${CMAKE_COMMAND} -E tar xzf ${CMAKE_BINARY_DIR}/quazip-${QUAZIP_VERSION}.tar.gz
PATCH_COMMAND patch -p0 -i ${CMAKE_SOURCE_DIR}/quazip.patch
CMAKE_ARGS -DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE} -DCMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER} -DCMAKE_C_COMPILER=${CMAKE_C_COMPILER} -DCMAKE_CXX_FLAGS=${CMAKE_CXX_FLAGS} -DCMAKE_CXX_FLAGS_DEBUG=${CMAKE_CXX_FLAGS_DEBUG} -DCMAKE_PREFIX_PATH=${CMAKE_PREFIX_PATH} -DCMAKE_INSTALL_PREFIX=<INSTALL_DIR>
)
include_directories("${CMAKE_BINARY_DIR}/External/Install/QuaZIP/include/quazip")
if(UNIX)
set(QUAZIP_LIBRARIES -L"${CMAKE_BINARY_DIR}/External/Install/QuaZIP/lib" quazip z)
else()
set(QUAZIP_LIBRARIES -L"${CMAKE_BINARY_DIR}/External/Install/QuaZIP/lib" quazip)
endif()
option(NBT_BUILD_SHARED "Build NBT shared library" ON)
option(NBT_USE_ZLIB "Build NBT library with zlib support" OFF)
option(NBT_BUILD_TESTS "Build NBT library tests" OFF) #FIXME: fix unit tests.
set(NBT_NAME MultiMC_nbt++)
set(NBT_DEST_DIR ${LIBRARY_DEST_DIR})
add_subdirectory(libraries/libnbtplusplus)
# Add the markdown parser thing
add_subdirectory(depends/hoedown)
include_directories(${HOEDOWN_INCLUDE_DIR})
# Add the java launcher and checker
add_subdirectory(depends/launcher)
add_subdirectory(depends/javacheck)
# Add xz decompression
add_subdirectory(depends/xz-embedded)
include_directories(${XZ_INCLUDE_DIR})
# Add pack200 decompression
add_subdirectory(depends/pack200)
include_directories(${PACK200_INCLUDE_DIR})
######## MultiMC Libs ########
# Add the util library.
add_definitions(-DLIBUTIL_STATIC)
add_subdirectory(depends/util)
include_directories(${LIBUTIL_INCLUDE_DIR})
# Add the GUI -> Logic connection header
add_subdirectory(depends/LogicalGui)
include_directories(${LOGICALGUI_INCLUDE_DIR})
# Add the GUI -> Logic connection header
add_subdirectory(depends/iconfix)
include_directories(${ICONFIX_INCLUDE_DIR})
include(Coverity)
add_subdirectory(libraries/ganalytics) # google analytics library
add_subdirectory(libraries/systeminfo) # system information library
add_subdirectory(libraries/hoedown) # markdown parser
add_subdirectory(libraries/launcher) # java based launcher part for Minecraft
add_subdirectory(libraries/javacheck) # java compatibility checker
add_subdirectory(libraries/xz-embedded) # xz compression
add_subdirectory(libraries/quazip) # zip manipulation library
add_subdirectory(libraries/pack200) # java pack200 compression
add_subdirectory(libraries/rainbow) # Qt extension for colors
add_subdirectory(libraries/iconfix) # fork of Qt's QIcon loader
add_subdirectory(libraries/LocalPeer) # fork of a library from Qt solutions
add_subdirectory(libraries/classparser) # google analytics library
############################### Built Artifacts ###############################
add_subdirectory(tests)
add_subdirectory(logic)
add_subdirectory(api/logic)
add_subdirectory(api/gui)
# NOTE: this must always be last to appease the CMake deity of quirky install command evaluation order.
add_subdirectory(application)
add_subdirectory(mmc_updater)

254
COPYING.md Normal file
View File

@@ -0,0 +1,254 @@
# MultiMC
Copyright 2012-2019 MultiMC Contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
# MinGW runtime (Windows)
Copyright (c) 2012 MinGW.org project
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice, this permission notice and the below disclaimer
shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
# Qt 5
Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
Contact: http://www.qt-project.org/legal
Licensed under LGPL v2.1
# libnbt++
libnbt++ - A library for the Minecraft Named Binary Tag format.
Copyright (C) 2013, 2015 ljfa-ag
libnbt++ is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
libnbt++ 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with libnbt++. If not, see <http://www.gnu.org/licenses/>.
# rainbow (KGuiAddons)
Copyright (C) 2007 Matthew Woehlke <mw_triad@users.sourceforge.net>
Copyright (C) 2007 Olaf Schmidt <ojschmidt@kde.org>
Copyright (C) 2007 Thomas Zander <zander@kde.org>
Copyright (C) 2007 Zack Rusin <zack@kde.org>
Copyright (C) 2015 Petr Mrazek <peterix@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
# Hoedown
Copyright (c) 2008, Natacha Porté
Copyright (c) 2011, Vicent Martí
Copyright (c) 2014, Xavier Mendez, Devin Torres and the Hoedown authors
Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
# Batch icon set
You are free to use Batch (the "icon set") or any part thereof (the "icons")
in any personal, open-source or commercial work without obligation of payment
(monetary or otherwise) or attribution. Do not sell the icon set, host
the icon set or rent the icon set (either in existing or modified form).
While attribution is optional, it is always appreciated.
Intellectual property rights are not transferred with the download of the icons.
EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE LAW, IN NO EVENT WILL ADAM WHITCROFT
BE LIABLE TO YOU ON ANY LEGAL THEORY FOR ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL,
PUNITIVE OR EXEMPLARY DAMAGES ARISING OUT OF THE USE OF THE ICONS,
EVEN IF LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
# Material Design Icons
Copyright (c) 2014, Austin Andrews (http://materialdesignicons.com/),
with Reserved Font Name Material Design Icons.
Copyright (c) 2014, Google (http://www.google.com/design/)
uses the license at https://github.com/google/material-design-icons/blob/master/LICENSE
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
# Pack200
The GNU General Public License (GPL)
Version 2, June 1991
+ "CLASSPATH" EXCEPTION TO THE GPL
Certain source files distributed by Oracle America and/or its affiliates are
subject to the following clarification and special exception to the GPL, but
only where Oracle has expressly included in the particular source file's header
the words "Oracle designates this particular file as subject to the "Classpath"
exception as provided by Oracle in the LICENSE file that accompanied this code."
Linking this library statically or dynamically with other modules is making
a combined work based on this library. Thus, the terms and conditions of
the GNU General Public License cover the whole combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent modules,
and to copy and distribute the resulting executable under terms of your
choice, provided that you also meet, for each linked independent module,
the terms and conditions of the license of that module. An independent
module is a module which is not derived from or based on this library. If
you modify this library, you may extend this exception to your version of
the library, but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version.
# Quazip
Copyright (C) 2005-2011 Sergey A. Tachenov
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2 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 Lesser
General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
See COPYING file for the full LGPL text.
Original ZIP package is copyrighted by Gilles Vollant, see
quazip/(un)zip.h files for details, basically it's zlib license.
# xz-minidec
XZ decompressor
Authors: Lasse Collin <lasse.collin@tukaani.org>
Igor Pavlov <http://7-zip.org/>
This file has been put into the public domain.
You can do whatever you want with this file.
# ColumnResizer
Copyright (c) 2011-2016 Aurélien Gâteau and contributors.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted (subject to the limitations in the
disclaimer below) provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the
distribution.
* The name of the contributors may not be used to endorse or
promote products derived from this software without specific prior
written permission.
NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE
GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT
HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# lionshead
Code has been taken from https://github.com/natefoo/lionshead and loosely
translated to C++ laced with Qt.
MIT License
Copyright (c) 2017 Nate Coraor
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -1,17 +1,33 @@
![MultiMC](http://i.imgur.com/QJXbz.png)
<p align="center">
<img src="https://avatars2.githubusercontent.com/u/5411890" alt="MultiMC logo"/>
</p>
MultiMC 5 [![Build Status](https://travis-ci.org/MultiMC/MultiMC5.svg?branch=develop)](https://travis-ci.org/MultiMC/MultiMC5) [![Translation Status](http://weblate.robotbrain.info/widgets/multimc/-/shields-badge.svg)](http://weblate.robotbrain.info/engage/multimc/?utm_source=widget) [![Stories in Ready](https://badge.waffle.io/MultiMC/MultiMC5.svg?label=ready&title=Ready)](http://waffle.io/MultiMC/MultiMC5)
MultiMC 5
=========
MultiMC is a custom launcher for Minecraft that allows you to easily manage multiple installations of Minecraft at once. It also allows you to easily install and remove mods by simply dragging and dropping. Here are the current [features](https://github.com/MultiMC/MultiMC5/wiki#features) of MultiMC.
## Building
Check [BUILD.md](BUILD.md) for build instructions.
## Contributing
The repository is currently managed by @peterix. If you'd like to contribute to the project please talk to us on IRC (Esper/#MultiMC) first! This helps us organise ideas and keep in contact with you, and we're unlikely to accept anything blindly.
## Development
The project uses C++ and Qt5 as the language and base framework. This might seem odd in the Minecraft community, but allows using 25MB of RAM, where other tools use an excessive amount of resources for no reason.
We use [Clang Format](http://clang.llvm.org/docs/ClangFormat.html) to format the project. We highly recommend setting it up so the project stays well formatted, but there are issues with it on Windows. If you have trouble setting it up, check [.clang-format](.clang-format) manually. We don't accept pull requests with poor formatting. If you have questions, talk to us on IRC (Esper/#MultiMC) _before_ submitting a pull request.
We can do more, with less, on worse hardware and leave more resources for the game while keeping the launcher running and providing extra features.
If you want to contribute, either talk to us on [Discord](https://discord.gg/0k2zsXGNHs0fE4Wm), [IRC](http://webchat.esper.net/?nick=&channels=MultiMC)(esper.net/#MultiMC) or pick up some item from [workflowy](https://workflowy.com/s/2EyDMcp7CU) - there are many.
### Building
If you want to build MultiMC yourself, check [BUILD.md](BUILD.md) for build instructions.
The ci server is running at [ci.multimc.org](http://ci.multimc.org), where you can watch the builds happen in (or very close to) real time. It can also serve as a nice reference on how to set up the build environment on your end.
According to travis.ci, the builds are currently [![Build Status](https://travis-ci.org/MultiMC/MultiMC5.svg?branch=develop)](https://travis-ci.org/MultiMC/MultiMC5)
### Code formatting
We use [Clang Format](http://clang.llvm.org/docs/ClangFormat.html) to format the project. We highly recommend setting it up so the project stays well formatted.
## Translations
Translations can be done either directly in the [translations repository](https://github.com/MultiMC/MultiMC5). For more details, see: [Translating-MultiMC](https://github.com/MultiMC/MultiMC5/wiki/Translating-MultiMC).
## Forking/Redistributing
We keep MultiMC open source because we think it's important to be able to see the source code for a project like this, and we do so using the Apache license.
@@ -22,7 +38,7 @@ Apache covers reasonable use for the name - a mention of the project's origins i
## License
Copyright &copy; 2013-2015 MultiMC Contributors
Copyright &copy; 2013-2019 MultiMC Contributors
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this program except in compliance with the License. You may obtain a copy of the License at [http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0).

34
api/gui/CMakeLists.txt Normal file
View File

@@ -0,0 +1,34 @@
project(MultiMC_gui LANGUAGES CXX)
set(GUI_SOURCES
DesktopServices.h
DesktopServices.cpp
# Icons
icons/MMCIcon.h
icons/MMCIcon.cpp
icons/IconList.h
icons/IconList.cpp
SkinUtils.cpp
SkinUtils.h
)
################################ COMPILE ################################
add_library(MultiMC_gui SHARED ${GUI_SOURCES})
set_target_properties(MultiMC_gui PROPERTIES CXX_VISIBILITY_PRESET hidden VISIBILITY_INLINES_HIDDEN 1)
generate_export_header(MultiMC_gui)
# Link
target_link_libraries(MultiMC_gui MultiMC_iconfix MultiMC_logic Qt5::Gui)
# Mark and export headers
target_include_directories(MultiMC_gui PUBLIC "${CMAKE_CURRENT_BINARY_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}")
# Install it
install(
TARGETS MultiMC_gui
RUNTIME DESTINATION ${LIBRARY_DEST_DIR}
LIBRARY DESTINATION ${LIBRARY_DEST_DIR}
)

149
api/gui/DesktopServices.cpp Normal file
View File

@@ -0,0 +1,149 @@
#include "DesktopServices.h"
#include <QDir>
#include <QDesktopServices>
#include <QProcess>
#include <QDebug>
/**
* This shouldn't exist, but until QTBUG-9328 and other unreported bugs are fixed, it needs to be a thing.
*/
#if defined(Q_OS_LINUX)
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>
template <typename T>
bool IndirectOpen(T callable, qint64 *pid_forked = nullptr)
{
auto pid = fork();
if(pid_forked)
{
if(pid > 0)
*pid_forked = pid;
else
*pid_forked = 0;
}
if(pid == -1)
{
qWarning() << "IndirectOpen failed to fork: " << errno;
return false;
}
// child - do the stuff
if(pid == 0)
{
// unset all this garbage so it doesn't get passed to the child process
qunsetenv("LD_PRELOAD");
qunsetenv("LD_LIBRARY_PATH");
qunsetenv("LD_DEBUG");
qunsetenv("QT_PLUGIN_PATH");
qunsetenv("QT_FONTPATH");
// open the URL
auto status = callable();
// detach from the parent process group.
setsid();
// die. now. do not clean up anything, it would just hang forever.
_exit(status ? 0 : 1);
}
else
{
//parent - assume it worked.
int status;
while (waitpid(pid, &status, 0))
{
if(WIFEXITED(status))
{
return WEXITSTATUS(status) == 0;
}
if(WIFSIGNALED(status))
{
return false;
}
}
return true;
}
}
#endif
namespace DesktopServices {
bool openDirectory(const QString &path, bool ensureExists)
{
qDebug() << "Opening directory" << path;
QDir parentPath;
QDir dir(path);
if (!dir.exists())
{
parentPath.mkpath(dir.absolutePath());
}
auto f = [&]()
{
return QDesktopServices::openUrl(QUrl::fromLocalFile(dir.absolutePath()));
};
#if defined(Q_OS_LINUX)
return IndirectOpen(f);
#else
return f();
#endif
}
bool openFile(const QString &path)
{
qDebug() << "Opening file" << path;
auto f = [&]()
{
return QDesktopServices::openUrl(QUrl::fromLocalFile(path));
};
#if defined(Q_OS_LINUX)
return IndirectOpen(f);
#else
return f();
#endif
}
bool openFile(const QString &application, const QString &path, const QString &workingDirectory, qint64 *pid)
{
qDebug() << "Opening file" << path << "using" << application;
#if defined(Q_OS_LINUX)
// FIXME: the pid here is fake. So if something depends on it, it will likely misbehave
return IndirectOpen([&]()
{
return QProcess::startDetached(application, QStringList() << path, workingDirectory);
}, pid);
#else
return QProcess::startDetached(application, QStringList() << path, workingDirectory, pid);
#endif
}
bool run(const QString &application, const QStringList &args, const QString &workingDirectory, qint64 *pid)
{
qDebug() << "Running" << application << "with args" << args.join(' ');
#if defined(Q_OS_LINUX)
// FIXME: the pid here is fake. So if something depends on it, it will likely misbehave
return IndirectOpen([&]()
{
return QProcess::startDetached(application, args, workingDirectory);
}, pid);
#else
return QProcess::startDetached(application, args, workingDirectory, pid);
#endif
}
bool openUrl(const QUrl &url)
{
qDebug() << "Opening URL" << url.toString();
auto f = [&]()
{
return QDesktopServices::openUrl(url);
};
#if defined(Q_OS_LINUX)
return IndirectOpen(f);
#else
return f();
#endif
}
}

37
api/gui/DesktopServices.h Normal file
View File

@@ -0,0 +1,37 @@
#pragma once
#include <QUrl>
#include <QString>
#include "multimc_gui_export.h"
/**
* This wraps around QDesktopServices and adds workarounds where needed
* Use this instead of QDesktopServices!
*/
namespace DesktopServices
{
/**
* Open a file in whatever application is applicable
*/
MULTIMC_GUI_EXPORT bool openFile(const QString &path);
/**
* Open a file in the specified application
*/
MULTIMC_GUI_EXPORT bool openFile(const QString &application, const QString &path, const QString & workingDirectory = QString(), qint64 *pid = 0);
/**
* Run an application
*/
MULTIMC_GUI_EXPORT bool run(const QString &application,const QStringList &args, const QString & workingDirectory = QString(), qint64 *pid = 0);
/**
* Open a directory
*/
MULTIMC_GUI_EXPORT bool openDirectory(const QString &path, bool ensureExists = false);
/**
* Open the URL, most likely in a browser. Maybe.
*/
MULTIMC_GUI_EXPORT bool openUrl(const QUrl &url);
}

View File

@@ -1,4 +1,4 @@
/* Copyright 2013-2015 MultiMC Contributors
/* Copyright 2013-2019 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,7 +13,7 @@
* limitations under the License.
*/
#include "minecraft/SkinUtils.h"
#include "SkinUtils.h"
#include "net/HttpMetaCache.h"
#include "Env.h"
@@ -29,19 +29,19 @@ namespace SkinUtils
*/
QPixmap getFaceFromCache(QString username, int height, int width)
{
QFile fskin(ENV.metacache()
->resolveEntry("skins", username + ".png")
->getFullPath());
QFile fskin(ENV.metacache()
->resolveEntry("skins", username + ".png")
->getFullPath());
if (fskin.exists())
{
QPixmap skin(fskin.fileName());
if(!skin.isNull())
{
return skin.copy(8, 8, 8, 8).scaled(height, width, Qt::KeepAspectRatio);
}
}
if (fskin.exists())
{
QPixmap skin(fskin.fileName());
if(!skin.isNull())
{
return skin.copy(8, 8, 8, 8).scaled(height, width, Qt::KeepAspectRatio);
}
}
return QPixmap();
return QPixmap();
}
}

View File

@@ -1,4 +1,4 @@
/* Copyright 2013-2015 MultiMC Contributors
/* Copyright 2013-2019 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,7 +17,9 @@
#include <QPixmap>
#include "multimc_gui_export.h"
namespace SkinUtils
{
QPixmap getFaceFromCache(QString username, int height = 64, int width = 64);
QPixmap MULTIMC_GUI_EXPORT getFaceFromCache(QString id, int height = 64, int width = 64);
}

422
api/gui/icons/IconList.cpp Normal file
View File

@@ -0,0 +1,422 @@
/* Copyright 2013-2019 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "IconList.h"
#include <FileSystem.h>
#include <QMap>
#include <QEventLoop>
#include <QMimeData>
#include <QUrl>
#include <QFileSystemWatcher>
#include <QSet>
#include <QDebug>
#define MAX_SIZE 1024
IconList::IconList(const QStringList &builtinPaths, QString path, QObject *parent) : QAbstractListModel(parent)
{
QSet<QString> builtinNames;
// add builtin icons
for(auto & builtinPath: builtinPaths)
{
QDir instance_icons(builtinPath);
auto file_info_list = instance_icons.entryInfoList(QDir::Files, QDir::Name);
for (auto file_info : file_info_list)
{
builtinNames.insert(file_info.baseName());
}
}
for(auto & builtinName : builtinNames)
{
addThemeIcon(builtinName);
}
m_watcher.reset(new QFileSystemWatcher());
is_watching = false;
connect(m_watcher.get(), SIGNAL(directoryChanged(QString)),
SLOT(directoryChanged(QString)));
connect(m_watcher.get(), SIGNAL(fileChanged(QString)), SLOT(fileChanged(QString)));
directoryChanged(path);
}
void IconList::directoryChanged(const QString &path)
{
QDir new_dir (path);
if(m_dir.absolutePath() != new_dir.absolutePath())
{
m_dir.setPath(path);
m_dir.refresh();
if(is_watching)
stopWatching();
startWatching();
}
if(!m_dir.exists())
if(!FS::ensureFolderPathExists(m_dir.absolutePath()))
return;
m_dir.refresh();
auto new_list = m_dir.entryList(QDir::Files, QDir::Name);
for (auto it = new_list.begin(); it != new_list.end(); it++)
{
QString &foo = (*it);
foo = m_dir.filePath(foo);
}
auto new_set = new_list.toSet();
QList<QString> current_list;
for (auto &it : icons)
{
if (!it.has(IconType::FileBased))
continue;
current_list.push_back(it.m_images[IconType::FileBased].filename);
}
QSet<QString> current_set = current_list.toSet();
QSet<QString> to_remove = current_set;
to_remove -= new_set;
QSet<QString> to_add = new_set;
to_add -= current_set;
for (auto remove : to_remove)
{
qDebug() << "Removing " << remove;
QFileInfo rmfile(remove);
QString key = rmfile.baseName();
int idx = getIconIndex(key);
if (idx == -1)
continue;
icons[idx].remove(IconType::FileBased);
if (icons[idx].type() == IconType::ToBeDeleted)
{
beginRemoveRows(QModelIndex(), idx, idx);
icons.remove(idx);
reindex();
endRemoveRows();
}
else
{
dataChanged(index(idx), index(idx));
}
m_watcher->removePath(remove);
emit iconUpdated(key);
}
for (auto add : to_add)
{
qDebug() << "Adding " << add;
QFileInfo addfile(add);
QString key = addfile.baseName();
if (addIcon(key, QString(), addfile.filePath(), IconType::FileBased))
{
m_watcher->addPath(add);
emit iconUpdated(key);
}
}
}
void IconList::fileChanged(const QString &path)
{
qDebug() << "Checking " << path;
QFileInfo checkfile(path);
if (!checkfile.exists())
return;
QString key = checkfile.baseName();
int idx = getIconIndex(key);
if (idx == -1)
return;
QIcon icon(path);
if (!icon.availableSizes().size())
return;
icons[idx].m_images[IconType::FileBased].icon = icon;
dataChanged(index(idx), index(idx));
emit iconUpdated(key);
}
void IconList::SettingChanged(const Setting &setting, QVariant value)
{
if(setting.id() != "IconsDir")
return;
directoryChanged(value.toString());
}
void IconList::startWatching()
{
auto abs_path = m_dir.absolutePath();
FS::ensureFolderPathExists(abs_path);
is_watching = m_watcher->addPath(abs_path);
if (is_watching)
{
qDebug() << "Started watching " << abs_path;
}
else
{
qDebug() << "Failed to start watching " << abs_path;
}
}
void IconList::stopWatching()
{
m_watcher->removePaths(m_watcher->files());
m_watcher->removePaths(m_watcher->directories());
is_watching = false;
}
QStringList IconList::mimeTypes() const
{
QStringList types;
types << "text/uri-list";
return types;
}
Qt::DropActions IconList::supportedDropActions() const
{
return Qt::CopyAction;
}
bool IconList::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent)
{
if (action == Qt::IgnoreAction)
return true;
// check if the action is supported
if (!data || !(action & supportedDropActions()))
return false;
// files dropped from outside?
if (data->hasUrls())
{
auto urls = data->urls();
QStringList iconFiles;
for (auto url : urls)
{
// only local files may be dropped...
if (!url.isLocalFile())
continue;
iconFiles += url.toLocalFile();
}
installIcons(iconFiles);
return true;
}
return false;
}
Qt::ItemFlags IconList::flags(const QModelIndex &index) const
{
Qt::ItemFlags defaultFlags = QAbstractListModel::flags(index);
if (index.isValid())
return Qt::ItemIsDropEnabled | defaultFlags;
else
return Qt::ItemIsDropEnabled | defaultFlags;
}
QVariant IconList::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
int row = index.row();
if (row < 0 || row >= icons.size())
return QVariant();
switch (role)
{
case Qt::DecorationRole:
return icons[row].icon();
case Qt::DisplayRole:
return icons[row].name();
case Qt::UserRole:
return icons[row].m_key;
default:
return QVariant();
}
}
int IconList::rowCount(const QModelIndex &parent) const
{
return icons.size();
}
void IconList::installIcons(const QStringList &iconFiles)
{
for (QString file : iconFiles)
{
installIcon(file, QFileInfo(file).fileName());
}
}
void IconList::installIcon(const QString &file, const QString &name)
{
QFileInfo fileinfo(file);
if(!fileinfo.isReadable() || !fileinfo.isFile())
{
qWarning() << "Failed to install icon" << fileinfo.absoluteFilePath();
return;
}
QString target = FS::PathCombine(m_dir.dirName(), name);
QPixmap icon(fileinfo.absoluteFilePath());
if(icon.isNull())
{
qWarning() << "Icon " << fileinfo.absoluteFilePath() << "is null";
return;
}
auto currentSize = icon.size();
auto targetedWidth = qMin(currentSize.width(), 512);
auto targetedHeight = qMin(currentSize.height(), 512);
icon.scaled(targetedWidth, targetedHeight).save(target);
}
bool IconList::iconFileExists(const QString &key) const
{
auto iconEntry = icon(key);
if(!iconEntry)
{
return false;
}
return iconEntry->has(IconType::FileBased);
}
const MMCIcon *IconList::icon(const QString &key) const
{
int iconIdx = getIconIndex(key);
if (iconIdx == -1)
return nullptr;
return &icons[iconIdx];
}
bool IconList::deleteIcon(const QString &key)
{
int iconIdx = getIconIndex(key);
if (iconIdx == -1)
return false;
auto &iconEntry = icons[iconIdx];
if (iconEntry.has(IconType::FileBased))
{
return QFile::remove(iconEntry.m_images[IconType::FileBased].filename);
}
return false;
}
bool IconList::addThemeIcon(const QString& key)
{
auto iter = name_index.find(key);
if (iter != name_index.end())
{
auto &oldOne = icons[*iter];
oldOne.replace(Builtin, key);
dataChanged(index(*iter), index(*iter));
return true;
}
else
{
// add a new icon
beginInsertRows(QModelIndex(), icons.size(), icons.size());
{
MMCIcon mmc_icon;
mmc_icon.m_name = key;
mmc_icon.m_key = key;
mmc_icon.replace(Builtin, key);
icons.push_back(mmc_icon);
name_index[key] = icons.size() - 1;
}
endInsertRows();
return true;
}
}
bool IconList::addIcon(const QString &key, const QString &name, const QString &path, const IconType type)
{
// replace the icon even? is the input valid?
QIcon icon(path);
if (icon.isNull())
return false;
auto iter = name_index.find(key);
if (iter != name_index.end())
{
auto &oldOne = icons[*iter];
oldOne.replace(type, icon, path);
dataChanged(index(*iter), index(*iter));
return true;
}
else
{
// add a new icon
beginInsertRows(QModelIndex(), icons.size(), icons.size());
{
MMCIcon mmc_icon;
mmc_icon.m_name = name;
mmc_icon.m_key = key;
mmc_icon.replace(type, icon, path);
icons.push_back(mmc_icon);
name_index[key] = icons.size() - 1;
}
endInsertRows();
return true;
}
}
void IconList::saveIcon(const QString &key, const QString &path, const char * format) const
{
auto icon = getIcon(key);
auto pixmap = icon.pixmap(128, 128);
pixmap.save(path, format);
}
void IconList::reindex()
{
name_index.clear();
int i = 0;
for (auto &iter : icons)
{
name_index[iter.m_key] = i;
i++;
}
}
QIcon IconList::getIcon(const QString &key) const
{
int icon_index = getIconIndex(key);
if (icon_index != -1)
return icons[icon_index].icon();
// Fallback for icons that don't exist.
icon_index = getIconIndex("infinity");
if (icon_index != -1)
return icons[icon_index].icon();
return QIcon();
}
int IconList::getIconIndex(const QString &key) const
{
auto iter = name_index.find(key == "default" ? "infinity" : key);
if (iter != name_index.end())
return *iter;
return -1;
}
QString IconList::getDirectory() const
{
return m_dir.absolutePath();
}
//#include "IconList.moc"

88
api/gui/icons/IconList.h Normal file
View File

@@ -0,0 +1,88 @@
/* Copyright 2013-2019 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <QMutex>
#include <QAbstractListModel>
#include <QFile>
#include <QDir>
#include <QtGui/QIcon>
#include <memory>
#include "MMCIcon.h"
#include "settings/Setting.h"
#include "Env.h" // there is a global icon list inside Env.
#include <icons/IIconList.h>
#include "multimc_gui_export.h"
class QFileSystemWatcher;
class MULTIMC_GUI_EXPORT IconList : public QAbstractListModel, public IIconList
{
Q_OBJECT
public:
explicit IconList(const QStringList &builtinPaths, QString path, QObject *parent = 0);
virtual ~IconList() {};
QIcon getIcon(const QString &key) const;
int getIconIndex(const QString &key) const;
QString getDirectory() const;
virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
virtual int rowCount(const QModelIndex &parent = QModelIndex()) const override;
bool addThemeIcon(const QString &key);
bool addIcon(const QString &key, const QString &name, const QString &path, const IconType type) override;
void saveIcon(const QString &key, const QString &path, const char * format) const override;
bool deleteIcon(const QString &key) override;
bool iconFileExists(const QString &key) const override;
virtual QStringList mimeTypes() const override;
virtual Qt::DropActions supportedDropActions() const override;
virtual bool dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) override;
virtual Qt::ItemFlags flags(const QModelIndex &index) const override;
void installIcons(const QStringList &iconFiles) override;
void installIcon(const QString &file, const QString &name) override;
const MMCIcon * icon(const QString &key) const;
void startWatching();
void stopWatching();
signals:
void iconUpdated(QString key);
private:
// hide copy constructor
IconList(const IconList &) = delete;
// hide assign op
IconList &operator=(const IconList &) = delete;
void reindex();
public slots:
void directoryChanged(const QString &path);
protected slots:
void fileChanged(const QString &path);
void SettingChanged(const Setting & setting, QVariant value);
private:
shared_qobject_ptr<QFileSystemWatcher> m_watcher;
bool is_watching;
QMap<QString, int> name_index;
QVector<MMCIcon> icons;
QDir m_dir;
};

118
api/gui/icons/MMCIcon.cpp Normal file
View File

@@ -0,0 +1,118 @@
/* Copyright 2013-2019 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "MMCIcon.h"
#include <QFileInfo>
#include <xdgicon.h>
IconType operator--(IconType &t, int)
{
IconType temp = t;
switch (t)
{
case IconType::Builtin:
t = IconType::ToBeDeleted;
break;
case IconType::Transient:
t = IconType::Builtin;
break;
case IconType::FileBased:
t = IconType::Transient;
break;
default:
{
}
}
return temp;
}
IconType MMCIcon::type() const
{
return m_current_type;
}
QString MMCIcon::name() const
{
if (m_name.size())
return m_name;
return m_key;
}
bool MMCIcon::has(IconType _type) const
{
return m_images[_type].present();
}
QIcon MMCIcon::icon() const
{
if (m_current_type == IconType::ToBeDeleted)
return QIcon();
auto & icon = m_images[m_current_type].icon;
if(!icon.isNull())
return icon;
// FIXME: inject this.
return XdgIcon::fromTheme(m_images[m_current_type].key);
}
void MMCIcon::remove(IconType rm_type)
{
m_images[rm_type].filename = QString();
m_images[rm_type].icon = QIcon();
for (auto iter = rm_type; iter != IconType::ToBeDeleted; iter--)
{
if (m_images[iter].present())
{
m_current_type = iter;
return;
}
}
m_current_type = IconType::ToBeDeleted;
}
void MMCIcon::replace(IconType new_type, QIcon icon, QString path)
{
if (new_type > m_current_type || m_current_type == IconType::ToBeDeleted)
{
m_current_type = new_type;
}
m_images[new_type].icon = icon;
m_images[new_type].filename = path;
m_images[new_type].key = QString();
}
void MMCIcon::replace(IconType new_type, const QString& key)
{
if (new_type > m_current_type || m_current_type == IconType::ToBeDeleted)
{
m_current_type = new_type;
}
m_images[new_type].icon = QIcon();
m_images[new_type].filename = QString();
m_images[new_type].key = key;
}
QString MMCIcon::getFilePath() const
{
if(m_current_type == IconType::ToBeDeleted){
return QString();
}
return m_images[m_current_type].filename;
}
bool MMCIcon::isBuiltIn() const
{
return m_current_type == IconType::Builtin;
}

51
api/gui/icons/MMCIcon.h Normal file
View File

@@ -0,0 +1,51 @@
/* Copyright 2013-2019 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <QString>
#include <QDateTime>
#include <QIcon>
#include <icons/IIconList.h>
#include "multimc_gui_export.h"
struct MULTIMC_GUI_EXPORT MMCImage
{
QIcon icon;
QString key;
QString filename;
bool present() const
{
return !icon.isNull() || !key.isEmpty();
}
};
struct MULTIMC_GUI_EXPORT MMCIcon
{
QString m_key;
QString m_name;
MMCImage m_images[ICONS_TOTAL];
IconType m_current_type = ToBeDeleted;
IconType type() const;
QString name() const;
bool has(IconType _type) const;
QIcon icon() const;
void remove(IconType rm_type);
void replace(IconType new_type, QIcon icon, QString path = QString());
void replace(IconType new_type, const QString &key);
bool isBuiltIn() const;
QString getFilePath() const;
};

View File

@@ -1,4 +1,4 @@
/* Copyright 2013-2015 MultiMC Contributors
/* Copyright 2013-2019 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,46 +16,46 @@
#include <QFile>
#include "BaseInstaller.h"
#include "minecraft/OneSixInstance.h"
#include "minecraft/MinecraftInstance.h"
BaseInstaller::BaseInstaller()
{
}
bool BaseInstaller::isApplied(OneSixInstance *on)
bool BaseInstaller::isApplied(MinecraftInstance *on)
{
return QFile::exists(filename(on->instanceRoot()));
return QFile::exists(filename(on->instanceRoot()));
}
bool BaseInstaller::add(OneSixInstance *to)
bool BaseInstaller::add(MinecraftInstance *to)
{
if (!patchesDir(to->instanceRoot()).exists())
{
QDir(to->instanceRoot()).mkdir("patches");
}
if (!patchesDir(to->instanceRoot()).exists())
{
QDir(to->instanceRoot()).mkdir("patches");
}
if (isApplied(to))
{
if (!remove(to))
{
return false;
}
}
if (isApplied(to))
{
if (!remove(to))
{
return false;
}
}
return true;
return true;
}
bool BaseInstaller::remove(OneSixInstance *from)
bool BaseInstaller::remove(MinecraftInstance *from)
{
return QFile::remove(filename(from->instanceRoot()));
return QFile::remove(filename(from->instanceRoot()));
}
QString BaseInstaller::filename(const QString &root) const
{
return patchesDir(root).absoluteFilePath(id() + ".json");
return patchesDir(root).absoluteFilePath(id() + ".json");
}
QDir BaseInstaller::patchesDir(const QString &root) const
{
return QDir(root + "/patches/");
return QDir(root + "/patches/");
}

View File

@@ -1,4 +1,4 @@
/* Copyright 2013-2015 MultiMC Contributors
/* Copyright 2013-2019 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,28 +17,30 @@
#include <memory>
class OneSixInstance;
#include "multimc_logic_export.h"
class MinecraftInstance;
class QDir;
class QString;
class QObject;
class Task;
struct BaseVersion;
class BaseVersion;
typedef std::shared_ptr<BaseVersion> BaseVersionPtr;
class BaseInstaller
class MULTIMC_LOGIC_EXPORT BaseInstaller
{
public:
BaseInstaller();
virtual ~BaseInstaller(){};
bool isApplied(OneSixInstance *on);
BaseInstaller();
virtual ~BaseInstaller(){};
bool isApplied(MinecraftInstance *on);
virtual bool add(OneSixInstance *to);
virtual bool remove(OneSixInstance *from);
virtual bool add(MinecraftInstance *to);
virtual bool remove(MinecraftInstance *from);
virtual Task *createInstallTask(OneSixInstance *instance, BaseVersionPtr version, QObject *parent) = 0;
virtual Task *createInstallTask(MinecraftInstance *instance, BaseVersionPtr version, QObject *parent) = 0;
protected:
virtual QString id() const = 0;
QString filename(const QString &root) const;
QDir patchesDir(const QString &root) const;
virtual QString id() const = 0;
QString filename(const QString &root) const;
QDir patchesDir(const QString &root) const;
};

254
api/logic/BaseInstance.cpp Normal file
View File

@@ -0,0 +1,254 @@
/* Copyright 2013-2019 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "BaseInstance.h"
#include <QFileInfo>
#include <QDir>
#include <QDebug>
#include "settings/INISettingsObject.h"
#include "settings/Setting.h"
#include "settings/OverrideSetting.h"
#include "FileSystem.h"
#include "Commandline.h"
BaseInstance::BaseInstance(SettingsObjectPtr globalSettings, SettingsObjectPtr settings, const QString &rootDir)
: QObject()
{
m_settings = settings;
m_rootDir = rootDir;
m_settings->registerSetting("name", "Unnamed Instance");
m_settings->registerSetting("iconKey", "default");
m_settings->registerSetting("notes", "");
m_settings->registerSetting("lastLaunchTime", 0);
m_settings->registerSetting("totalTimePlayed", 0);
// Custom Commands
auto commandSetting = m_settings->registerSetting({"OverrideCommands","OverrideLaunchCmd"}, false);
m_settings->registerOverride(globalSettings->getSetting("PreLaunchCommand"), commandSetting);
m_settings->registerOverride(globalSettings->getSetting("WrapperCommand"), commandSetting);
m_settings->registerOverride(globalSettings->getSetting("PostExitCommand"), commandSetting);
// Console
auto consoleSetting = m_settings->registerSetting("OverrideConsole", false);
m_settings->registerOverride(globalSettings->getSetting("ShowConsole"), consoleSetting);
m_settings->registerOverride(globalSettings->getSetting("AutoCloseConsole"), consoleSetting);
m_settings->registerOverride(globalSettings->getSetting("ShowConsoleOnError"), consoleSetting);
m_settings->registerOverride(globalSettings->getSetting("LogPrePostOutput"), consoleSetting);
m_settings->registerPassthrough(globalSettings->getSetting("ConsoleMaxLines"), nullptr);
m_settings->registerPassthrough(globalSettings->getSetting("ConsoleOverflowStop"), nullptr);
}
QString BaseInstance::getPreLaunchCommand()
{
return settings()->get("PreLaunchCommand").toString();
}
QString BaseInstance::getWrapperCommand()
{
return settings()->get("WrapperCommand").toString();
}
QString BaseInstance::getPostExitCommand()
{
return settings()->get("PostExitCommand").toString();
}
int BaseInstance::getConsoleMaxLines() const
{
auto lineSetting = settings()->getSetting("ConsoleMaxLines");
bool conversionOk = false;
int maxLines = lineSetting->get().toInt(&conversionOk);
if(!conversionOk)
{
maxLines = lineSetting->defValue().toInt();
qWarning() << "ConsoleMaxLines has nonsensical value, defaulting to" << maxLines;
}
return maxLines;
}
bool BaseInstance::shouldStopOnConsoleOverflow() const
{
return settings()->get("ConsoleOverflowStop").toBool();
}
void BaseInstance::iconUpdated(QString key)
{
if(iconKey() == key)
{
emit propertiesChanged(this);
}
}
void BaseInstance::invalidate()
{
changeStatus(Status::Gone);
qDebug() << "Instance" << id() << "has been invalidated.";
}
void BaseInstance::changeStatus(BaseInstance::Status newStatus)
{
Status status = currentStatus();
if(status != newStatus)
{
m_status = newStatus;
emit statusChanged(status, newStatus);
}
}
BaseInstance::Status BaseInstance::currentStatus() const
{
return m_status;
}
QString BaseInstance::id() const
{
return QFileInfo(instanceRoot()).fileName();
}
bool BaseInstance::isRunning() const
{
return m_isRunning;
}
void BaseInstance::setRunning(bool running)
{
if(running == m_isRunning)
return;
m_isRunning = running;
if(running)
{
m_timeStarted = QDateTime::currentDateTime();
}
else
{
qint64 current = settings()->get("totalTimePlayed").toLongLong();
QDateTime timeEnded = QDateTime::currentDateTime();
settings()->set("totalTimePlayed", current + m_timeStarted.secsTo(timeEnded));
emit propertiesChanged(this);
}
emit runningStatusChanged(running);
}
int64_t BaseInstance::totalTimePlayed() const
{
qint64 current = settings()->get("totalTimePlayed").toLongLong();
if(m_isRunning)
{
QDateTime timeNow = QDateTime::currentDateTime();
return current + m_timeStarted.secsTo(timeNow);
}
return current;
}
void BaseInstance::resetTimePlayed()
{
settings()->reset("totalTimePlayed");
}
QString BaseInstance::instanceType() const
{
return m_settings->get("InstanceType").toString();
}
QString BaseInstance::instanceRoot() const
{
return m_rootDir;
}
SettingsObjectPtr BaseInstance::settings() const
{
return m_settings;
}
bool BaseInstance::canLaunch() const
{
return (!hasVersionBroken() && !isRunning());
}
bool BaseInstance::reloadSettings()
{
return m_settings->reload();
}
qint64 BaseInstance::lastLaunch() const
{
return m_settings->get("lastLaunchTime").value<qint64>();
}
void BaseInstance::setLastLaunch(qint64 val)
{
//FIXME: if no change, do not set. setting involves saving a file.
m_settings->set("lastLaunchTime", val);
emit propertiesChanged(this);
}
void BaseInstance::setNotes(QString val)
{
//FIXME: if no change, do not set. setting involves saving a file.
m_settings->set("notes", val);
}
QString BaseInstance::notes() const
{
return m_settings->get("notes").toString();
}
void BaseInstance::setIconKey(QString val)
{
//FIXME: if no change, do not set. setting involves saving a file.
m_settings->set("iconKey", val);
emit propertiesChanged(this);
}
QString BaseInstance::iconKey() const
{
return m_settings->get("iconKey").toString();
}
void BaseInstance::setName(QString val)
{
//FIXME: if no change, do not set. setting involves saving a file.
m_settings->set("name", val);
emit propertiesChanged(this);
}
QString BaseInstance::name() const
{
return m_settings->get("name").toString();
}
QString BaseInstance::windowTitle() const
{
return "MultiMC: " + name().replace(QRegExp("[ \n\r\t]+"), " ");
}
// FIXME: why is this here? move it to MinecraftInstance!!!
QStringList BaseInstance::extraArguments() const
{
return Commandline::splitArgs(settings()->get("JvmArgs").toString());
}
shared_qobject_ptr<LaunchTask> BaseInstance::getLaunchTask()
{
return m_launchProcess;
}

268
api/logic/BaseInstance.h Normal file
View File

@@ -0,0 +1,268 @@
/* Copyright 2013-2019 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <cassert>
#include <QObject>
#include "QObjectPtr.h"
#include <QDateTime>
#include <QSet>
#include <QProcess>
#include "settings/SettingsObject.h"
#include "settings/INIFile.h"
#include "BaseVersionList.h"
#include "minecraft/auth/MojangAccount.h"
#include "MessageLevel.h"
#include "pathmatcher/IPathMatcher.h"
#include "net/Mode.h"
#include "multimc_logic_export.h"
class QDir;
class Task;
class LaunchTask;
class BaseInstance;
// pointer for lazy people
typedef std::shared_ptr<BaseInstance> InstancePtr;
/*!
* \brief Base class for instances.
* This class implements many functions that are common between instances and
* provides a standard interface for all instances.
*
* To create a new instance type, create a new class inheriting from this class
* and implement the pure virtual functions.
*/
class MULTIMC_LOGIC_EXPORT BaseInstance : public QObject, public std::enable_shared_from_this<BaseInstance>
{
Q_OBJECT
protected:
/// no-touchy!
BaseInstance(SettingsObjectPtr globalSettings, SettingsObjectPtr settings, const QString &rootDir);
public: /* types */
enum class Status
{
Present,
Gone // either nuked or invalidated
};
public:
/// virtual destructor to make sure the destruction is COMPLETE
virtual ~BaseInstance() {};
virtual void saveNow() = 0;
/***
* the instance has been invalidated - it is no longer tracked by MultiMC for some reason,
* but it has not necessarily been deleted.
*
* Happens when the instance folder changes to some other location, or the instance is removed by external means.
*/
void invalidate();
/// The instance's ID. The ID SHALL be determined by MMC internally. The ID IS guaranteed to
/// be unique.
virtual QString id() const;
void setRunning(bool running);
bool isRunning() const;
int64_t totalTimePlayed() const;
void resetTimePlayed();
/// get the type of this instance
QString instanceType() const;
/// Path to the instance's root directory.
QString instanceRoot() const;
/// Path to the instance's game root directory.
virtual QString gameRoot() const
{
return instanceRoot();
}
QString name() const;
void setName(QString val);
/// Value used for instance window titles
QString windowTitle() const;
QString iconKey() const;
void setIconKey(QString val);
QString notes() const;
void setNotes(QString val);
QString getPreLaunchCommand();
QString getPostExitCommand();
QString getWrapperCommand();
/// guess log level from a line of game log
virtual MessageLevel::Enum guessLevel(const QString &line, MessageLevel::Enum level)
{
return level;
};
virtual QStringList extraArguments() const;
/// Traits. Normally inside the version, depends on instance implementation.
virtual QSet <QString> traits() const = 0;
/**
* Gets the time that the instance was last launched.
* Stored in milliseconds since epoch.
*/
qint64 lastLaunch() const;
/// Sets the last launched time to 'val' milliseconds since epoch
void setLastLaunch(qint64 val = QDateTime::currentMSecsSinceEpoch());
/*!
* \brief Gets this instance's settings object.
* This settings object stores instance-specific settings.
* \return A pointer to this instance's settings object.
*/
virtual SettingsObjectPtr settings() const;
/// returns a valid update task
virtual shared_qobject_ptr<Task> createUpdateTask(Net::Mode mode) = 0;
/// returns a valid launcher (task container)
virtual shared_qobject_ptr<LaunchTask> createLaunchTask(AuthSessionPtr account) = 0;
/// returns the current launch task (if any)
shared_qobject_ptr<LaunchTask> getLaunchTask();
/*!
* Create envrironment variables for running the instance
*/
virtual QProcessEnvironment createEnvironment() = 0;
/*!
* Returns a matcher that can maps relative paths within the instance to whether they are 'log files'
*/
virtual IPathMatcher::Ptr getLogFileMatcher() = 0;
/*!
* Returns the root folder to use for looking up log files
*/
virtual QString getLogFileRoot() = 0;
virtual QString getStatusbarDescription() = 0;
/// FIXME: this really should be elsewhere...
virtual QString instanceConfigFolder() const = 0;
/// get variables this instance exports
virtual QMap<QString, QString> getVariables() const = 0;
virtual QString typeName() const = 0;
bool hasVersionBroken() const
{
return m_hasBrokenVersion;
}
void setVersionBroken(bool value)
{
if(m_hasBrokenVersion != value)
{
m_hasBrokenVersion = value;
emit propertiesChanged(this);
}
}
bool hasUpdateAvailable() const
{
return m_hasUpdate;
}
void setUpdateAvailable(bool value)
{
if(m_hasUpdate != value)
{
m_hasUpdate = value;
emit propertiesChanged(this);
}
}
bool hasCrashed() const
{
return m_crashed;
}
void setCrashed(bool value)
{
if(m_crashed != value)
{
m_crashed = value;
emit propertiesChanged(this);
}
}
virtual bool canLaunch() const;
virtual bool canEdit() const = 0;
virtual bool canExport() const = 0;
bool reloadSettings();
/**
* 'print' a verbose desription of the instance into a QStringList
*/
virtual QStringList verboseDescription(AuthSessionPtr session) = 0;
Status currentStatus() const;
int getConsoleMaxLines() const;
bool shouldStopOnConsoleOverflow() const;
protected:
void changeStatus(Status newStatus);
signals:
/*!
* \brief Signal emitted when properties relevant to the instance view change
*/
void propertiesChanged(BaseInstance *inst);
void launchTaskChanged(shared_qobject_ptr<LaunchTask>);
void runningStatusChanged(bool running);
void statusChanged(Status from, Status to);
protected slots:
void iconUpdated(QString key);
protected: /* data */
QString m_rootDir;
SettingsObjectPtr m_settings;
// InstanceFlags m_flags;
bool m_isRunning = false;
shared_qobject_ptr<LaunchTask> m_launchProcess;
QDateTime m_timeStarted;
private: /* data */
Status m_status = Status::Present;
bool m_crashed = false;
bool m_hasUpdate = false;
bool m_hasBrokenVersion = false;
};
Q_DECLARE_METATYPE(shared_qobject_ptr<BaseInstance>)
//Q_DECLARE_METATYPE(BaseInstance::InstanceFlag)
//Q_DECLARE_OPERATORS_FOR_FLAGS(BaseInstance::InstanceFlags)

59
api/logic/BaseVersion.h Normal file
View File

@@ -0,0 +1,59 @@
/* Copyright 2013-2019 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <memory>
#include <QString>
#include <QMetaType>
/*!
* An abstract base class for versions.
*/
class BaseVersion
{
public:
virtual ~BaseVersion() {}
/*!
* A string used to identify this version in config files.
* This should be unique within the version list or shenanigans will occur.
*/
virtual QString descriptor() = 0;
/*!
* The name of this version as it is displayed to the user.
* For example: "1.5.1"
*/
virtual QString name() = 0;
/*!
* This should return a string that describes
* the kind of version this is (Stable, Beta, Snapshot, whatever)
*/
virtual QString typeString() const = 0;
virtual bool operator<(BaseVersion &a)
{
return name() < a.name();
};
virtual bool operator>(BaseVersion &a)
{
return name() > a.name();
};
};
typedef std::shared_ptr<BaseVersion> BaseVersionPtr;
Q_DECLARE_METATYPE(BaseVersionPtr)

View File

@@ -0,0 +1,99 @@
/* Copyright 2013-2019 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "BaseVersionList.h"
#include "BaseVersion.h"
BaseVersionList::BaseVersionList(QObject *parent) : QAbstractListModel(parent)
{
}
BaseVersionPtr BaseVersionList::findVersion(const QString &descriptor)
{
for (int i = 0; i < count(); i++)
{
if (at(i)->descriptor() == descriptor)
return at(i);
}
return BaseVersionPtr();
}
BaseVersionPtr BaseVersionList::getRecommended() const
{
if (count() <= 0)
return BaseVersionPtr();
else
return at(0);
}
QVariant BaseVersionList::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
if (index.row() > count())
return QVariant();
BaseVersionPtr version = at(index.row());
switch (role)
{
case VersionPointerRole:
return qVariantFromValue(version);
case VersionRole:
return version->name();
case VersionIdRole:
return version->descriptor();
case TypeRole:
return version->typeString();
default:
return QVariant();
}
}
BaseVersionList::RoleList BaseVersionList::providesRoles() const
{
return {VersionPointerRole, VersionRole, VersionIdRole, TypeRole};
}
int BaseVersionList::rowCount(const QModelIndex &parent) const
{
// Return count
return count();
}
int BaseVersionList::columnCount(const QModelIndex &parent) const
{
return 1;
}
QHash<int, QByteArray> BaseVersionList::roleNames() const
{
QHash<int, QByteArray> roles = QAbstractListModel::roleNames();
roles.insert(VersionRole, "version");
roles.insert(VersionIdRole, "versionId");
roles.insert(ParentVersionRole, "parentGameVersion");
roles.insert(RecommendedRole, "recommended");
roles.insert(LatestRole, "latest");
roles.insert(TypeRole, "type");
roles.insert(BranchRole, "branch");
roles.insert(PathRole, "path");
roles.insert(ArchitectureRole, "architecture");
return roles;
}

122
api/logic/BaseVersionList.h Normal file
View File

@@ -0,0 +1,122 @@
/* Copyright 2013-2019 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <QObject>
#include <QVariant>
#include <QAbstractListModel>
#include "BaseVersion.h"
#include "tasks/Task.h"
#include "multimc_logic_export.h"
#include "QObjectPtr.h"
/*!
* \brief Class that each instance type's version list derives from.
* Version lists are the lists that keep track of the available game versions
* for that instance. This list will not be loaded on startup. It will be loaded
* when the list's load function is called. Before using the version list, you
* should check to see if it has been loaded yet and if not, load the list.
*
* Note that this class also inherits from QAbstractListModel. Methods from that
* class determine how this version list shows up in a list view. Said methods
* all have a default implementation, but they can be overridden by plugins to
* change the behavior of the list.
*/
class MULTIMC_LOGIC_EXPORT BaseVersionList : public QAbstractListModel
{
Q_OBJECT
public:
enum ModelRoles
{
VersionPointerRole = Qt::UserRole,
VersionRole,
VersionIdRole,
ParentVersionRole,
RecommendedRole,
LatestRole,
TypeRole,
BranchRole,
PathRole,
ArchitectureRole,
SortRole
};
typedef QList<int> RoleList;
explicit BaseVersionList(QObject *parent = 0);
/*!
* \brief Gets a task that will reload the version list.
* Simply execute the task to load the list.
* The task returned by this function should reset the model when it's done.
* \return A pointer to a task that reloads the version list.
*/
virtual shared_qobject_ptr<Task> getLoadTask() = 0;
//! Checks whether or not the list is loaded. If this returns false, the list should be
//loaded.
virtual bool isLoaded() = 0;
//! Gets the version at the given index.
virtual const BaseVersionPtr at(int i) const = 0;
//! Returns the number of versions in the list.
virtual int count() const = 0;
//////// List Model Functions ////////
QVariant data(const QModelIndex &index, int role) const override;
int rowCount(const QModelIndex &parent) const override;
int columnCount(const QModelIndex &parent) const override;
QHash<int, QByteArray> roleNames() const override;
//! which roles are provided by this version list?
virtual RoleList providesRoles() const;
/*!
* \brief Finds a version by its descriptor.
* \param descriptor The descriptor of the version to find.
* \return A const pointer to the version with the given descriptor. NULL if
* one doesn't exist.
*/
virtual BaseVersionPtr findVersion(const QString &descriptor);
/*!
* \brief Gets the recommended version from this list
* If the list doesn't support recommended versions, this works exactly as getLatestStable
*/
virtual BaseVersionPtr getRecommended() const;
/*!
* Sorts the version list.
*/
virtual void sortVersions() = 0;
protected
slots:
/*!
* Updates this list with the given list of versions.
* This is done by copying each version in the given list and inserting it
* into this one.
* We need to do this so that we can set the parents of the versions are set to this
* version list. This can't be done in the load task, because the versions the load
* task creates are on the load task's thread and Qt won't allow their parents
* to be set to something created on another thread.
* To get around that problem, we invoke this method on the GUI thread, which
* then copies the versions and sets their parents correctly.
* \param versions List of versions whose parents should be set.
*/
virtual void updateListData(QList<BaseVersionPtr> versions) = 0;
};

499
api/logic/CMakeLists.txt Normal file
View File

@@ -0,0 +1,499 @@
project(MultiMC_logic)
include (UnitTest)
set(CORE_SOURCES
# LOGIC - Base classes and infrastructure
BaseInstaller.h
BaseInstaller.cpp
BaseVersionList.h
BaseVersionList.cpp
InstanceList.h
InstanceList.cpp
InstanceTask.h
InstanceTask.cpp
LoggedProcess.h
LoggedProcess.cpp
MessageLevel.cpp
MessageLevel.h
BaseVersion.h
BaseInstance.h
BaseInstance.cpp
NullInstance.h
MMCZip.h
MMCZip.cpp
MMCStrings.h
MMCStrings.cpp
# Basic instance manipulation tasks (derived from InstanceTask)
InstanceCreationTask.h
InstanceCreationTask.cpp
InstanceCopyTask.h
InstanceCopyTask.cpp
InstanceImportTask.h
InstanceImportTask.cpp
# Use tracking separate from memory management
Usable.h
# Prefix tree where node names are strings between separators
SeparatorPrefixTree.h
# WARNING: globals live here
Env.h
Env.cpp
# String filters
Filter.h
Filter.cpp
# JSON parsing helpers
Json.h
Json.cpp
FileSystem.h
FileSystem.cpp
Exception.h
# RW lock protected map
RWStorage.h
# A variable that has an implicit default value and keeps track of changes
DefaultVariable.h
# a smart pointer wrapper intended for safer use with Qt signal/slot mechanisms
QObjectPtr.h
# Compression support
GZip.h
GZip.cpp
# Command line parameter parsing
Commandline.h
Commandline.cpp
# Version number string support
Version.h
Version.cpp
# A Recursive file system watcher
RecursiveFileSystemWatcher.h
RecursiveFileSystemWatcher.cpp
)
add_unit_test(FileSystem
SOURCES FileSystem_test.cpp
LIBS MultiMC_logic
DATA testdata
)
add_unit_test(GZip
SOURCES GZip_test.cpp
LIBS MultiMC_logic
)
set(PATHMATCHER_SOURCES
# Path matchers
pathmatcher/FSTreeMatcher.h
pathmatcher/IPathMatcher.h
pathmatcher/MultiMatcher.h
pathmatcher/RegexpMatcher.h
)
set(NET_SOURCES
# network stuffs
net/ByteArraySink.h
net/ChecksumValidator.h
net/Download.cpp
net/Download.h
net/FileSink.cpp
net/FileSink.h
net/HttpMetaCache.cpp
net/HttpMetaCache.h
net/MetaCacheSink.cpp
net/MetaCacheSink.h
net/NetAction.h
net/NetJob.cpp
net/NetJob.h
net/PasteUpload.cpp
net/PasteUpload.h
net/Sink.h
net/URLConstants.cpp
net/URLConstants.h
net/Validator.h
)
# Game launch logic
set(LAUNCH_SOURCES
launch/steps/PostLaunchCommand.cpp
launch/steps/PostLaunchCommand.h
launch/steps/PreLaunchCommand.cpp
launch/steps/PreLaunchCommand.h
launch/steps/TextPrint.cpp
launch/steps/TextPrint.h
launch/steps/Update.cpp
launch/steps/Update.h
launch/LaunchStep.cpp
launch/LaunchStep.h
launch/LaunchTask.cpp
launch/LaunchTask.h
launch/LogModel.cpp
launch/LogModel.h
)
# Old update system
set(UPDATE_SOURCES
updater/GoUpdate.h
updater/GoUpdate.cpp
updater/UpdateChecker.h
updater/UpdateChecker.cpp
updater/DownloadTask.h
updater/DownloadTask.cpp
)
add_unit_test(UpdateChecker
SOURCES updater/UpdateChecker_test.cpp
LIBS MultiMC_logic
DATA updater/testdata
)
add_unit_test(DownloadTask
SOURCES updater/DownloadTask_test.cpp
LIBS MultiMC_logic
DATA updater/testdata
)
# Rarely used notifications
set(NOTIFICATIONS_SOURCES
# Notifications - short warning messages
notifications/NotificationChecker.h
notifications/NotificationChecker.cpp
)
# Backend for the news bar... there's usually no news.
set(NEWS_SOURCES
# News System
news/NewsChecker.h
news/NewsChecker.cpp
news/NewsEntry.h
news/NewsEntry.cpp
)
# Icon interface
set(ICONS_SOURCES
# Icons System and related code
icons/IIconList.h
icons/IIconList.cpp
icons/IconUtils.h
icons/IconUtils.cpp
)
# Minecraft services status checker
set(STATUS_SOURCES
# Status system
status/StatusChecker.h
status/StatusChecker.cpp
)
# Support for Minecraft instances and launch
set(MINECRAFT_SOURCES
# Minecraft support
minecraft/auth/AuthSession.h
minecraft/auth/AuthSession.cpp
minecraft/auth/MojangAccountList.h
minecraft/auth/MojangAccountList.cpp
minecraft/auth/MojangAccount.h
minecraft/auth/MojangAccount.cpp
minecraft/auth/YggdrasilTask.h
minecraft/auth/YggdrasilTask.cpp
minecraft/auth/flows/AuthenticateTask.h
minecraft/auth/flows/AuthenticateTask.cpp
minecraft/auth/flows/RefreshTask.cpp
minecraft/auth/flows/RefreshTask.cpp
minecraft/auth/flows/ValidateTask.h
minecraft/auth/flows/ValidateTask.cpp
minecraft/gameoptions/GameOptions.h
minecraft/gameoptions/GameOptions.cpp
minecraft/update/AssetUpdateTask.h
minecraft/update/AssetUpdateTask.cpp
minecraft/update/FMLLibrariesTask.cpp
minecraft/update/FMLLibrariesTask.h
minecraft/update/FoldersTask.cpp
minecraft/update/FoldersTask.h
minecraft/update/LibrariesTask.cpp
minecraft/update/LibrariesTask.h
minecraft/launch/ClaimAccount.cpp
minecraft/launch/ClaimAccount.h
minecraft/launch/CreateServerResourcePacksFolder.cpp
minecraft/launch/CreateServerResourcePacksFolder.h
minecraft/launch/ModMinecraftJar.cpp
minecraft/launch/ModMinecraftJar.h
minecraft/launch/DirectJavaLaunch.cpp
minecraft/launch/DirectJavaLaunch.h
minecraft/launch/ExtractNatives.cpp
minecraft/launch/ExtractNatives.h
minecraft/launch/LauncherPartLaunch.cpp
minecraft/launch/LauncherPartLaunch.h
minecraft/launch/PrintInstanceInfo.cpp
minecraft/launch/PrintInstanceInfo.h
minecraft/launch/ReconstructAssets.cpp
minecraft/launch/ReconstructAssets.h
minecraft/legacy/LegacyModList.h
minecraft/legacy/LegacyModList.cpp
minecraft/legacy/LegacyInstance.h
minecraft/legacy/LegacyInstance.cpp
minecraft/legacy/LegacyUpgradeTask.h
minecraft/legacy/LegacyUpgradeTask.cpp
minecraft/GradleSpecifier.h
minecraft/MinecraftInstance.cpp
minecraft/MinecraftInstance.h
minecraft/LaunchProfile.cpp
minecraft/LaunchProfile.h
minecraft/Component.cpp
minecraft/Component.h
minecraft/ComponentList.cpp
minecraft/ComponentList.h
minecraft/ComponentUpdateTask.cpp
minecraft/ComponentUpdateTask.h
minecraft/MinecraftLoadAndCheck.h
minecraft/MinecraftLoadAndCheck.cpp
minecraft/MinecraftUpdate.h
minecraft/MinecraftUpdate.cpp
minecraft/MojangVersionFormat.cpp
minecraft/MojangVersionFormat.h
minecraft/Rule.cpp
minecraft/Rule.h
minecraft/OneSixVersionFormat.cpp
minecraft/OneSixVersionFormat.h
minecraft/OpSys.cpp
minecraft/OpSys.h
minecraft/ParseUtils.cpp
minecraft/ParseUtils.h
minecraft/ProfileUtils.cpp
minecraft/ProfileUtils.h
minecraft/Library.cpp
minecraft/Library.h
minecraft/MojangDownloadInfo.h
minecraft/VersionFile.cpp
minecraft/VersionFile.h
minecraft/VersionFilterData.h
minecraft/VersionFilterData.cpp
minecraft/Mod.h
minecraft/Mod.cpp
minecraft/SimpleModList.h
minecraft/SimpleModList.cpp
minecraft/World.h
minecraft/World.cpp
minecraft/WorldList.h
minecraft/WorldList.cpp
# Assets
minecraft/AssetsUtils.h
minecraft/AssetsUtils.cpp
# Forge and all things forge related
minecraft/forge/ForgeXzDownload.h
minecraft/forge/ForgeXzDownload.cpp
# Skin upload utilities
minecraft/SkinUpload.cpp
minecraft/SkinUpload.h
)
add_unit_test(GradleSpecifier
SOURCES minecraft/GradleSpecifier_test.cpp
LIBS MultiMC_logic
)
add_unit_test(MojangVersionFormat
SOURCES minecraft/MojangVersionFormat_test.cpp
LIBS MultiMC_logic
DATA minecraft/testdata
)
add_unit_test(Library
SOURCES minecraft/Library_test.cpp
LIBS MultiMC_logic
)
# FIXME: shares data with FileSystem test
add_unit_test(SimpleModList
SOURCES minecraft/SimpleModList_test.cpp
DATA testdata
LIBS MultiMC_logic
)
add_unit_test(ParseUtils
SOURCES minecraft/ParseUtils_test.cpp
LIBS MultiMC_logic
)
# the screenshots feature
set(SCREENSHOTS_SOURCES
screenshots/Screenshot.h
screenshots/ImgurUpload.h
screenshots/ImgurUpload.cpp
screenshots/ImgurAlbumCreation.h
screenshots/ImgurAlbumCreation.cpp
)
set(TASKS_SOURCES
# Tasks
tasks/Task.h
tasks/Task.cpp
tasks/SequentialTask.h
tasks/SequentialTask.cpp
)
set(SETTINGS_SOURCES
# Settings
settings/INIFile.cpp
settings/INIFile.h
settings/INISettingsObject.cpp
settings/INISettingsObject.h
settings/OverrideSetting.cpp
settings/OverrideSetting.h
settings/PassthroughSetting.cpp
settings/PassthroughSetting.h
settings/Setting.cpp
settings/Setting.h
settings/SettingsObject.cpp
settings/SettingsObject.h
)
add_unit_test(INIFile
SOURCES settings/INIFile_test.cpp
LIBS MultiMC_logic
)
set(JAVA_SOURCES
# Java related code
java/launch/CheckJava.cpp
java/launch/CheckJava.h
java/JavaChecker.h
java/JavaChecker.cpp
java/JavaCheckerJob.h
java/JavaCheckerJob.cpp
java/JavaInstall.h
java/JavaInstall.cpp
java/JavaInstallList.h
java/JavaInstallList.cpp
java/JavaUtils.h
java/JavaUtils.cpp
java/JavaVersion.h
java/JavaVersion.cpp
)
add_unit_test(JavaVersion
SOURCES java/JavaVersion_test.cpp
LIBS MultiMC_logic
)
set(TRANSLATIONS_SOURCES
translations/TranslationsModel.h
translations/TranslationsModel.cpp
translations/POTranslator.h
translations/POTranslator.cpp
)
set(TOOLS_SOURCES
# Tools
tools/BaseExternalTool.cpp
tools/BaseExternalTool.h
tools/BaseProfiler.cpp
tools/BaseProfiler.h
tools/JProfiler.cpp
tools/JProfiler.h
tools/JVisualVM.cpp
tools/JVisualVM.h
tools/MCEditTool.cpp
tools/MCEditTool.h
)
set(META_SOURCES
# Metadata sources
meta/JsonFormat.cpp
meta/JsonFormat.h
meta/BaseEntity.cpp
meta/BaseEntity.h
meta/VersionList.cpp
meta/VersionList.h
meta/Version.cpp
meta/Version.h
meta/Index.cpp
meta/Index.h
)
set(FTB_SOURCES
modplatform/ftb/FtbPackFetchTask.h
modplatform/ftb/FtbPackFetchTask.cpp
modplatform/ftb/FtbPackInstallTask.h
modplatform/ftb/FtbPackInstallTask.cpp
modplatform/ftb/FtbPrivatePackManager.h
modplatform/ftb/FtbPrivatePackManager.cpp
modplatform/ftb/PackHelpers.h
)
set(FLAME_SOURCES
# Flame
modplatform/flame/PackManifest.h
modplatform/flame/PackManifest.cpp
modplatform/flame/FileResolvingTask.h
modplatform/flame/FileResolvingTask.cpp
)
add_unit_test(Index
SOURCES meta/Index_test.cpp
LIBS MultiMC_logic
)
################################ COMPILE ################################
# we need zlib
find_package(ZLIB REQUIRED)
set(LOGIC_SOURCES
${CORE_SOURCES}
${PATHMATCHER_SOURCES}
${NET_SOURCES}
${LAUNCH_SOURCES}
${UPDATE_SOURCES}
${NOTIFICATIONS_SOURCES}
${NEWS_SOURCES}
${STATUS_SOURCES}
${MINECRAFT_SOURCES}
${SCREENSHOTS_SOURCES}
${TASKS_SOURCES}
${SETTINGS_SOURCES}
${JAVA_SOURCES}
${TRANSLATIONS_SOURCES}
${TOOLS_SOURCES}
${META_SOURCES}
${ICONS_SOURCES}
${FTB_SOURCES}
${FLAME_SOURCES}
)
message(STATUS "FOO! ${LOGIC_SOURCES}")
add_library(MultiMC_logic SHARED ${LOGIC_SOURCES})
set_target_properties(MultiMC_logic PROPERTIES CXX_VISIBILITY_PRESET hidden VISIBILITY_INLINES_HIDDEN 1)
generate_export_header(MultiMC_logic)
# Link
target_link_libraries(MultiMC_logic xz-embedded MultiMC_unpack200 systeminfo MultiMC_quazip MultiMC_classparser ${NBT_NAME} ${ZLIB_LIBRARIES})
target_link_libraries(MultiMC_logic Qt5::Core Qt5::Xml Qt5::Network Qt5::Concurrent)
# Mark and export headers
target_include_directories(MultiMC_logic PUBLIC "${CMAKE_CURRENT_BINARY_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}" PRIVATE "${ZLIB_INCLUDE_DIRS}")
# Install it
install(
TARGETS MultiMC_logic
RUNTIME DESTINATION ${LIBRARY_DEST_DIR}
LIBRARY DESTINATION ${LIBRARY_DEST_DIR}
)

483
api/logic/Commandline.cpp Normal file
View File

@@ -0,0 +1,483 @@
/* Copyright 2013-2019 MultiMC Contributors
*
* Authors: Orochimarufan <orochimarufan.x3@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "Commandline.h"
/**
* @file libutil/src/cmdutils.cpp
*/
namespace Commandline
{
// commandline splitter
QStringList splitArgs(QString args)
{
QStringList argv;
QString current;
bool escape = false;
QChar inquotes;
for (int i = 0; i < args.length(); i++)
{
QChar cchar = args.at(i);
// \ escaped
if (escape)
{
current += cchar;
escape = false;
// in "quotes"
}
else if (!inquotes.isNull())
{
if (cchar == '\\')
escape = true;
else if (cchar == inquotes)
inquotes = 0;
else
current += cchar;
// otherwise
}
else
{
if (cchar == ' ')
{
if (!current.isEmpty())
{
argv << current;
current.clear();
}
}
else if (cchar == '"' || cchar == '\'')
inquotes = cchar;
else
current += cchar;
}
}
if (!current.isEmpty())
argv << current;
return argv;
}
Parser::Parser(FlagStyle::Enum flagStyle, ArgumentStyle::Enum argStyle)
{
m_flagStyle = flagStyle;
m_argStyle = argStyle;
}
// styles setter/getter
void Parser::setArgumentStyle(ArgumentStyle::Enum style)
{
m_argStyle = style;
}
ArgumentStyle::Enum Parser::argumentStyle()
{
return m_argStyle;
}
void Parser::setFlagStyle(FlagStyle::Enum style)
{
m_flagStyle = style;
}
FlagStyle::Enum Parser::flagStyle()
{
return m_flagStyle;
}
// setup methods
void Parser::addSwitch(QString name, bool def)
{
if (m_params.contains(name))
throw "Name not unique";
OptionDef *param = new OptionDef;
param->type = otSwitch;
param->name = name;
param->metavar = QString("<%1>").arg(name);
param->def = def;
m_options[name] = param;
m_params[name] = (CommonDef *)param;
m_optionList.append(param);
}
void Parser::addOption(QString name, QVariant def)
{
if (m_params.contains(name))
throw "Name not unique";
OptionDef *param = new OptionDef;
param->type = otOption;
param->name = name;
param->metavar = QString("<%1>").arg(name);
param->def = def;
m_options[name] = param;
m_params[name] = (CommonDef *)param;
m_optionList.append(param);
}
void Parser::addArgument(QString name, bool required, QVariant def)
{
if (m_params.contains(name))
throw "Name not unique";
PositionalDef *param = new PositionalDef;
param->name = name;
param->def = def;
param->required = required;
param->metavar = name;
m_positionals.append(param);
m_params[name] = (CommonDef *)param;
}
void Parser::addDocumentation(QString name, QString doc, QString metavar)
{
if (!m_params.contains(name))
throw "Name does not exist";
CommonDef *param = m_params[name];
param->doc = doc;
if (!metavar.isNull())
param->metavar = metavar;
}
void Parser::addShortOpt(QString name, QChar flag)
{
if (!m_params.contains(name))
throw "Name does not exist";
if (!m_options.contains(name))
throw "Name is not an Option or Swtich";
OptionDef *param = m_options[name];
m_flags[flag] = param;
param->flag = flag;
}
// help methods
QString Parser::compileHelp(QString progName, int helpIndent, bool useFlags)
{
QStringList help;
help << compileUsage(progName, useFlags) << "\r\n";
// positionals
if (!m_positionals.isEmpty())
{
help << "\r\n";
help << "Positional arguments:\r\n";
QListIterator<PositionalDef *> it2(m_positionals);
while (it2.hasNext())
{
PositionalDef *param = it2.next();
help << " " << param->metavar;
help << " " << QString(helpIndent - param->metavar.length() - 1, ' ');
help << param->doc << "\r\n";
}
}
// Options
if (!m_optionList.isEmpty())
{
help << "\r\n";
QString optPrefix, flagPrefix;
getPrefix(optPrefix, flagPrefix);
help << "Options & Switches:\r\n";
QListIterator<OptionDef *> it(m_optionList);
while (it.hasNext())
{
OptionDef *option = it.next();
help << " ";
int nameLength = optPrefix.length() + option->name.length();
if (!option->flag.isNull())
{
nameLength += 3 + flagPrefix.length();
help << flagPrefix << option->flag << ", ";
}
help << optPrefix << option->name;
if (option->type == otOption)
{
QString arg = QString("%1%2").arg(
((m_argStyle == ArgumentStyle::Equals) ? "=" : " "), option->metavar);
nameLength += arg.length();
help << arg;
}
help << " " << QString(helpIndent - nameLength - 1, ' ');
help << option->doc << "\r\n";
}
}
return help.join("");
}
QString Parser::compileUsage(QString progName, bool useFlags)
{
QStringList usage;
usage << "Usage: " << progName;
QString optPrefix, flagPrefix;
getPrefix(optPrefix, flagPrefix);
// options
QListIterator<OptionDef *> it(m_optionList);
while (it.hasNext())
{
OptionDef *option = it.next();
usage << " [";
if (!option->flag.isNull() && useFlags)
usage << flagPrefix << option->flag;
else
usage << optPrefix << option->name;
if (option->type == otOption)
usage << ((m_argStyle == ArgumentStyle::Equals) ? "=" : " ") << option->metavar;
usage << "]";
}
// arguments
QListIterator<PositionalDef *> it2(m_positionals);
while (it2.hasNext())
{
PositionalDef *param = it2.next();
usage << " " << (param->required ? "<" : "[");
usage << param->metavar;
usage << (param->required ? ">" : "]");
}
return usage.join("");
}
// parsing
QHash<QString, QVariant> Parser::parse(QStringList argv)
{
QHash<QString, QVariant> map;
QStringListIterator it(argv);
QString programName = it.next();
QString optionPrefix;
QString flagPrefix;
QListIterator<PositionalDef *> positionals(m_positionals);
QStringList expecting;
getPrefix(optionPrefix, flagPrefix);
while (it.hasNext())
{
QString arg = it.next();
if (!expecting.isEmpty())
// we were expecting an argument
{
QString name = expecting.first();
/*
if (map.contains(name))
throw ParsingError(
QString("Option %2%1 was given multiple times").arg(name, optionPrefix));
*/
map[name] = QVariant(arg);
expecting.removeFirst();
continue;
}
if (arg.startsWith(optionPrefix))
// we have an option
{
// qDebug("Found option %s", qPrintable(arg));
QString name = arg.mid(optionPrefix.length());
QString equals;
if ((m_argStyle == ArgumentStyle::Equals ||
m_argStyle == ArgumentStyle::SpaceAndEquals) &&
name.contains("="))
{
int i = name.indexOf("=");
equals = name.mid(i + 1);
name = name.left(i);
}
if (m_options.contains(name))
{
/*
if (map.contains(name))
throw ParsingError(QString("Option %2%1 was given multiple times")
.arg(name, optionPrefix));
*/
OptionDef *option = m_options[name];
if (option->type == otSwitch)
map[name] = true;
else // if (option->type == otOption)
{
if (m_argStyle == ArgumentStyle::Space)
expecting.append(name);
else if (!equals.isNull())
map[name] = equals;
else if (m_argStyle == ArgumentStyle::SpaceAndEquals)
expecting.append(name);
else
throw ParsingError(QString("Option %2%1 reqires an argument.")
.arg(name, optionPrefix));
}
continue;
}
throw ParsingError(QString("Unknown Option %2%1").arg(name, optionPrefix));
}
if (arg.startsWith(flagPrefix))
// we have (a) flag(s)
{
// qDebug("Found flags %s", qPrintable(arg));
QString flags = arg.mid(flagPrefix.length());
QString equals;
if ((m_argStyle == ArgumentStyle::Equals ||
m_argStyle == ArgumentStyle::SpaceAndEquals) &&
flags.contains("="))
{
int i = flags.indexOf("=");
equals = flags.mid(i + 1);
flags = flags.left(i);
}
for (int i = 0; i < flags.length(); i++)
{
QChar flag = flags.at(i);
if (!m_flags.contains(flag))
throw ParsingError(QString("Unknown flag %2%1").arg(flag, flagPrefix));
OptionDef *option = m_flags[flag];
/*
if (map.contains(option->name))
throw ParsingError(QString("Option %2%1 was given multiple times")
.arg(option->name, optionPrefix));
*/
if (option->type == otSwitch)
map[option->name] = true;
else // if (option->type == otOption)
{
if (m_argStyle == ArgumentStyle::Space)
expecting.append(option->name);
else if (!equals.isNull())
if (i == flags.length() - 1)
map[option->name] = equals;
else
throw ParsingError(QString("Flag %4%2 of Argument-requiring Option "
"%1 not last flag in %4%3")
.arg(option->name, flag, flags, flagPrefix));
else if (m_argStyle == ArgumentStyle::SpaceAndEquals)
expecting.append(option->name);
else
throw ParsingError(QString("Option %1 reqires an argument. (flag %3%2)")
.arg(option->name, flag, flagPrefix));
}
}
continue;
}
// must be a positional argument
if (!positionals.hasNext())
throw ParsingError(QString("Don't know what to do with '%1'").arg(arg));
PositionalDef *param = positionals.next();
map[param->name] = arg;
}
// check if we're missing something
if (!expecting.isEmpty())
throw ParsingError(QString("Was still expecting arguments for %2%1").arg(
expecting.join(QString(", ") + optionPrefix), optionPrefix));
while (positionals.hasNext())
{
PositionalDef *param = positionals.next();
if (param->required)
throw ParsingError(
QString("Missing required positional argument '%1'").arg(param->name));
else
map[param->name] = param->def;
}
// fill out gaps
QListIterator<OptionDef *> iter(m_optionList);
while (iter.hasNext())
{
OptionDef *option = iter.next();
if (!map.contains(option->name))
map[option->name] = option->def;
}
return map;
}
// clear defs
void Parser::clear()
{
m_flags.clear();
m_params.clear();
m_options.clear();
QMutableListIterator<OptionDef *> it(m_optionList);
while (it.hasNext())
{
OptionDef *option = it.next();
it.remove();
delete option;
}
QMutableListIterator<PositionalDef *> it2(m_positionals);
while (it2.hasNext())
{
PositionalDef *arg = it2.next();
it2.remove();
delete arg;
}
}
// Destructor
Parser::~Parser()
{
clear();
}
// getPrefix
void Parser::getPrefix(QString &opt, QString &flag)
{
if (m_flagStyle == FlagStyle::Windows)
opt = flag = "/";
else if (m_flagStyle == FlagStyle::Unix)
opt = flag = "-";
// else if (m_flagStyle == FlagStyle::GNU)
else
{
opt = "--";
flag = "-";
}
}
// ParsingError
ParsingError::ParsingError(const QString &what) : std::runtime_error(what.toStdString())
{
}
}

252
api/logic/Commandline.h Normal file
View File

@@ -0,0 +1,252 @@
/* Copyright 2013-2019 MultiMC Contributors
*
* Authors: Orochimarufan <orochimarufan.x3@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <exception>
#include <stdexcept>
#include <QString>
#include <QVariant>
#include <QHash>
#include <QStringList>
#include "multimc_logic_export.h"
/**
* @file libutil/include/cmdutils.h
* @brief commandline parsing and processing utilities
*/
namespace Commandline
{
/**
* @brief split a string into argv items like a shell would do
* @param args the argument string
* @return a QStringList containing all arguments
*/
MULTIMC_LOGIC_EXPORT QStringList splitArgs(QString args);
/**
* @brief The FlagStyle enum
* Specifies how flags are decorated
*/
namespace FlagStyle
{
enum Enum
{
GNU, /**< --option and -o (GNU Style) */
Unix, /**< -option and -o (Unix Style) */
Windows, /**< /option and /o (Windows Style) */
#ifdef Q_OS_WIN32
Default = Windows
#else
Default = GNU
#endif
};
}
/**
* @brief The ArgumentStyle enum
*/
namespace ArgumentStyle
{
enum Enum
{
Space, /**< --option=value */
Equals, /**< --option value */
SpaceAndEquals, /**< --option[= ]value */
#ifdef Q_OS_WIN32
Default = Equals
#else
Default = SpaceAndEquals
#endif
};
}
/**
* @brief The ParsingError class
*/
class MULTIMC_LOGIC_EXPORT ParsingError : public std::runtime_error
{
public:
ParsingError(const QString &what);
};
/**
* @brief The Parser class
*/
class MULTIMC_LOGIC_EXPORT Parser
{
public:
/**
* @brief Parser constructor
* @param flagStyle the FlagStyle to use in this Parser
* @param argStyle the ArgumentStyle to use in this Parser
*/
Parser(FlagStyle::Enum flagStyle = FlagStyle::Default,
ArgumentStyle::Enum argStyle = ArgumentStyle::Default);
/**
* @brief set the flag style
* @param style
*/
void setFlagStyle(FlagStyle::Enum style);
/**
* @brief get the flag style
* @return
*/
FlagStyle::Enum flagStyle();
/**
* @brief set the argument style
* @param style
*/
void setArgumentStyle(ArgumentStyle::Enum style);
/**
* @brief get the argument style
* @return
*/
ArgumentStyle::Enum argumentStyle();
/**
* @brief define a boolean switch
* @param name the parameter name
* @param def the default value
*/
void addSwitch(QString name, bool def = false);
/**
* @brief define an option that takes an additional argument
* @param name the parameter name
* @param def the default value
*/
void addOption(QString name, QVariant def = QVariant());
/**
* @brief define a positional argument
* @param name the parameter name
* @param required wether this argument is required
* @param def the default value
*/
void addArgument(QString name, bool required = true, QVariant def = QVariant());
/**
* @brief adds a flag to an existing parameter
* @param name the (existing) parameter name
* @param flag the flag character
* @see addSwitch addArgument addOption
* Note: any one parameter can only have one flag
*/
void addShortOpt(QString name, QChar flag);
/**
* @brief adds documentation to a Parameter
* @param name the parameter name
* @param metavar a string to be displayed as placeholder for the value
* @param doc a QString containing the documentation
* Note: on positional arguments, metavar replaces the name as displayed.
* on options , metavar replaces the value placeholder
*/
void addDocumentation(QString name, QString doc, QString metavar = QString());
/**
* @brief generate a help message
* @param progName the program name to use in the help message
* @param helpIndent how much the parameter documentation should be indented
* @param flagsInUsage whether we should use flags instead of options in the usage
* @return a help message
*/
QString compileHelp(QString progName, int helpIndent = 22, bool flagsInUsage = true);
/**
* @brief generate a short usage message
* @param progName the program name to use in the usage message
* @param useFlags whether we should use flags instead of options
* @return a usage message
*/
QString compileUsage(QString progName, bool useFlags = true);
/**
* @brief parse
* @param argv a QStringList containing the program ARGV
* @return a QHash mapping argument names to their values
*/
QHash<QString, QVariant> parse(QStringList argv);
/**
* @brief clear all definitions
*/
void clear();
~Parser();
private:
FlagStyle::Enum m_flagStyle;
ArgumentStyle::Enum m_argStyle;
enum OptionType
{
otSwitch,
otOption
};
// Important: the common part MUST BE COMMON ON ALL THREE structs
struct CommonDef
{
QString name;
QString doc;
QString metavar;
QVariant def;
};
struct OptionDef
{
// common
QString name;
QString doc;
QString metavar;
QVariant def;
// option
OptionType type;
QChar flag;
};
struct PositionalDef
{
// common
QString name;
QString doc;
QString metavar;
QVariant def;
// positional
bool required;
};
QHash<QString, OptionDef *> m_options;
QHash<QChar, OptionDef *> m_flags;
QHash<QString, CommonDef *> m_params;
QList<PositionalDef *> m_positionals;
QList<OptionDef *> m_optionList;
void getPrefix(QString &opt, QString &flag);
};
}

View File

@@ -0,0 +1,35 @@
#pragma once
template <typename T>
class DefaultVariable
{
public:
DefaultVariable(const T & value)
{
defaultValue = value;
}
DefaultVariable<T> & operator =(const T & value)
{
currentValue = value;
is_default = currentValue == defaultValue;
is_explicit = true;
return *this;
}
operator const T &() const
{
return is_default ? defaultValue : currentValue;
}
bool isDefault() const
{
return is_default;
}
bool isExplicit() const
{
return is_explicit;
}
private:
T currentValue;
T defaultValue;
bool is_default = true;
bool is_explicit = false;
};

209
api/logic/Env.cpp Normal file
View File

@@ -0,0 +1,209 @@
#include "Env.h"
#include "net/HttpMetaCache.h"
#include "BaseVersion.h"
#include "BaseVersionList.h"
#include <QDir>
#include <QCoreApplication>
#include <QNetworkProxy>
#include <QNetworkAccessManager>
#include <QDebug>
#include "tasks/Task.h"
#include "meta/Index.h"
#include "FileSystem.h"
#include <QDebug>
struct Env::Private
{
QNetworkAccessManager m_qnam;
shared_qobject_ptr<HttpMetaCache> m_metacache;
std::shared_ptr<IIconList> m_iconlist;
shared_qobject_ptr<Meta::Index> m_metadataIndex;
QString m_jarsPath;
QSet<QString> m_features;
};
static Env * instance;
/*
* The *NEW* global rat nest of an object. Handle with care.
*/
Env::Env()
{
d = new Private();
}
Env::~Env()
{
delete d;
}
Env& Env::Env::getInstance()
{
if(!instance)
{
instance = new Env();
}
return *instance;
}
void Env::dispose()
{
delete instance;
instance = nullptr;
}
shared_qobject_ptr< HttpMetaCache > Env::metacache()
{
return d->m_metacache;
}
QNetworkAccessManager& Env::qnam() const
{
return d->m_qnam;
}
std::shared_ptr<IIconList> Env::icons()
{
return d->m_iconlist;
}
void Env::registerIconList(std::shared_ptr<IIconList> iconlist)
{
d->m_iconlist = iconlist;
}
shared_qobject_ptr<Meta::Index> Env::metadataIndex()
{
if (!d->m_metadataIndex)
{
d->m_metadataIndex.reset(new Meta::Index());
}
return d->m_metadataIndex;
}
void Env::initHttpMetaCache()
{
auto &m_metacache = d->m_metacache;
m_metacache.reset(new HttpMetaCache("metacache"));
m_metacache->addBase("asset_indexes", QDir("assets/indexes").absolutePath());
m_metacache->addBase("asset_objects", QDir("assets/objects").absolutePath());
m_metacache->addBase("versions", QDir("versions").absolutePath());
m_metacache->addBase("libraries", QDir("libraries").absolutePath());
m_metacache->addBase("minecraftforge", QDir("mods/minecraftforge").absolutePath());
m_metacache->addBase("fmllibs", QDir("mods/minecraftforge/libs").absolutePath());
m_metacache->addBase("liteloader", QDir("mods/liteloader").absolutePath());
m_metacache->addBase("general", QDir("cache").absolutePath());
m_metacache->addBase("FTBPacks", QDir("cache/FTBPacks").absolutePath());
m_metacache->addBase("skins", QDir("accounts/skins").absolutePath());
m_metacache->addBase("root", QDir::currentPath());
m_metacache->addBase("translations", QDir("translations").absolutePath());
m_metacache->addBase("icons", QDir("cache/icons").absolutePath());
m_metacache->addBase("meta", QDir("meta").absolutePath());
m_metacache->Load();
}
void Env::updateProxySettings(QString proxyTypeStr, QString addr, int port, QString user, QString password)
{
// Set the application proxy settings.
if (proxyTypeStr == "SOCKS5")
{
QNetworkProxy::setApplicationProxy(
QNetworkProxy(QNetworkProxy::Socks5Proxy, addr, port, user, password));
}
else if (proxyTypeStr == "HTTP")
{
QNetworkProxy::setApplicationProxy(
QNetworkProxy(QNetworkProxy::HttpProxy, addr, port, user, password));
}
else if (proxyTypeStr == "None")
{
// If we have no proxy set, set no proxy and return.
QNetworkProxy::setApplicationProxy(QNetworkProxy(QNetworkProxy::NoProxy));
}
else
{
// If we have "Default" selected, set Qt to use the system proxy settings.
QNetworkProxyFactory::setUseSystemConfiguration(true);
}
qDebug() << "Detecting proxy settings...";
QNetworkProxy proxy = QNetworkProxy::applicationProxy();
d->m_qnam.setProxy(proxy);
QString proxyDesc;
if (proxy.type() == QNetworkProxy::NoProxy)
{
qDebug() << "Using no proxy is an option!";
return;
}
switch (proxy.type())
{
case QNetworkProxy::DefaultProxy:
proxyDesc = "Default proxy: ";
break;
case QNetworkProxy::Socks5Proxy:
proxyDesc = "Socks5 proxy: ";
break;
case QNetworkProxy::HttpProxy:
proxyDesc = "HTTP proxy: ";
break;
case QNetworkProxy::HttpCachingProxy:
proxyDesc = "HTTP caching: ";
break;
case QNetworkProxy::FtpCachingProxy:
proxyDesc = "FTP caching: ";
break;
default:
proxyDesc = "DERP proxy: ";
break;
}
proxyDesc += QString("%3@%1:%2 pass %4")
.arg(proxy.hostName())
.arg(proxy.port())
.arg(proxy.user())
.arg(proxy.password());
qDebug() << proxyDesc;
}
QString Env::getJarsPath()
{
if(d->m_jarsPath.isEmpty())
{
return FS::PathCombine(QCoreApplication::applicationDirPath(), "jars");
}
return d->m_jarsPath;
}
void Env::setJarsPath(const QString& path)
{
d->m_jarsPath = path;
}
void Env::enableFeature(const QString& featureName, bool state)
{
if(state)
{
d->m_features.insert(featureName);
}
else
{
d->m_features.remove(featureName);
}
}
bool Env::isFeatureEnabled(const QString& featureName) const
{
return d->m_features.contains(featureName);
}
void Env::getEnabledFeatures(QSet<QString>& features) const
{
features = d->m_features;
}
void Env::setEnabledFeatures(const QSet<QString>& features) const
{
d->m_features = features;
}

65
api/logic/Env.h Normal file
View File

@@ -0,0 +1,65 @@
#pragma once
#include <memory>
#include "icons/IIconList.h"
#include <QString>
#include <QMap>
#include "multimc_logic_export.h"
#include "QObjectPtr.h"
class QNetworkAccessManager;
class HttpMetaCache;
class BaseVersionList;
class BaseVersion;
namespace Meta
{
class Index;
}
#if defined(ENV)
#undef ENV
#endif
#define ENV (Env::getInstance())
class MULTIMC_LOGIC_EXPORT Env
{
friend class MultiMC;
private:
struct Private;
Env();
~Env();
static void dispose();
public:
static Env& getInstance();
QNetworkAccessManager &qnam() const;
shared_qobject_ptr<HttpMetaCache> metacache();
std::shared_ptr<IIconList> icons();
/// init the cache. FIXME: possible future hook point
void initHttpMetaCache();
/// Updates the application proxy settings from the settings object.
void updateProxySettings(QString proxyTypeStr, QString addr, int port, QString user, QString password);
void registerIconList(std::shared_ptr<IIconList> iconlist);
shared_qobject_ptr<Meta::Index> metadataIndex();
QString getJarsPath();
void setJarsPath(const QString & path);
bool isFeatureEnabled(const QString & featureName) const;
void enableFeature(const QString & featureName, bool state = true);
void getEnabledFeatures(QSet<QString> & features) const;
void setEnabledFeatures(const QSet<QString> & features) const;
protected:
Private * d;
};

34
api/logic/Exception.h Normal file
View File

@@ -0,0 +1,34 @@
// Licensed under the Apache-2.0 license. See README.md for details.
#pragma once
#include <QString>
#include <QDebug>
#include <exception>
#include "multimc_logic_export.h"
class MULTIMC_LOGIC_EXPORT Exception : public std::exception
{
public:
Exception(const QString &message) : std::exception(), m_message(message)
{
qCritical() << "Exception:" << message;
}
Exception(const Exception &other)
: std::exception(), m_message(other.cause())
{
}
virtual ~Exception() noexcept {}
const char *what() const noexcept
{
return m_message.toLatin1().constData();
}
QString cause() const
{
return m_message;
}
private:
QString m_message;
};

View File

@@ -0,0 +1,43 @@
#pragma once
template <typename T>
inline void clamp(T& current, T min, T max)
{
if (current < min)
{
current = min;
}
else if(current > max)
{
current = max;
}
}
// List of numbers from min to max. Next is exponent times bigger than previous.
class ExponentialSeries
{
public:
ExponentialSeries(unsigned min, unsigned max, unsigned exponent = 2)
{
m_current = m_min = min;
m_max = max;
m_exponent = exponent;
}
void reset()
{
m_current = m_min;
}
unsigned operator()()
{
unsigned retval = m_current;
m_current *= m_exponent;
clamp(m_current, m_min, m_max);
return retval;
}
unsigned m_current;
unsigned m_min;
unsigned m_max;
unsigned m_exponent;
};

452
api/logic/FileSystem.cpp Normal file
View File

@@ -0,0 +1,452 @@
// Licensed under the Apache-2.0 license. See README.md for details.
#include "FileSystem.h"
#include <QDir>
#include <QFile>
#include <QSaveFile>
#include <QFileInfo>
#include <QDebug>
#include <QUrl>
#include <QStandardPaths>
#include <QTextStream>
#if defined Q_OS_WIN32
#include <windows.h>
#include <string>
#include <sys/utime.h>
#include <winnls.h>
#include <shobjidl.h>
#include <objbase.h>
#include <objidl.h>
#include <shlguid.h>
#include <shlobj.h>
#else
#include <utime.h>
#endif
namespace FS {
void ensureExists(const QDir &dir)
{
if (!QDir().mkpath(dir.absolutePath()))
{
throw FileSystemException("Unable to create folder " + dir.dirName() + " (" +
dir.absolutePath() + ")");
}
}
void write(const QString &filename, const QByteArray &data)
{
ensureExists(QFileInfo(filename).dir());
QSaveFile file(filename);
if (!file.open(QSaveFile::WriteOnly))
{
throw FileSystemException("Couldn't open " + filename + " for writing: " +
file.errorString());
}
if (data.size() != file.write(data))
{
throw FileSystemException("Error writing data to " + filename + ": " +
file.errorString());
}
if (!file.commit())
{
throw FileSystemException("Error while committing data to " + filename + ": " +
file.errorString());
}
}
QByteArray read(const QString &filename)
{
QFile file(filename);
if (!file.open(QFile::ReadOnly))
{
throw FileSystemException("Unable to open " + filename + " for reading: " +
file.errorString());
}
const qint64 size = file.size();
QByteArray data(int(size), 0);
const qint64 ret = file.read(data.data(), size);
if (ret == -1 || ret != size)
{
throw FileSystemException("Error reading data from " + filename + ": " +
file.errorString());
}
return data;
}
bool updateTimestamp(const QString& filename)
{
#ifdef Q_OS_WIN32
std::wstring filename_utf_16 = filename.toStdWString();
return (_wutime64(filename_utf_16.c_str(), nullptr) == 0);
#else
QByteArray filenameBA = QFile::encodeName(filename);
return (utime(filenameBA.data(), nullptr) == 0);
#endif
}
bool ensureFilePathExists(QString filenamepath)
{
QFileInfo a(filenamepath);
QDir dir;
QString ensuredPath = a.path();
bool success = dir.mkpath(ensuredPath);
return success;
}
bool ensureFolderPathExists(QString foldernamepath)
{
QFileInfo a(foldernamepath);
QDir dir;
QString ensuredPath = a.filePath();
bool success = dir.mkpath(ensuredPath);
return success;
}
bool copy::operator()(const QString &offset)
{
//NOTE always deep copy on windows. the alternatives are too messy.
#if defined Q_OS_WIN32
m_followSymlinks = true;
#endif
auto src = PathCombine(m_src.absolutePath(), offset);
auto dst = PathCombine(m_dst.absolutePath(), offset);
QFileInfo currentSrc(src);
if (!currentSrc.exists())
return false;
if(!m_followSymlinks && currentSrc.isSymLink())
{
qDebug() << "creating symlink" << src << " - " << dst;
if (!ensureFilePathExists(dst))
{
qWarning() << "Cannot create path!";
return false;
}
return QFile::link(currentSrc.symLinkTarget(), dst);
}
else if(currentSrc.isFile())
{
qDebug() << "copying file" << src << " - " << dst;
if (!ensureFilePathExists(dst))
{
qWarning() << "Cannot create path!";
return false;
}
return QFile::copy(src, dst);
}
else if(currentSrc.isDir())
{
qDebug() << "recursing" << offset;
if (!ensureFolderPathExists(dst))
{
qWarning() << "Cannot create path!";
return false;
}
QDir currentDir(src);
for(auto & f : currentDir.entryList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot | QDir::Hidden | QDir::System))
{
auto inner_offset = PathCombine(offset, f);
// ignore and skip stuff that matches the blacklist.
if(m_blacklist && m_blacklist->matches(inner_offset))
{
continue;
}
if(!operator()(inner_offset))
{
qWarning() << "Failed to copy" << inner_offset;
return false;
}
}
}
else
{
qCritical() << "Copy ERROR: Unknown filesystem object:" << src;
return false;
}
return true;
}
bool deletePath(QString path)
{
bool OK = true;
QDir dir(path);
if (!dir.exists())
{
return OK;
}
auto allEntries = dir.entryInfoList(QDir::NoDotAndDotDot | QDir::System | QDir::Hidden |
QDir::AllDirs | QDir::Files,
QDir::DirsFirst);
for(auto & info: allEntries)
{
#if defined Q_OS_WIN32
QString nativePath = QDir::toNativeSeparators(info.absoluteFilePath());
auto wString = nativePath.toStdWString();
DWORD dwAttrs = GetFileAttributesW(wString.c_str());
// Windows: check for junctions, reparse points and other nasty things of that sort
if(dwAttrs & FILE_ATTRIBUTE_REPARSE_POINT)
{
if (info.isFile())
{
OK &= QFile::remove(info.absoluteFilePath());
}
else if (info.isDir())
{
OK &= dir.rmdir(info.absoluteFilePath());
}
}
#else
// We do not trust Qt with reparse points, but do trust it with unix symlinks.
if(info.isSymLink())
{
OK &= QFile::remove(info.absoluteFilePath());
}
#endif
else if (info.isDir())
{
OK &= deletePath(info.absoluteFilePath());
}
else if (info.isFile())
{
OK &= QFile::remove(info.absoluteFilePath());
}
else
{
OK = false;
qCritical() << "Delete ERROR: Unknown filesystem object:" << info.absoluteFilePath();
}
}
OK &= dir.rmdir(dir.absolutePath());
return OK;
}
QString PathCombine(const QString & path1, const QString & path2)
{
if(!path1.size())
return path2;
if(!path2.size())
return path1;
return QDir::cleanPath(path1 + QDir::separator() + path2);
}
QString PathCombine(const QString & path1, const QString & path2, const QString & path3)
{
return PathCombine(PathCombine(path1, path2), path3);
}
QString PathCombine(const QString & path1, const QString & path2, const QString & path3, const QString & path4)
{
return PathCombine(PathCombine(path1, path2, path3), path4);
}
QString AbsolutePath(QString path)
{
return QFileInfo(path).absolutePath();
}
QString ResolveExecutable(QString path)
{
if (path.isEmpty())
{
return QString();
}
if(!path.contains('/'))
{
path = QStandardPaths::findExecutable(path);
}
QFileInfo pathInfo(path);
if(!pathInfo.exists() || !pathInfo.isExecutable())
{
return QString();
}
return pathInfo.absoluteFilePath();
}
/**
* Normalize path
*
* Any paths inside the current folder will be normalized to relative paths (to current)
* Other paths will be made absolute
*/
QString NormalizePath(QString path)
{
QDir a = QDir::currentPath();
QString currentAbsolute = a.absolutePath();
QDir b(path);
QString newAbsolute = b.absolutePath();
if (newAbsolute.startsWith(currentAbsolute))
{
return a.relativeFilePath(newAbsolute);
}
else
{
return newAbsolute;
}
}
QString badFilenameChars = "\"\\/?<>:*|!+\r\n";
QString RemoveInvalidFilenameChars(QString string, QChar replaceWith)
{
for (int i = 0; i < string.length(); i++)
{
if (badFilenameChars.contains(string[i]))
{
string[i] = replaceWith;
}
}
return string;
}
QString DirNameFromString(QString string, QString inDir)
{
int num = 0;
QString baseName = RemoveInvalidFilenameChars(string, '-');
QString dirName;
do
{
if(num == 0)
{
dirName = baseName;
}
else
{
dirName = baseName + QString::number(num);;
}
// If it's over 9000
if (num > 9000)
return "";
num++;
} while (QFileInfo(PathCombine(inDir, dirName)).exists());
return dirName;
}
// Does the folder path contain any '!'? If yes, return true, otherwise false.
// (This is a problem for Java)
bool checkProblemticPathJava(QDir folder)
{
QString pathfoldername = folder.absolutePath();
return pathfoldername.contains("!", Qt::CaseInsensitive);
}
// Win32 crap
#if defined Q_OS_WIN
bool called_coinit = false;
HRESULT CreateLink(LPCSTR linkPath, LPCSTR targetPath, LPCSTR args)
{
HRESULT hres;
if (!called_coinit)
{
hres = CoInitialize(NULL);
called_coinit = true;
if (!SUCCEEDED(hres))
{
qWarning("Failed to initialize COM. Error 0x%08lX", hres);
return hres;
}
}
IShellLink *link;
hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink,
(LPVOID *)&link);
if (SUCCEEDED(hres))
{
IPersistFile *persistFile;
link->SetPath(targetPath);
link->SetArguments(args);
hres = link->QueryInterface(IID_IPersistFile, (LPVOID *)&persistFile);
if (SUCCEEDED(hres))
{
WCHAR wstr[MAX_PATH];
MultiByteToWideChar(CP_ACP, 0, linkPath, -1, wstr, MAX_PATH);
hres = persistFile->Save(wstr, TRUE);
persistFile->Release();
}
link->Release();
}
return hres;
}
#endif
QString getDesktopDir()
{
return QStandardPaths::writableLocation(QStandardPaths::DesktopLocation);
}
// Cross-platform Shortcut creation
bool createShortCut(QString location, QString dest, QStringList args, QString name,
QString icon)
{
#if defined Q_OS_LINUX
location = PathCombine(location, name + ".desktop");
QFile f(location);
f.open(QIODevice::WriteOnly | QIODevice::Text);
QTextStream stream(&f);
QString argstring;
if (!args.empty())
argstring = " '" + args.join("' '") + "'";
stream << "[Desktop Entry]"
<< "\n";
stream << "Type=Application"
<< "\n";
stream << "TryExec=" << dest.toLocal8Bit() << "\n";
stream << "Exec=" << dest.toLocal8Bit() << argstring.toLocal8Bit() << "\n";
stream << "Name=" << name.toLocal8Bit() << "\n";
stream << "Icon=" << icon.toLocal8Bit() << "\n";
stream.flush();
f.close();
f.setPermissions(f.permissions() | QFileDevice::ExeOwner | QFileDevice::ExeGroup |
QFileDevice::ExeOther);
return true;
#elif defined Q_OS_WIN
// TODO: Fix
// QFile file(PathCombine(location, name + ".lnk"));
// WCHAR *file_w;
// WCHAR *dest_w;
// WCHAR *args_w;
// file.fileName().toWCharArray(file_w);
// dest.toWCharArray(dest_w);
// QString argStr;
// for (int i = 0; i < args.count(); i++)
// {
// argStr.append(args[i]);
// argStr.append(" ");
// }
// argStr.toWCharArray(args_w);
// return SUCCEEDED(CreateLink(file_w, dest_w, args_w));
return false;
#else
qWarning("Desktop Shortcuts not supported on your platform!");
return false;
#endif
}
}

128
api/logic/FileSystem.h Normal file
View File

@@ -0,0 +1,128 @@
// Licensed under the Apache-2.0 license. See README.md for details.
#pragma once
#include "Exception.h"
#include "pathmatcher/IPathMatcher.h"
#include "multimc_logic_export.h"
#include <QDir>
#include <QFlags>
namespace FS
{
class MULTIMC_LOGIC_EXPORT FileSystemException : public ::Exception
{
public:
FileSystemException(const QString &message) : Exception(message) {}
};
/**
* write data to a file safely
*/
MULTIMC_LOGIC_EXPORT void write(const QString &filename, const QByteArray &data);
/**
* read data from a file safely\
*/
MULTIMC_LOGIC_EXPORT QByteArray read(const QString &filename);
/**
* Update the last changed timestamp of an existing file
*/
MULTIMC_LOGIC_EXPORT bool updateTimestamp(const QString & filename);
/**
* Creates all the folders in a path for the specified path
* last segment of the path is treated as a file name and is ignored!
*/
MULTIMC_LOGIC_EXPORT bool ensureFilePathExists(QString filenamepath);
/**
* Creates all the folders in a path for the specified path
* last segment of the path is treated as a folder name and is created!
*/
MULTIMC_LOGIC_EXPORT bool ensureFolderPathExists(QString filenamepath);
class MULTIMC_LOGIC_EXPORT copy
{
public:
copy(const QString & src, const QString & dst)
{
m_src = src;
m_dst = dst;
}
copy & followSymlinks(const bool follow)
{
m_followSymlinks = follow;
return *this;
}
copy & blacklist(const IPathMatcher * filter)
{
m_blacklist = filter;
return *this;
}
bool operator()()
{
return operator()(QString());
}
private:
bool operator()(const QString &offset);
private:
bool m_followSymlinks = true;
const IPathMatcher * m_blacklist = nullptr;
QDir m_src;
QDir m_dst;
};
/**
* Delete a folder recursively
*/
MULTIMC_LOGIC_EXPORT bool deletePath(QString path);
MULTIMC_LOGIC_EXPORT QString PathCombine(const QString &path1, const QString &path2);
MULTIMC_LOGIC_EXPORT QString PathCombine(const QString &path1, const QString &path2, const QString &path3);
MULTIMC_LOGIC_EXPORT QString PathCombine(const QString &path1, const QString &path2, const QString &path3, const QString &path4);
MULTIMC_LOGIC_EXPORT QString AbsolutePath(QString path);
/**
* Resolve an executable
*
* Will resolve:
* single executable (by name)
* relative path
* absolute path
*
* @return absolute path to executable or null string
*/
MULTIMC_LOGIC_EXPORT QString ResolveExecutable(QString path);
/**
* Normalize path
*
* Any paths inside the current directory will be normalized to relative paths (to current)
* Other paths will be made absolute
*
* Returns false if the path logic somehow filed (and normalizedPath in invalid)
*/
MULTIMC_LOGIC_EXPORT QString NormalizePath(QString path);
MULTIMC_LOGIC_EXPORT QString RemoveInvalidFilenameChars(QString string, QChar replaceWith = '-');
MULTIMC_LOGIC_EXPORT QString DirNameFromString(QString string, QString inDir = ".");
/// Checks if the a given Path contains "!"
MULTIMC_LOGIC_EXPORT bool checkProblemticPathJava(QDir folder);
// Get the Directory representing the User's Desktop
MULTIMC_LOGIC_EXPORT QString getDesktopDir();
// Create a shortcut at *location*, pointing to *dest* called with the arguments *args*
// call it *name* and assign it the icon *icon*
// return true if operation succeeded
MULTIMC_LOGIC_EXPORT bool createShortCut(QString location, QString dest, QStringList args, QString name, QString iconLocation);
}

View File

@@ -0,0 +1,164 @@
#include <QTest>
#include <QTemporaryDir>
#include <QStandardPaths>
#include "TestUtil.h"
#include "FileSystem.h"
class FileSystemTest : public QObject
{
Q_OBJECT
const QString bothSlash = "/foo/";
const QString trailingSlash = "foo/";
const QString leadingSlash = "/foo";
private
slots:
void test_pathCombine()
{
QCOMPARE(QString("/foo/foo"), FS::PathCombine(bothSlash, bothSlash));
QCOMPARE(QString("foo/foo"), FS::PathCombine(trailingSlash, trailingSlash));
QCOMPARE(QString("/foo/foo"), FS::PathCombine(leadingSlash, leadingSlash));
QCOMPARE(QString("/foo/foo/foo"), FS::PathCombine(bothSlash, bothSlash, bothSlash));
QCOMPARE(QString("foo/foo/foo"), FS::PathCombine(trailingSlash, trailingSlash, trailingSlash));
QCOMPARE(QString("/foo/foo/foo"), FS::PathCombine(leadingSlash, leadingSlash, leadingSlash));
}
void test_PathCombine1_data()
{
QTest::addColumn<QString>("result");
QTest::addColumn<QString>("path1");
QTest::addColumn<QString>("path2");
QTest::newRow("qt 1") << "/abc/def/ghi/jkl" << "/abc/def" << "ghi/jkl";
QTest::newRow("qt 2") << "/abc/def/ghi/jkl" << "/abc/def/" << "ghi/jkl";
#if defined(Q_OS_WIN)
QTest::newRow("win native, from C:") << "C:/abc" << "C:" << "abc";
QTest::newRow("win native 1") << "C:/abc/def/ghi/jkl" << "C:\\abc\\def" << "ghi\\jkl";
QTest::newRow("win native 2") << "C:/abc/def/ghi/jkl" << "C:\\abc\\def\\" << "ghi\\jkl";
#endif
}
void test_PathCombine1()
{
QFETCH(QString, result);
QFETCH(QString, path1);
QFETCH(QString, path2);
QCOMPARE(FS::PathCombine(path1, path2), result);
}
void test_PathCombine2_data()
{
QTest::addColumn<QString>("result");
QTest::addColumn<QString>("path1");
QTest::addColumn<QString>("path2");
QTest::addColumn<QString>("path3");
QTest::newRow("qt 1") << "/abc/def/ghi/jkl" << "/abc" << "def" << "ghi/jkl";
QTest::newRow("qt 2") << "/abc/def/ghi/jkl" << "/abc/" << "def" << "ghi/jkl";
QTest::newRow("qt 3") << "/abc/def/ghi/jkl" << "/abc" << "def/" << "ghi/jkl";
QTest::newRow("qt 4") << "/abc/def/ghi/jkl" << "/abc/" << "def/" << "ghi/jkl";
#if defined(Q_OS_WIN)
QTest::newRow("win 1") << "C:/abc/def/ghi/jkl" << "C:\\abc" << "def" << "ghi\\jkl";
QTest::newRow("win 2") << "C:/abc/def/ghi/jkl" << "C:\\abc\\" << "def" << "ghi\\jkl";
QTest::newRow("win 3") << "C:/abc/def/ghi/jkl" << "C:\\abc" << "def\\" << "ghi\\jkl";
QTest::newRow("win 4") << "C:/abc/def/ghi/jkl" << "C:\\abc\\" << "def" << "ghi\\jkl";
#endif
}
void test_PathCombine2()
{
QFETCH(QString, result);
QFETCH(QString, path1);
QFETCH(QString, path2);
QFETCH(QString, path3);
QCOMPARE(FS::PathCombine(path1, path2, path3), result);
}
void test_copy()
{
QString folder = QFINDTESTDATA("data/test_folder");
auto f = [&folder]()
{
QTemporaryDir tempDir;
tempDir.setAutoRemove(true);
qDebug() << "From:" << folder << "To:" << tempDir.path();
QDir target_dir(FS::PathCombine(tempDir.path(), "test_folder"));
qDebug() << tempDir.path();
qDebug() << target_dir.path();
FS::copy c(folder, target_dir.path());
c();
for(auto entry: target_dir.entryList())
{
qDebug() << entry;
}
QVERIFY(target_dir.entryList().contains("pack.mcmeta"));
QVERIFY(target_dir.entryList().contains("assets"));
};
// first try variant without trailing /
QVERIFY(!folder.endsWith('/'));
f();
// then variant with trailing /
folder.append('/');
QVERIFY(folder.endsWith('/'));
f();
}
void test_getDesktop()
{
QCOMPARE(FS::getDesktopDir(), QStandardPaths::writableLocation(QStandardPaths::DesktopLocation));
}
// this is only valid on linux
// FIXME: implement on windows, OSX, then test.
#if defined(Q_OS_LINUX)
void test_createShortcut_data()
{
QTest::addColumn<QString>("location");
QTest::addColumn<QString>("dest");
QTest::addColumn<QStringList>("args");
QTest::addColumn<QString>("name");
QTest::addColumn<QString>("iconLocation");
QTest::addColumn<QByteArray>("result");
QTest::newRow("unix") << QDir::currentPath()
<< "asdfDest"
<< (QStringList() << "arg1" << "arg2")
<< "asdf"
<< QString()
#if defined(Q_OS_LINUX)
<< MULTIMC_GET_TEST_FILE("data/FileSystem-test_createShortcut-unix")
#elif defined(Q_OS_WIN)
<< QByteArray()
#endif
;
}
void test_createShortcut()
{
QFETCH(QString, location);
QFETCH(QString, dest);
QFETCH(QStringList, args);
QFETCH(QString, name);
QFETCH(QString, iconLocation);
QFETCH(QByteArray, result);
QVERIFY(FS::createShortCut(location, dest, args, name, iconLocation));
QCOMPARE(QString::fromLocal8Bit(TestsInternal::readFile(location + QDir::separator() + name + ".desktop")), QString::fromLocal8Bit(result));
//QDir().remove(location);
}
#endif
};
QTEST_GUILESS_MAIN(FileSystemTest)
#include "FileSystem_test.moc"

31
api/logic/Filter.cpp Normal file
View File

@@ -0,0 +1,31 @@
#include "Filter.h"
Filter::~Filter(){}
ContainsFilter::ContainsFilter(const QString& pattern) : pattern(pattern){}
ContainsFilter::~ContainsFilter(){}
bool ContainsFilter::accepts(const QString& value)
{
return value.contains(pattern);
}
ExactFilter::ExactFilter(const QString& pattern) : pattern(pattern){}
ExactFilter::~ExactFilter(){}
bool ExactFilter::accepts(const QString& value)
{
return value == pattern;
}
RegexpFilter::RegexpFilter(const QString& regexp, bool invert)
:invert(invert)
{
pattern.setPattern(regexp);
pattern.optimize();
}
RegexpFilter::~RegexpFilter(){}
bool RegexpFilter::accepts(const QString& value)
{
auto match = pattern.match(value);
bool matched = match.hasMatch();
return invert ? (!matched) : (matched);
}

44
api/logic/Filter.h Normal file
View File

@@ -0,0 +1,44 @@
#pragma once
#include <QString>
#include <QRegularExpression>
#include "multimc_logic_export.h"
class MULTIMC_LOGIC_EXPORT Filter
{
public:
virtual ~Filter();
virtual bool accepts(const QString & value) = 0;
};
class MULTIMC_LOGIC_EXPORT ContainsFilter: public Filter
{
public:
ContainsFilter(const QString &pattern);
virtual ~ContainsFilter();
bool accepts(const QString & value) override;
private:
QString pattern;
};
class MULTIMC_LOGIC_EXPORT ExactFilter: public Filter
{
public:
ExactFilter(const QString &pattern);
virtual ~ExactFilter();
bool accepts(const QString & value) override;
private:
QString pattern;
};
class MULTIMC_LOGIC_EXPORT RegexpFilter: public Filter
{
public:
RegexpFilter(const QString &regexp, bool invert);
virtual ~RegexpFilter();
bool accepts(const QString & value) override;
private:
QRegularExpression pattern;
bool invert = false;
};

115
api/logic/GZip.cpp Normal file
View File

@@ -0,0 +1,115 @@
#include "GZip.h"
#include <zlib.h>
#include <QByteArray>
bool GZip::unzip(const QByteArray &compressedBytes, QByteArray &uncompressedBytes)
{
if (compressedBytes.size() == 0)
{
uncompressedBytes = compressedBytes;
return true;
}
unsigned uncompLength = compressedBytes.size();
uncompressedBytes.clear();
uncompressedBytes.resize(uncompLength);
z_stream strm;
memset(&strm, 0, sizeof(strm));
strm.next_in = (Bytef *)compressedBytes.data();
strm.avail_in = compressedBytes.size();
bool done = false;
if (inflateInit2(&strm, (16 + MAX_WBITS)) != Z_OK)
{
return false;
}
int err = Z_OK;
while (!done)
{
// If our output buffer is too small
if (strm.total_out >= uncompLength)
{
uncompressedBytes.resize(uncompLength * 2);
uncompLength *= 2;
}
strm.next_out = (Bytef *)(uncompressedBytes.data() + strm.total_out);
strm.avail_out = uncompLength - strm.total_out;
// Inflate another chunk.
err = inflate(&strm, Z_SYNC_FLUSH);
if (err == Z_STREAM_END)
done = true;
else if (err != Z_OK)
{
break;
}
}
if (inflateEnd(&strm) != Z_OK || !done)
{
return false;
}
uncompressedBytes.resize(strm.total_out);
return true;
}
bool GZip::zip(const QByteArray &uncompressedBytes, QByteArray &compressedBytes)
{
if (uncompressedBytes.size() == 0)
{
compressedBytes = uncompressedBytes;
return true;
}
unsigned compLength = std::min(uncompressedBytes.size(), 16);
compressedBytes.clear();
compressedBytes.resize(compLength);
z_stream zs;
memset(&zs, 0, sizeof(zs));
if (deflateInit2(&zs, Z_DEFAULT_COMPRESSION, Z_DEFLATED, (16 + MAX_WBITS), 8, Z_DEFAULT_STRATEGY) != Z_OK)
{
return false;
}
zs.next_in = (Bytef*)uncompressedBytes.data();
zs.avail_in = uncompressedBytes.size();
int ret;
compressedBytes.resize(uncompressedBytes.size());
unsigned offset = 0;
unsigned temp = 0;
do
{
auto remaining = compressedBytes.size() - offset;
if(remaining < 1)
{
compressedBytes.resize(compressedBytes.size() * 2);
}
zs.next_out = (Bytef *) (compressedBytes.data() + offset);
temp = zs.avail_out = compressedBytes.size() - offset;
ret = deflate(&zs, Z_FINISH);
offset += temp - zs.avail_out;
} while (ret == Z_OK);
compressedBytes.resize(offset);
if (deflateEnd(&zs) != Z_OK)
{
return false;
}
if (ret != Z_STREAM_END)
{
return false;
}
return true;
}

12
api/logic/GZip.h Normal file
View File

@@ -0,0 +1,12 @@
#pragma once
#include <QByteArray>
#include "multimc_logic_export.h"
class MULTIMC_LOGIC_EXPORT GZip
{
public:
static bool unzip(const QByteArray &compressedBytes, QByteArray &uncompressedBytes);
static bool zip(const QByteArray &uncompressedBytes, QByteArray &compressedBytes);
};

57
api/logic/GZip_test.cpp Normal file
View File

@@ -0,0 +1,57 @@
#include <QTest>
#include "TestUtil.h"
#include "GZip.h"
#include <random>
void fib(int &prev, int &cur)
{
auto ret = prev + cur;
prev = cur;
cur = ret;
}
class GZipTest : public QObject
{
Q_OBJECT
private
slots:
void test_Through()
{
// test up to 10 MB
static const int size = 10 * 1024 * 1024;
QByteArray random;
QByteArray compressed;
QByteArray decompressed;
std::default_random_engine eng((std::random_device())());
std::uniform_int_distribution<uint8_t> idis(0, std::numeric_limits<uint8_t>::max());
// initialize random buffer
for(int i = 0; i < size; i++)
{
random.append((char)idis(eng));
}
// initialize fibonacci
int prev = 1;
int cur = 1;
// test if fibonacci long random buffers pass through GZip
do
{
QByteArray copy = random;
copy.resize(cur);
compressed.clear();
decompressed.clear();
QVERIFY(GZip::zip(copy, compressed));
QVERIFY(GZip::unzip(compressed, decompressed));
QCOMPARE(decompressed, copy);
fib(prev, cur);
} while (cur < size);
}
};
QTEST_GUILESS_MAIN(GZipTest)
#include "GZip_test.moc"

View File

@@ -0,0 +1,56 @@
#include "InstanceCopyTask.h"
#include "settings/INISettingsObject.h"
#include "FileSystem.h"
#include "NullInstance.h"
#include "pathmatcher/RegexpMatcher.h"
#include <QtConcurrentRun>
InstanceCopyTask::InstanceCopyTask(InstancePtr origInstance, bool copySaves)
{
m_origInstance = origInstance;
if(!copySaves)
{
// FIXME: get this from the original instance type...
auto matcherReal = new RegexpMatcher("[.]?minecraft/saves");
matcherReal->caseSensitive(false);
m_matcher.reset(matcherReal);
}
}
void InstanceCopyTask::executeTask()
{
setStatus(tr("Copying instance %1").arg(m_origInstance->name()));
FS::copy folderCopy(m_origInstance->instanceRoot(), m_stagingPath);
folderCopy.followSymlinks(false).blacklist(m_matcher.get());
m_copyFuture = QtConcurrent::run(QThreadPool::globalInstance(), folderCopy);
connect(&m_copyFutureWatcher, &QFutureWatcher<bool>::finished, this, &InstanceCopyTask::copyFinished);
connect(&m_copyFutureWatcher, &QFutureWatcher<bool>::canceled, this, &InstanceCopyTask::copyAborted);
m_copyFutureWatcher.setFuture(m_copyFuture);
}
void InstanceCopyTask::copyFinished()
{
auto successful = m_copyFuture.result();
if(!successful)
{
emitFailed(tr("Instance folder copy failed."));
return;
}
// FIXME: shouldn't this be able to report errors?
auto instanceSettings = std::make_shared<INISettingsObject>(FS::PathCombine(m_stagingPath, "instance.cfg"));
instanceSettings->registerSetting("InstanceType", "Legacy");
InstancePtr inst(new NullInstance(m_globalSettings, instanceSettings, m_stagingPath));
inst->setName(m_instName);
inst->setIconKey(m_instIcon);
emitSucceeded();
}
void InstanceCopyTask::copyAborted()
{
emitFailed(tr("Instance folder copy has been aborted."));
return;
}

View File

@@ -0,0 +1,31 @@
#pragma once
#include "tasks/Task.h"
#include "multimc_logic_export.h"
#include "net/NetJob.h"
#include <QUrl>
#include <QFuture>
#include <QFutureWatcher>
#include "settings/SettingsObject.h"
#include "BaseVersion.h"
#include "BaseInstance.h"
#include "InstanceTask.h"
class MULTIMC_LOGIC_EXPORT InstanceCopyTask : public InstanceTask
{
Q_OBJECT
public:
explicit InstanceCopyTask(InstancePtr origInstance, bool copySaves);
protected:
//! Entry point for tasks.
virtual void executeTask() override;
void copyFinished();
void copyAborted();
private: /* data */
InstancePtr m_origInstance;
QFuture<bool> m_copyFuture;
QFutureWatcher<bool> m_copyFutureWatcher;
std::unique_ptr<IPathMatcher> m_matcher;
};

View File

@@ -0,0 +1,31 @@
#include "InstanceCreationTask.h"
#include "settings/INISettingsObject.h"
#include "FileSystem.h"
//FIXME: remove this
#include "minecraft/MinecraftInstance.h"
#include "minecraft/ComponentList.h"
InstanceCreationTask::InstanceCreationTask(BaseVersionPtr version)
{
m_version = version;
}
void InstanceCreationTask::executeTask()
{
setStatus(tr("Creating instance from version %1").arg(m_version->name()));
{
auto instanceSettings = std::make_shared<INISettingsObject>(FS::PathCombine(m_stagingPath, "instance.cfg"));
instanceSettings->suspendSave();
instanceSettings->registerSetting("InstanceType", "Legacy");
instanceSettings->set("InstanceType", "OneSix");
MinecraftInstance inst(m_globalSettings, instanceSettings, m_stagingPath);
auto components = inst.getComponentList();
components->buildingFromScratch();
components->setComponentVersion("net.minecraft", m_version->descriptor(), true);
inst.setName(m_instName);
inst.setIconKey(m_instIcon);
instanceSettings->resumeSave();
}
emitSucceeded();
}

View File

@@ -0,0 +1,23 @@
#pragma once
#include "tasks/Task.h"
#include "multimc_logic_export.h"
#include "net/NetJob.h"
#include <QUrl>
#include "settings/SettingsObject.h"
#include "BaseVersion.h"
#include "InstanceTask.h"
class MULTIMC_LOGIC_EXPORT InstanceCreationTask : public InstanceTask
{
Q_OBJECT
public:
explicit InstanceCreationTask(BaseVersionPtr version);
protected:
//! Entry point for tasks.
virtual void executeTask() override;
private: /* data */
BaseVersionPtr m_version;
};

View File

@@ -0,0 +1,411 @@
#include "InstanceImportTask.h"
#include "BaseInstance.h"
#include "FileSystem.h"
#include "Env.h"
#include "MMCZip.h"
#include "NullInstance.h"
#include "settings/INISettingsObject.h"
#include "icons/IIconList.h"
#include "icons/IconUtils.h"
#include <QtConcurrentRun>
// FIXME: this does not belong here, it's Minecraft/Flame specific
#include "minecraft/MinecraftInstance.h"
#include "minecraft/ComponentList.h"
#include "modplatform/flame/FileResolvingTask.h"
#include "modplatform/flame/PackManifest.h"
#include "Json.h"
InstanceImportTask::InstanceImportTask(const QUrl sourceUrl)
{
m_sourceUrl = sourceUrl;
}
void InstanceImportTask::executeTask()
{
InstancePtr newInstance;
if (m_sourceUrl.isLocalFile())
{
m_archivePath = m_sourceUrl.toLocalFile();
processZipPack();
}
else
{
setStatus(tr("Downloading modpack:\n%1").arg(m_sourceUrl.toString()));
m_downloadRequired = true;
const QString path = m_sourceUrl.host() + '/' + m_sourceUrl.path();
auto entry = ENV.metacache()->resolveEntry("general", path);
entry->setStale(true);
m_filesNetJob.reset(new NetJob(tr("Modpack download")));
m_filesNetJob->addNetAction(Net::Download::makeCached(m_sourceUrl, entry));
m_archivePath = entry->getFullPath();
auto job = m_filesNetJob.get();
connect(job, &NetJob::succeeded, this, &InstanceImportTask::downloadSucceeded);
connect(job, &NetJob::progress, this, &InstanceImportTask::downloadProgressChanged);
connect(job, &NetJob::failed, this, &InstanceImportTask::downloadFailed);
m_filesNetJob->start();
}
}
void InstanceImportTask::downloadSucceeded()
{
processZipPack();
m_filesNetJob.reset();
}
void InstanceImportTask::downloadFailed(QString reason)
{
emitFailed(reason);
m_filesNetJob.reset();
}
void InstanceImportTask::downloadProgressChanged(qint64 current, qint64 total)
{
setProgress(current / 2, total);
}
void InstanceImportTask::processZipPack()
{
setStatus(tr("Extracting modpack"));
QDir extractDir(m_stagingPath);
qDebug() << "Attempting to create instance from" << m_archivePath;
// open the zip and find relevant files in it
m_packZip.reset(new QuaZip(m_archivePath));
if (!m_packZip->open(QuaZip::mdUnzip))
{
emitFailed(tr("Unable to open supplied modpack zip file."));
return;
}
QStringList blacklist = {"instance.cfg", "manifest.json"};
QString mmcFound = MMCZip::findFolderOfFileInZip(m_packZip.get(), "instance.cfg");
QString flameFound = MMCZip::findFolderOfFileInZip(m_packZip.get(), "manifest.json");
QString root;
if(!mmcFound.isNull())
{
// process as MultiMC instance/pack
qDebug() << "MultiMC:" << mmcFound;
root = mmcFound;
m_modpackType = ModpackType::MultiMC;
}
else if(!flameFound.isNull())
{
// process as Flame pack
qDebug() << "Flame:" << flameFound;
root = flameFound;
m_modpackType = ModpackType::Flame;
}
if(m_modpackType == ModpackType::Unknown)
{
emitFailed(tr("Archive does not contain a recognized modpack type."));
return;
}
// make sure we extract just the pack
m_extractFuture = QtConcurrent::run(QThreadPool::globalInstance(), MMCZip::extractSubDir, m_packZip.get(), root, extractDir.absolutePath());
connect(&m_extractFutureWatcher, &QFutureWatcher<QStringList>::finished, this, &InstanceImportTask::extractFinished);
connect(&m_extractFutureWatcher, &QFutureWatcher<QStringList>::canceled, this, &InstanceImportTask::extractAborted);
m_extractFutureWatcher.setFuture(m_extractFuture);
}
void InstanceImportTask::extractFinished()
{
m_packZip.reset();
if (m_extractFuture.result().isEmpty())
{
emitFailed(tr("Failed to extract modpack"));
return;
}
QDir extractDir(m_stagingPath);
qDebug() << "Fixing permissions for extracted pack files...";
QDirIterator it(extractDir, QDirIterator::Subdirectories);
while (it.hasNext())
{
auto filepath = it.next();
QFileInfo file(filepath);
auto permissions = QFile::permissions(filepath);
auto origPermissions = permissions;
if(file.isDir())
{
// Folder +rwx for current user
permissions |= QFileDevice::Permission::ReadUser | QFileDevice::Permission::WriteUser | QFileDevice::Permission::ExeUser;
}
else
{
// File +rw for current user
permissions |= QFileDevice::Permission::ReadUser | QFileDevice::Permission::WriteUser;
}
if(origPermissions != permissions)
{
if(!QFile::setPermissions(filepath, permissions))
{
logWarning(tr("Could not fix permissions for %1").arg(filepath));
}
else
{
qDebug() << "Fixed" << filepath;
}
}
}
switch(m_modpackType)
{
case ModpackType::Flame:
processFlame();
return;
case ModpackType::MultiMC:
processMultiMC();
return;
case ModpackType::Unknown:
emitFailed(tr("Archive does not contain a recognized modpack type."));
return;
}
}
void InstanceImportTask::extractAborted()
{
emitFailed(tr("Instance import has been aborted."));
return;
}
void InstanceImportTask::processFlame()
{
const static QMap<QString,QString> forgemap = {
{"1.2.5", "3.4.9.171"},
{"1.4.2", "6.0.1.355"},
{"1.4.7", "6.6.2.534"},
{"1.5.2", "7.8.1.737"}
};
Flame::Manifest pack;
try
{
QString configPath = FS::PathCombine(m_stagingPath, "manifest.json");
Flame::loadManifest(pack, configPath);
QFile::remove(configPath);
}
catch (const JSONValidationError &e)
{
emitFailed(tr("Could not understand pack manifest:\n") + e.cause());
return;
}
if(!pack.overrides.isEmpty())
{
QString overridePath = FS::PathCombine(m_stagingPath, pack.overrides);
if (QFile::exists(overridePath))
{
QString mcPath = FS::PathCombine(m_stagingPath, "minecraft");
if (!QFile::rename(overridePath, mcPath))
{
emitFailed(tr("Could not rename the overrides folder:\n") + pack.overrides);
return;
}
}
else
{
logWarning(tr("The specified overrides folder (%1) is missing. Maybe the modpack was already used before?").arg(pack.overrides));
}
}
QString forgeVersion;
for(auto &loader: pack.minecraft.modLoaders)
{
auto id = loader.id;
if(id.startsWith("forge-"))
{
id.remove("forge-");
forgeVersion = id;
continue;
}
logWarning(tr("Unknown mod loader in manifest: %1").arg(id));
}
QString configPath = FS::PathCombine(m_stagingPath, "instance.cfg");
auto instanceSettings = std::make_shared<INISettingsObject>(configPath);
instanceSettings->registerSetting("InstanceType", "Legacy");
instanceSettings->set("InstanceType", "OneSix");
MinecraftInstance instance(m_globalSettings, instanceSettings, m_stagingPath);
auto mcVersion = pack.minecraft.version;
// Hack to correct some 'special sauce'...
if(mcVersion.endsWith('.'))
{
mcVersion.remove(QRegExp("[.]+$"));
logWarning(tr("Mysterious trailing dots removed from Minecraft version while importing pack."));
}
auto components = instance.getComponentList();
components->buildingFromScratch();
components->setComponentVersion("net.minecraft", mcVersion, true);
if(!forgeVersion.isEmpty())
{
// FIXME: dirty, nasty, hack. Proper solution requires dependency resolution and knowledge of the metadata.
if(forgeVersion == "recommended")
{
if(forgemap.contains(mcVersion))
{
forgeVersion = forgemap[mcVersion];
}
else
{
logWarning(tr("Could not map recommended forge version for Minecraft %1").arg(mcVersion));
}
}
components->setComponentVersion("net.minecraftforge", forgeVersion);
}
if (m_instIcon != "default")
{
instance.setIconKey(m_instIcon);
}
else
{
if(pack.name.contains("Direwolf20"))
{
instance.setIconKey("steve");
}
else if(pack.name.contains("FTB") || pack.name.contains("Feed The Beast"))
{
instance.setIconKey("ftb_logo");
}
else
{
// default to something other than the MultiMC default to distinguish these
instance.setIconKey("flame");
}
}
QString jarmodsPath = FS::PathCombine(m_stagingPath, "minecraft", "jarmods");
QFileInfo jarmodsInfo(jarmodsPath);
if(jarmodsInfo.isDir())
{
// install all the jar mods
qDebug() << "Found jarmods:";
QDir jarmodsDir(jarmodsPath);
QStringList jarMods;
for (auto info: jarmodsDir.entryInfoList(QDir::NoDotAndDotDot | QDir::Files))
{
qDebug() << info.fileName();
jarMods.push_back(info.absoluteFilePath());
}
auto profile = instance.getComponentList();
profile->installJarMods(jarMods);
// nuke the original files
FS::deletePath(jarmodsPath);
}
instance.setName(m_instName);
m_modIdResolver.reset(new Flame::FileResolvingTask(pack));
connect(m_modIdResolver.get(), &Flame::FileResolvingTask::succeeded, [&]()
{
auto results = m_modIdResolver->getResults();
m_filesNetJob.reset(new NetJob(tr("Mod download")));
for(auto result: results.files)
{
QString filename = result.fileName;
if(!result.required)
{
filename += ".disabled";
}
auto relpath = FS::PathCombine("minecraft", result.targetFolder, filename);
auto path = FS::PathCombine(m_stagingPath , relpath);
switch(result.type)
{
case Flame::File::Type::Folder:
{
logWarning(tr("This 'Folder' may need extracting: %1").arg(relpath));
// fall-through intentional, we treat these as plain old mods and dump them wherever.
}
case Flame::File::Type::SingleFile:
case Flame::File::Type::Mod:
{
qDebug() << "Will download" << result.url << "to" << path;
auto dl = Net::Download::makeFile(result.url, path);
m_filesNetJob->addNetAction(dl);
break;
}
case Flame::File::Type::Modpack:
logWarning(tr("Nesting modpacks in modpacks is not implemented, nothing was downloaded: %1").arg(relpath));
break;
case Flame::File::Type::Cmod2:
case Flame::File::Type::Ctoc:
case Flame::File::Type::Unknown:
logWarning(tr("Unrecognized/unhandled PackageType for: %1").arg(relpath));
break;
}
}
m_modIdResolver.reset();
connect(m_filesNetJob.get(), &NetJob::succeeded, this, [&]()
{
m_filesNetJob.reset();
emitSucceeded();
}
);
connect(m_filesNetJob.get(), &NetJob::failed, [&](QString reason)
{
m_filesNetJob.reset();
emitFailed(reason);
});
connect(m_filesNetJob.get(), &NetJob::progress, [&](qint64 current, qint64 total)
{
setProgress(current, total);
});
setStatus(tr("Downloading mods..."));
m_filesNetJob->start();
}
);
connect(m_modIdResolver.get(), &Flame::FileResolvingTask::failed, [&](QString reason)
{
m_modIdResolver.reset();
emitFailed(tr("Unable to resolve mod IDs:\n") + reason);
});
connect(m_modIdResolver.get(), &Flame::FileResolvingTask::progress, [&](qint64 current, qint64 total)
{
setProgress(current, total);
});
connect(m_modIdResolver.get(), &Flame::FileResolvingTask::status, [&](QString status)
{
setStatus(status);
});
m_modIdResolver->start();
}
void InstanceImportTask::processMultiMC()
{
// FIXME: copy from FolderInstanceProvider!!! FIX IT!!!
QString configPath = FS::PathCombine(m_stagingPath, "instance.cfg");
auto instanceSettings = std::make_shared<INISettingsObject>(configPath);
instanceSettings->registerSetting("InstanceType", "Legacy");
NullInstance instance(m_globalSettings, instanceSettings, m_stagingPath);
// reset time played on import... because packs.
instance.resetTimePlayed();
// set a new nice name
instance.setName(m_instName);
// if the icon was specified by user, use that. otherwise pull icon from the pack
if (m_instIcon != "default")
{
instance.setIconKey(m_instIcon);
}
else
{
m_instIcon = instance.iconKey();
auto importIconPath = IconUtils::findBestIconIn(instance.instanceRoot(), m_instIcon);
if (!importIconPath.isNull() && QFile::exists(importIconPath))
{
// import icon
auto iconList = ENV.icons();
if (iconList->iconFileExists(m_instIcon))
{
iconList->deleteIcon(m_instIcon);
}
iconList->installIcons({importIconPath});
}
}
emitSucceeded();
}

View File

@@ -0,0 +1,54 @@
#pragma once
#include "InstanceTask.h"
#include "multimc_logic_export.h"
#include "net/NetJob.h"
#include <QUrl>
#include <QFuture>
#include <QFutureWatcher>
#include "settings/SettingsObject.h"
#include "QObjectPtr.h"
class QuaZip;
namespace Flame
{
class FileResolvingTask;
}
class MULTIMC_LOGIC_EXPORT InstanceImportTask : public InstanceTask
{
Q_OBJECT
public:
explicit InstanceImportTask(const QUrl sourceUrl);
protected:
//! Entry point for tasks.
virtual void executeTask() override;
private:
void processZipPack();
void processMultiMC();
void processFlame();
private slots:
void downloadSucceeded();
void downloadFailed(QString reason);
void downloadProgressChanged(qint64 current, qint64 total);
void extractFinished();
void extractAborted();
private: /* data */
NetJobPtr m_filesNetJob;
shared_qobject_ptr<Flame::FileResolvingTask> m_modIdResolver;
QUrl m_sourceUrl;
QString m_archivePath;
bool m_downloadRequired = false;
std::unique_ptr<QuaZip> m_packZip;
QFuture<QStringList> m_extractFuture;
QFutureWatcher<QStringList> m_extractFutureWatcher;
enum class ModpackType{
Unknown,
MultiMC,
Flame
} m_modpackType = ModpackType::Unknown;
};

832
api/logic/InstanceList.cpp Normal file
View File

@@ -0,0 +1,832 @@
/* Copyright 2013-2019 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <QDir>
#include <QDirIterator>
#include <QSet>
#include <QFile>
#include <QThread>
#include <QTextStream>
#include <QXmlStreamReader>
#include <QTimer>
#include <QDebug>
#include <QFileSystemWatcher>
#include <QUuid>
#include <QJsonArray>
#include <QJsonDocument>
#include "InstanceList.h"
#include "BaseInstance.h"
#include "InstanceTask.h"
#include "settings/INISettingsObject.h"
#include "minecraft/legacy/LegacyInstance.h"
#include "NullInstance.h"
#include "minecraft/MinecraftInstance.h"
#include "FileSystem.h"
#include "ExponentialSeries.h"
#include "WatchLock.h"
const static int GROUP_FILE_FORMAT_VERSION = 1;
InstanceList::InstanceList(SettingsObjectPtr settings, const QString & instDir, QObject *parent)
: QAbstractListModel(parent), m_globalSettings(settings)
{
resumeWatch();
// Create aand normalize path
if (!QDir::current().exists(instDir))
{
QDir::current().mkpath(instDir);
}
connect(this, &InstanceList::instancesChanged, this, &InstanceList::providerUpdated);
// NOTE: canonicalPath requires the path to exist. Do not move this above the creation block!
m_instDir = QDir(instDir).canonicalPath();
m_watcher = new QFileSystemWatcher(this);
connect(m_watcher, &QFileSystemWatcher::directoryChanged, this, &InstanceList::instanceDirContentsChanged);
m_watcher->addPath(m_instDir);
}
InstanceList::~InstanceList()
{
}
int InstanceList::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return m_instances.count();
}
QModelIndex InstanceList::index(int row, int column, const QModelIndex &parent) const
{
Q_UNUSED(parent);
if (row < 0 || row >= m_instances.size())
return QModelIndex();
return createIndex(row, column, (void *)m_instances.at(row).get());
}
QVariant InstanceList::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
{
return QVariant();
}
BaseInstance *pdata = static_cast<BaseInstance *>(index.internalPointer());
switch (role)
{
case InstancePointerRole:
{
QVariant v = qVariantFromValue((void *)pdata);
return v;
}
case InstanceIDRole:
{
return pdata->id();
}
case Qt::EditRole:
case Qt::DisplayRole:
{
return pdata->name();
}
case Qt::ToolTipRole:
{
return pdata->instanceRoot();
}
case Qt::DecorationRole:
{
return pdata->iconKey();
}
// HACK: see GroupView.h in gui!
case GroupRole:
{
return getInstanceGroup(pdata->id());
}
default:
break;
}
return QVariant();
}
bool InstanceList::setData(const QModelIndex& index, const QVariant& value, int role)
{
if (!index.isValid())
{
return false;
}
if(role != Qt::EditRole)
{
return false;
}
BaseInstance *pdata = static_cast<BaseInstance *>(index.internalPointer());
auto newName = value.toString();
if(pdata->name() == newName)
{
return true;
}
pdata->setName(newName);
return true;
}
Qt::ItemFlags InstanceList::flags(const QModelIndex &index) const
{
Qt::ItemFlags f;
if (index.isValid())
{
f |= (Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable);
}
return f;
}
GroupId InstanceList::getInstanceGroup(const InstanceId& id) const
{
auto inst = getInstanceById(id);
if(!inst)
{
return GroupId();
}
auto iter = m_groupMap.find(inst->id());
if(iter != m_groupMap.end())
{
return *iter;
}
return GroupId();
}
void InstanceList::setInstanceGroup(const InstanceId& id, const GroupId& name)
{
auto inst = getInstanceById(id);
if(!inst)
{
qDebug() << "Attempt to set a null instance's group";
return;
}
bool changed = false;
auto iter = m_groupMap.find(inst->id());
if(iter != m_groupMap.end())
{
if(*iter != name)
{
*iter = name;
changed = true;
}
}
else
{
changed = true;
m_groupMap[id] = name;
}
if(changed)
{
m_groups.insert(name);
auto idx = getInstIndex(inst.get());
emit dataChanged(index(idx), index(idx), {GroupRole});
saveGroupList();
}
}
QStringList InstanceList::getGroups()
{
return m_groups.toList();
}
void InstanceList::deleteGroup(const QString& name)
{
bool removed = false;
qDebug() << "Delete group" << name;
for(auto & instance: m_instances)
{
const auto & instID = instance->id();
auto instGroupName = getInstanceGroup(instID);
if(instGroupName == name)
{
m_groupMap.remove(instID);
qDebug() << "Remove" << instID << "from group" << name;
removed = true;
auto idx = getInstIndex(instance.get());
if(idx > 0)
{
emit dataChanged(index(idx), index(idx), {GroupRole});
}
}
}
if(removed)
{
saveGroupList();
}
}
void InstanceList::deleteInstance(const InstanceId& id)
{
auto inst = getInstanceById(id);
if(!inst)
{
qDebug() << "Cannot delete instance" << id << " No such instance is present.";
return;
}
if(m_groupMap.remove(id))
{
saveGroupList();
}
qDebug() << "Will delete instance" << id;
if(!FS::deletePath(inst->instanceRoot()))
{
qWarning() << "Deletion of instance" << id << "has not been completely successful ...";
return;
}
qDebug() << "Instance" << id << "has been deleted by MultiMC.";
}
static QMap<InstanceId, InstanceLocator> getIdMapping(const QList<InstancePtr> &list)
{
QMap<InstanceId, InstanceLocator> out;
int i = 0;
for(auto & item: list)
{
auto id = item->id();
if(out.contains(id))
{
qWarning() << "Duplicate ID" << id << "in instance list";
}
out[id] = std::make_pair(item, i);
i++;
}
return out;
}
QList< InstanceId > InstanceList::discoverInstances()
{
qDebug() << "Discovering instances in" << m_instDir;
QList<InstanceId> out;
QDirIterator iter(m_instDir, QDir::Dirs | QDir::NoDot | QDir::NoDotDot | QDir::Readable | QDir::Hidden, QDirIterator::FollowSymlinks);
while (iter.hasNext())
{
QString subDir = iter.next();
QFileInfo dirInfo(subDir);
if (!QFileInfo(FS::PathCombine(subDir, "instance.cfg")).exists())
continue;
// if it is a symlink, ignore it if it goes to the instance folder
if(dirInfo.isSymLink())
{
QFileInfo targetInfo(dirInfo.symLinkTarget());
QFileInfo instDirInfo(m_instDir);
if(targetInfo.canonicalPath() == instDirInfo.canonicalFilePath())
{
qDebug() << "Ignoring symlink" << subDir << "that leads into the instances folder";
continue;
}
}
auto id = dirInfo.fileName();
out.append(id);
qDebug() << "Found instance ID" << id;
}
instanceSet = out.toSet();
m_instancesProbed = true;
return out;
}
InstanceList::InstListError InstanceList::loadList()
{
auto existingIds = getIdMapping(m_instances);
QList<InstancePtr> newList;
for(auto & id: discoverInstances())
{
if(existingIds.contains(id))
{
auto instPair = existingIds[id];
existingIds.remove(id);
qDebug() << "Should keep and soft-reload" << id;
}
else
{
InstancePtr instPtr = loadInstance(id);
if(instPtr)
{
newList.append(instPtr);
}
}
}
// TODO: looks like a general algorithm with a few specifics inserted. Do something about it.
if(!existingIds.isEmpty())
{
// get the list of removed instances and sort it by their original index, from last to first
auto deadList = existingIds.values();
auto orderSortPredicate = [](const InstanceLocator & a, const InstanceLocator & b) -> bool
{
return a.second > b.second;
};
std::sort(deadList.begin(), deadList.end(), orderSortPredicate);
// remove the contiguous ranges of rows
int front_bookmark = -1;
int back_bookmark = -1;
int currentItem = -1;
auto removeNow = [&]()
{
beginRemoveRows(QModelIndex(), front_bookmark, back_bookmark);
m_instances.erase(m_instances.begin() + front_bookmark, m_instances.begin() + back_bookmark + 1);
endRemoveRows();
front_bookmark = -1;
back_bookmark = currentItem;
};
for(auto & removedItem: deadList)
{
auto instPtr = removedItem.first;
instPtr->invalidate();
currentItem = removedItem.second;
if(back_bookmark == -1)
{
// no bookmark yet
back_bookmark = currentItem;
}
else if(currentItem == front_bookmark - 1)
{
// part of contiguous sequence, continue
}
else
{
// seam between previous and current item
removeNow();
}
front_bookmark = currentItem;
}
if(back_bookmark != -1)
{
removeNow();
}
}
if(newList.size())
{
add(newList);
}
m_dirty = false;
return NoError;
}
void InstanceList::saveNow()
{
for(auto & item: m_instances)
{
item->saveNow();
}
}
void InstanceList::add(const QList<InstancePtr> &t)
{
beginInsertRows(QModelIndex(), m_instances.count(), m_instances.count() + t.size() - 1);
m_instances.append(t);
for(auto & ptr : t)
{
connect(ptr.get(), &BaseInstance::propertiesChanged, this, &InstanceList::propertiesChanged);
}
endInsertRows();
}
void InstanceList::resumeWatch()
{
if(m_watchLevel > 0)
{
qWarning() << "Bad suspend level resume in instance list";
return;
}
m_watchLevel++;
if(m_watchLevel > 0 && m_dirty)
{
loadList();
}
}
void InstanceList::suspendWatch()
{
m_watchLevel --;
}
void InstanceList::providerUpdated()
{
m_dirty = true;
if(m_watchLevel == 1)
{
loadList();
}
}
InstancePtr InstanceList::getInstanceById(QString instId) const
{
if(instId.isEmpty())
return InstancePtr();
for(auto & inst: m_instances)
{
if (inst->id() == instId)
{
return inst;
}
}
return InstancePtr();
}
QModelIndex InstanceList::getInstanceIndexById(const QString &id) const
{
return index(getInstIndex(getInstanceById(id).get()));
}
int InstanceList::getInstIndex(BaseInstance *inst) const
{
int count = m_instances.count();
for (int i = 0; i < count; i++)
{
if (inst == m_instances[i].get())
{
return i;
}
}
return -1;
}
void InstanceList::propertiesChanged(BaseInstance *inst)
{
int i = getInstIndex(inst);
if (i != -1)
{
emit dataChanged(index(i), index(i));
}
}
InstancePtr InstanceList::loadInstance(const InstanceId& id)
{
if(!m_groupsLoaded)
{
loadGroupList();
}
auto instanceRoot = FS::PathCombine(m_instDir, id);
auto instanceSettings = std::make_shared<INISettingsObject>(FS::PathCombine(instanceRoot, "instance.cfg"));
InstancePtr inst;
instanceSettings->registerSetting("InstanceType", "Legacy");
QString inst_type = instanceSettings->get("InstanceType").toString();
if (inst_type == "OneSix" || inst_type == "Nostalgia")
{
inst.reset(new MinecraftInstance(m_globalSettings, instanceSettings, instanceRoot));
}
else if (inst_type == "Legacy")
{
inst.reset(new LegacyInstance(m_globalSettings, instanceSettings, instanceRoot));
}
else
{
inst.reset(new NullInstance(m_globalSettings, instanceSettings, instanceRoot));
}
qDebug() << "Loaded instance " << inst->name() << " from " << inst->instanceRoot();
return inst;
}
void InstanceList::saveGroupList()
{
qDebug() << "Will save group list now.";
if(!m_instancesProbed)
{
qDebug() << "Group saving prevented because we don't know the full list of instances yet.";
return;
}
WatchLock foo(m_watcher, m_instDir);
QString groupFileName = m_instDir + "/instgroups.json";
QMap<QString, QSet<QString>> reverseGroupMap;
for (auto iter = m_groupMap.begin(); iter != m_groupMap.end(); iter++)
{
QString id = iter.key();
QString group = iter.value();
if (group.isEmpty())
continue;
if(!instanceSet.contains(id))
{
qDebug() << "Skipping saving missing instance" << id << "to groups list.";
continue;
}
if (!reverseGroupMap.count(group))
{
QSet<QString> set;
set.insert(id);
reverseGroupMap[group] = set;
}
else
{
QSet<QString> &set = reverseGroupMap[group];
set.insert(id);
}
}
QJsonObject toplevel;
toplevel.insert("formatVersion", QJsonValue(QString("1")));
QJsonObject groupsArr;
for (auto iter = reverseGroupMap.begin(); iter != reverseGroupMap.end(); iter++)
{
auto list = iter.value();
auto name = iter.key();
QJsonObject groupObj;
QJsonArray instanceArr;
groupObj.insert("hidden", QJsonValue(QString("false")));
for (auto item : list)
{
instanceArr.append(QJsonValue(item));
}
groupObj.insert("instances", instanceArr);
groupsArr.insert(name, groupObj);
}
toplevel.insert("groups", groupsArr);
QJsonDocument doc(toplevel);
try
{
FS::write(groupFileName, doc.toJson());
qDebug() << "Group list saved.";
}
catch (const FS::FileSystemException &e)
{
qCritical() << "Failed to write instance group file :" << e.cause();
}
}
void InstanceList::loadGroupList()
{
qDebug() << "Will load group list now.";
QSet<QString> groupSet;
QString groupFileName = m_instDir + "/instgroups.json";
// if there's no group file, fail
if (!QFileInfo(groupFileName).exists())
return;
QByteArray jsonData;
try
{
jsonData = FS::read(groupFileName);
}
catch (const FS::FileSystemException &e)
{
qCritical() << "Failed to read instance group file :" << e.cause();
return;
}
QJsonParseError error;
QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonData, &error);
// if the json was bad, fail
if (error.error != QJsonParseError::NoError)
{
qCritical() << QString("Failed to parse instance group file: %1 at offset %2")
.arg(error.errorString(), QString::number(error.offset))
.toUtf8();
return;
}
// if the root of the json wasn't an object, fail
if (!jsonDoc.isObject())
{
qWarning() << "Invalid group file. Root entry should be an object.";
return;
}
QJsonObject rootObj = jsonDoc.object();
// Make sure the format version matches, otherwise fail.
if (rootObj.value("formatVersion").toVariant().toInt() != GROUP_FILE_FORMAT_VERSION)
return;
// Get the groups. if it's not an object, fail
if (!rootObj.value("groups").isObject())
{
qWarning() << "Invalid group list JSON: 'groups' should be an object.";
return;
}
m_groupMap.clear();
// Iterate through all the groups.
QJsonObject groupMapping = rootObj.value("groups").toObject();
for (QJsonObject::iterator iter = groupMapping.begin(); iter != groupMapping.end(); iter++)
{
QString groupName = iter.key();
// If not an object, complain and skip to the next one.
if (!iter.value().isObject())
{
qWarning() << QString("Group '%1' in the group list should "
"be an object.")
.arg(groupName)
.toUtf8();
continue;
}
QJsonObject groupObj = iter.value().toObject();
if (!groupObj.value("instances").isArray())
{
qWarning() << QString("Group '%1' in the group list is invalid. "
"It should contain an array "
"called 'instances'.")
.arg(groupName)
.toUtf8();
continue;
}
// keep a list/set of groups for choosing
groupSet.insert(groupName);
// Iterate through the list of instances in the group.
QJsonArray instancesArray = groupObj.value("instances").toArray();
for (QJsonArray::iterator iter2 = instancesArray.begin(); iter2 != instancesArray.end(); iter2++)
{
m_groupMap[(*iter2).toString()] = groupName;
}
}
m_groupsLoaded = true;
m_groups.unite(groupSet);
qDebug() << "Group list loaded.";
}
void InstanceList::instanceDirContentsChanged(const QString& path)
{
Q_UNUSED(path);
emit instancesChanged();
}
void InstanceList::on_InstFolderChanged(const Setting &setting, QVariant value)
{
QString newInstDir = QDir(value.toString()).canonicalPath();
if(newInstDir != m_instDir)
{
if(m_groupsLoaded)
{
saveGroupList();
}
m_instDir = newInstDir;
m_groupsLoaded = false;
emit instancesChanged();
}
}
class InstanceStaging : public Task
{
Q_OBJECT
const unsigned minBackoff = 1;
const unsigned maxBackoff = 16;
public:
InstanceStaging (
InstanceList * parent,
Task * child,
const QString & stagingPath,
const QString& instanceName,
const QString& groupName )
: backoff(minBackoff, maxBackoff)
{
m_parent = parent;
m_child.reset(child);
connect(child, &Task::succeeded, this, &InstanceStaging::childSucceded);
connect(child, &Task::failed, this, &InstanceStaging::childFailed);
connect(child, &Task::status, this, &InstanceStaging::setStatus);
connect(child, &Task::progress, this, &InstanceStaging::setProgress);
m_instanceName = instanceName;
m_groupName = groupName;
m_stagingPath = stagingPath;
m_backoffTimer.setSingleShot(true);
connect(&m_backoffTimer, &QTimer::timeout, this, &InstanceStaging::childSucceded);
}
virtual ~InstanceStaging() {};
// FIXME/TODO: add ability to abort during instance commit retries
bool abort() override
{
if(m_child && m_child->canAbort())
{
return m_child->abort();
}
return false;
}
bool canAbort() const override
{
if(m_child && m_child->canAbort())
{
return true;
}
return false;
}
protected:
virtual void executeTask() override
{
m_child->start();
}
QStringList warnings() const override
{
return m_child->warnings();
}
private slots:
void childSucceded()
{
unsigned sleepTime = backoff();
if(m_parent->commitStagedInstance(m_stagingPath, m_instanceName, m_groupName))
{
emitSucceeded();
return;
}
// we actually failed, retry?
if(sleepTime == maxBackoff)
{
emitFailed(tr("Failed to commit instance, even after multiple retries. It is being blocked by something."));
return;
}
qDebug() << "Failed to commit instance" << m_instanceName << "Initiating backoff:" << sleepTime;
m_backoffTimer.start(sleepTime * 500);
}
void childFailed(const QString & reason)
{
m_parent->destroyStagingPath(m_stagingPath);
emitFailed(reason);
}
private:
/*
* WHY: the whole reason why this uses an exponential backoff retry scheme is antivirus on Windows.
* Basically, it starts messing things up while MultiMC is extracting/creating instances
* and causes that horrible failure that is NTFS to lock files in place because they are open.
*/
ExponentialSeries backoff;
QString m_stagingPath;
InstanceList * m_parent;
unique_qobject_ptr<Task> m_child;
QString m_instanceName;
QString m_groupName;
QTimer m_backoffTimer;
};
Task * InstanceList::wrapInstanceTask(InstanceTask * task)
{
auto stagingPath = getStagedInstancePath();
task->setStagingPath(stagingPath);
task->setParentSettings(m_globalSettings);
return new InstanceStaging(this, task, stagingPath, task->name(), task->group());
}
QString InstanceList::getStagedInstancePath()
{
QString key = QUuid::createUuid().toString();
QString relPath = FS::PathCombine("_MMC_TEMP/" , key);
QDir rootPath(m_instDir);
auto path = FS::PathCombine(m_instDir, relPath);
if(!rootPath.mkpath(relPath))
{
return QString();
}
return path;
}
bool InstanceList::commitStagedInstance(const QString& path, const QString& instanceName, const QString& groupName)
{
QDir dir;
QString instID = FS::DirNameFromString(instanceName, m_instDir);
{
WatchLock lock(m_watcher, m_instDir);
QString destination = FS::PathCombine(m_instDir, instID);
if(!dir.rename(path, destination))
{
qWarning() << "Failed to move" << path << "to" << destination;
return false;
}
m_groupMap[instID] = groupName;
instanceSet.insert(instID);
m_groups.insert(groupName);
emit instancesChanged();
}
saveGroupList();
return true;
}
bool InstanceList::destroyStagingPath(const QString& keyPath)
{
return FS::deletePath(keyPath);
}
#include "InstanceList.moc"

165
api/logic/InstanceList.h Normal file
View File

@@ -0,0 +1,165 @@
/* Copyright 2013-2019 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <QObject>
#include <QAbstractListModel>
#include <QSet>
#include <QList>
#include "BaseInstance.h"
#include "multimc_logic_export.h"
#include "QObjectPtr.h"
class QFileSystemWatcher;
class InstanceTask;
using InstanceId = QString;
using GroupId = QString;
using InstanceLocator = std::pair<InstancePtr, int>;
enum class InstCreateError
{
NoCreateError = 0,
NoSuchVersion,
UnknownCreateError,
InstExists,
CantCreateDir
};
enum class GroupsState
{
NotLoaded,
Steady,
Dirty
};
class MULTIMC_LOGIC_EXPORT InstanceList : public QAbstractListModel
{
Q_OBJECT
public:
explicit InstanceList(SettingsObjectPtr settings, const QString & instDir, QObject *parent = 0);
virtual ~InstanceList();
public:
QModelIndex index(int row, int column = 0, const QModelIndex &parent = QModelIndex()) const override;
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role) const override;
Qt::ItemFlags flags(const QModelIndex &index) const override;
bool setData(const QModelIndex & index, const QVariant & value, int role) override;
enum AdditionalRoles
{
GroupRole = Qt::UserRole,
InstancePointerRole = 0x34B1CB48, ///< Return pointer to real instance
InstanceIDRole = 0x34B1CB49 ///< Return id if the instance
};
/*!
* \brief Error codes returned by functions in the InstanceList class.
* NoError Indicates that no error occurred.
* UnknownError indicates that an unspecified error occurred.
*/
enum InstListError
{
NoError = 0,
UnknownError
};
InstancePtr at(int i) const
{
return m_instances.at(i);
}
int count() const
{
return m_instances.count();
}
InstListError loadList();
void saveNow();
InstancePtr getInstanceById(QString id) const;
QModelIndex getInstanceIndexById(const QString &id) const;
QStringList getGroups();
GroupId getInstanceGroup(const InstanceId & id) const;
void setInstanceGroup(const InstanceId & id, const GroupId& name);
void deleteGroup(const GroupId & name);
void deleteInstance(const InstanceId & id);
// Wrap an instance creation task in some more task machinery and make it ready to be used
Task * wrapInstanceTask(InstanceTask * task);
/**
* Create a new empty staging area for instance creation and @return a path/key top commit it later.
* Used by instance manipulation tasks.
*/
QString getStagedInstancePath();
/**
* Commit the staging area given by @keyPath to the provider - used when creation succeeds.
* Used by instance manipulation tasks.
*/
bool commitStagedInstance(const QString & keyPath, const QString& instanceName, const QString & groupName);
/**
* Destroy a previously created staging area given by @keyPath - used when creation fails.
* Used by instance manipulation tasks.
*/
bool destroyStagingPath(const QString & keyPath);
signals:
void dataIsInvalid();
void instancesChanged();
void groupsChanged(QSet<QString> groups);
public slots:
void on_InstFolderChanged(const Setting &setting, QVariant value);
private slots:
void propertiesChanged(BaseInstance *inst);
void providerUpdated();
void instanceDirContentsChanged(const QString &path);
private:
int getInstIndex(BaseInstance *inst) const;
void suspendWatch();
void resumeWatch();
void add(const QList<InstancePtr> &list);
void loadGroupList();
void saveGroupList();
QList<InstanceId> discoverInstances();
InstancePtr loadInstance(const InstanceId& id);
private:
int m_watchLevel = 0;
bool m_dirty = false;
QList<InstancePtr> m_instances;
QSet<QString> m_groups;
SettingsObjectPtr m_globalSettings;
QString m_instDir;
QFileSystemWatcher * m_watcher;
QMap<InstanceId, GroupId> m_groupMap;
QSet<InstanceId> instanceSet;
bool m_groupsLoaded = false;
bool m_instancesProbed = false;
};

View File

@@ -0,0 +1,9 @@
#include "InstanceTask.h"
InstanceTask::InstanceTask()
{
}
InstanceTask::~InstanceTask()
{
}

53
api/logic/InstanceTask.h Normal file
View File

@@ -0,0 +1,53 @@
#pragma once
#include "tasks/Task.h"
#include "multimc_logic_export.h"
#include "settings/SettingsObject.h"
class MULTIMC_LOGIC_EXPORT InstanceTask : public Task
{
Q_OBJECT
public:
explicit InstanceTask();
virtual ~InstanceTask();
void setParentSettings(SettingsObjectPtr settings)
{
m_globalSettings = settings;
}
void setStagingPath(const QString &stagingPath)
{
m_stagingPath = stagingPath;
}
void setName(const QString &name)
{
m_instName = name;
}
QString name() const
{
return m_instName;
}
void setIcon(const QString &icon)
{
m_instIcon = icon;
}
void setGroup(const QString &group)
{
m_instGroup = group;
}
QString group() const
{
return m_instGroup;
}
protected: /* data */
SettingsObjectPtr m_globalSettings;
QString m_instName;
QString m_instIcon;
QString m_instGroup;
QString m_stagingPath;
};

272
api/logic/Json.cpp Normal file
View File

@@ -0,0 +1,272 @@
// Licensed under the Apache-2.0 license. See README.md for details.
#include "Json.h"
#include <QFile>
#include "FileSystem.h"
#include <math.h>
namespace Json
{
void write(const QJsonDocument &doc, const QString &filename)
{
FS::write(filename, doc.toJson());
}
void write(const QJsonObject &object, const QString &filename)
{
write(QJsonDocument(object), filename);
}
void write(const QJsonArray &array, const QString &filename)
{
write(QJsonDocument(array), filename);
}
QByteArray toBinary(const QJsonObject &obj)
{
return QJsonDocument(obj).toBinaryData();
}
QByteArray toBinary(const QJsonArray &array)
{
return QJsonDocument(array).toBinaryData();
}
QByteArray toText(const QJsonObject &obj)
{
return QJsonDocument(obj).toJson(QJsonDocument::Compact);
}
QByteArray toText(const QJsonArray &array)
{
return QJsonDocument(array).toJson(QJsonDocument::Compact);
}
static bool isBinaryJson(const QByteArray &data)
{
decltype(QJsonDocument::BinaryFormatTag) tag = QJsonDocument::BinaryFormatTag;
return memcmp(data.constData(), &tag, sizeof(QJsonDocument::BinaryFormatTag)) == 0;
}
QJsonDocument requireDocument(const QByteArray &data, const QString &what)
{
if (isBinaryJson(data))
{
QJsonDocument doc = QJsonDocument::fromBinaryData(data);
if (doc.isNull())
{
throw JsonException(what + ": Invalid JSON (binary JSON detected)");
}
return doc;
}
else
{
QJsonParseError error;
QJsonDocument doc = QJsonDocument::fromJson(data, &error);
if (error.error != QJsonParseError::NoError)
{
throw JsonException(what + ": Error parsing JSON: " + error.errorString());
}
return doc;
}
}
QJsonDocument requireDocument(const QString &filename, const QString &what)
{
return requireDocument(FS::read(filename), what);
}
QJsonObject requireObject(const QJsonDocument &doc, const QString &what)
{
if (!doc.isObject())
{
throw JsonException(what + " is not an object");
}
return doc.object();
}
QJsonArray requireArray(const QJsonDocument &doc, const QString &what)
{
if (!doc.isArray())
{
throw JsonException(what + " is not an array");
}
return doc.array();
}
void writeString(QJsonObject &to, const QString &key, const QString &value)
{
if (!value.isEmpty())
{
to.insert(key, value);
}
}
void writeStringList(QJsonObject &to, const QString &key, const QStringList &values)
{
if (!values.isEmpty())
{
QJsonArray array;
for(auto value: values)
{
array.append(value);
}
to.insert(key, array);
}
}
template<>
QJsonValue toJson<QUrl>(const QUrl &url)
{
return QJsonValue(url.toString(QUrl::FullyEncoded));
}
template<>
QJsonValue toJson<QByteArray>(const QByteArray &data)
{
return QJsonValue(QString::fromLatin1(data.toHex()));
}
template<>
QJsonValue toJson<QDateTime>(const QDateTime &datetime)
{
return QJsonValue(datetime.toString(Qt::ISODate));
}
template<>
QJsonValue toJson<QDir>(const QDir &dir)
{
return QDir::current().relativeFilePath(dir.absolutePath());
}
template<>
QJsonValue toJson<QUuid>(const QUuid &uuid)
{
return uuid.toString();
}
template<>
QJsonValue toJson<QVariant>(const QVariant &variant)
{
return QJsonValue::fromVariant(variant);
}
template<> QByteArray requireIsType<QByteArray>(const QJsonValue &value, const QString &what)
{
const QString string = ensureIsType<QString>(value, what);
// ensure that the string can be safely cast to Latin1
if (string != QString::fromLatin1(string.toLatin1()))
{
throw JsonException(what + " is not encodable as Latin1");
}
return QByteArray::fromHex(string.toLatin1());
}
template<> QJsonArray requireIsType<QJsonArray>(const QJsonValue &value, const QString &what)
{
if (!value.isArray())
{
throw JsonException(what + " is not an array");
}
return value.toArray();
}
template<> QString requireIsType<QString>(const QJsonValue &value, const QString &what)
{
if (!value.isString())
{
throw JsonException(what + " is not a string");
}
return value.toString();
}
template<> bool requireIsType<bool>(const QJsonValue &value, const QString &what)
{
if (!value.isBool())
{
throw JsonException(what + " is not a bool");
}
return value.toBool();
}
template<> double requireIsType<double>(const QJsonValue &value, const QString &what)
{
if (!value.isDouble())
{
throw JsonException(what + " is not a double");
}
return value.toDouble();
}
template<> int requireIsType<int>(const QJsonValue &value, const QString &what)
{
const double doubl = requireIsType<double>(value, what);
if (fmod(doubl, 1) != 0)
{
throw JsonException(what + " is not an integer");
}
return int(doubl);
}
template<> QDateTime requireIsType<QDateTime>(const QJsonValue &value, const QString &what)
{
const QString string = requireIsType<QString>(value, what);
const QDateTime datetime = QDateTime::fromString(string, Qt::ISODate);
if (!datetime.isValid())
{
throw JsonException(what + " is not a ISO formatted date/time value");
}
return datetime;
}
template<> QUrl requireIsType<QUrl>(const QJsonValue &value, const QString &what)
{
const QString string = ensureIsType<QString>(value, what);
if (string.isEmpty())
{
return QUrl();
}
const QUrl url = QUrl(string, QUrl::StrictMode);
if (!url.isValid())
{
throw JsonException(what + " is not a correctly formatted URL");
}
return url;
}
template<> QDir requireIsType<QDir>(const QJsonValue &value, const QString &what)
{
const QString string = requireIsType<QString>(value, what);
// FIXME: does not handle invalid characters!
return QDir::current().absoluteFilePath(string);
}
template<> QUuid requireIsType<QUuid>(const QJsonValue &value, const QString &what)
{
const QString string = requireIsType<QString>(value, what);
const QUuid uuid = QUuid(string);
if (uuid.toString() != string) // converts back => valid
{
throw JsonException(what + " is not a valid UUID");
}
return uuid;
}
template<> QJsonObject requireIsType<QJsonObject>(const QJsonValue &value, const QString &what)
{
if (!value.isObject())
{
throw JsonException(what + " is not an object");
}
return value.toObject();
}
template<> QVariant requireIsType<QVariant>(const QJsonValue &value, const QString &what)
{
if (value.isNull() || value.isUndefined())
{
throw JsonException(what + " is null or undefined");
}
return value.toVariant();
}
template<> QJsonValue requireIsType<QJsonValue>(const QJsonValue &value, const QString &what)
{
if (value.isNull() || value.isUndefined())
{
throw JsonException(what + " is null or undefined");
}
return value;
}
}

249
api/logic/Json.h Normal file
View File

@@ -0,0 +1,249 @@
// Licensed under the Apache-2.0 license. See README.md for details.
#pragma once
#include <QJsonDocument>
#include <QJsonArray>
#include <QJsonObject>
#include <QDateTime>
#include <QUrl>
#include <QDir>
#include <QUuid>
#include <QVariant>
#include <memory>
#include "Exception.h"
namespace Json
{
class MULTIMC_LOGIC_EXPORT JsonException : public ::Exception
{
public:
JsonException(const QString &message) : Exception(message) {}
};
/// @throw FileSystemException
MULTIMC_LOGIC_EXPORT void write(const QJsonDocument &doc, const QString &filename);
/// @throw FileSystemException
MULTIMC_LOGIC_EXPORT void write(const QJsonObject &object, const QString &filename);
/// @throw FileSystemException
MULTIMC_LOGIC_EXPORT void write(const QJsonArray &array, const QString &filename);
MULTIMC_LOGIC_EXPORT QByteArray toBinary(const QJsonObject &obj);
MULTIMC_LOGIC_EXPORT QByteArray toBinary(const QJsonArray &array);
MULTIMC_LOGIC_EXPORT QByteArray toText(const QJsonObject &obj);
MULTIMC_LOGIC_EXPORT QByteArray toText(const QJsonArray &array);
/// @throw JsonException
MULTIMC_LOGIC_EXPORT QJsonDocument requireDocument(const QByteArray &data, const QString &what = "Document");
/// @throw JsonException
MULTIMC_LOGIC_EXPORT QJsonDocument requireDocument(const QString &filename, const QString &what = "Document");
/// @throw JsonException
MULTIMC_LOGIC_EXPORT QJsonObject requireObject(const QJsonDocument &doc, const QString &what = "Document");
/// @throw JsonException
MULTIMC_LOGIC_EXPORT QJsonArray requireArray(const QJsonDocument &doc, const QString &what = "Document");
/////////////////// WRITING ////////////////////
void writeString(QJsonObject & to, const QString &key, const QString &value);
void writeStringList(QJsonObject & to, const QString &key, const QStringList &values);
template<typename T>
QJsonValue toJson(const T &t)
{
return QJsonValue(t);
}
template<>
QJsonValue toJson<QUrl>(const QUrl &url);
template<>
QJsonValue toJson<QByteArray>(const QByteArray &data);
template<>
QJsonValue toJson<QDateTime>(const QDateTime &datetime);
template<>
QJsonValue toJson<QDir>(const QDir &dir);
template<>
QJsonValue toJson<QUuid>(const QUuid &uuid);
template<>
QJsonValue toJson<QVariant>(const QVariant &variant);
template<typename T>
QJsonArray toJsonArray(const QList<T> &container)
{
QJsonArray array;
for (const T item : container)
{
array.append(toJson<T>(item));
}
return array;
}
////////////////// READING ////////////////////
/// @throw JsonException
template <typename T>
T requireIsType(const QJsonValue &value, const QString &what = "Value");
/// @throw JsonException
template<> MULTIMC_LOGIC_EXPORT double requireIsType<double>(const QJsonValue &value, const QString &what);
/// @throw JsonException
template<> MULTIMC_LOGIC_EXPORT bool requireIsType<bool>(const QJsonValue &value, const QString &what);
/// @throw JsonException
template<> MULTIMC_LOGIC_EXPORT int requireIsType<int>(const QJsonValue &value, const QString &what);
/// @throw JsonException
template<> MULTIMC_LOGIC_EXPORT QJsonObject requireIsType<QJsonObject>(const QJsonValue &value, const QString &what);
/// @throw JsonException
template<> MULTIMC_LOGIC_EXPORT QJsonArray requireIsType<QJsonArray>(const QJsonValue &value, const QString &what);
/// @throw JsonException
template<> MULTIMC_LOGIC_EXPORT QJsonValue requireIsType<QJsonValue>(const QJsonValue &value, const QString &what);
/// @throw JsonException
template<> MULTIMC_LOGIC_EXPORT QByteArray requireIsType<QByteArray>(const QJsonValue &value, const QString &what);
/// @throw JsonException
template<> MULTIMC_LOGIC_EXPORT QDateTime requireIsType<QDateTime>(const QJsonValue &value, const QString &what);
/// @throw JsonException
template<> MULTIMC_LOGIC_EXPORT QVariant requireIsType<QVariant>(const QJsonValue &value, const QString &what);
/// @throw JsonException
template<> MULTIMC_LOGIC_EXPORT QString requireIsType<QString>(const QJsonValue &value, const QString &what);
/// @throw JsonException
template<> MULTIMC_LOGIC_EXPORT QUuid requireIsType<QUuid>(const QJsonValue &value, const QString &what);
/// @throw JsonException
template<> MULTIMC_LOGIC_EXPORT QDir requireIsType<QDir>(const QJsonValue &value, const QString &what);
/// @throw JsonException
template<> MULTIMC_LOGIC_EXPORT QUrl requireIsType<QUrl>(const QJsonValue &value, const QString &what);
// the following functions are higher level functions, that make use of the above functions for
// type conversion
template <typename T>
T ensureIsType(const QJsonValue &value, const T default_ = T(), const QString &what = "Value")
{
if (value.isUndefined() || value.isNull())
{
return default_;
}
try
{
return requireIsType<T>(value, what);
}
catch (const JsonException &)
{
return default_;
}
}
/// @throw JsonException
template <typename T>
T requireIsType(const QJsonObject &parent, const QString &key, const QString &what = "__placeholder__")
{
const QString localWhat = QString(what).replace("__placeholder__", '\'' + key + '\'');
if (!parent.contains(key))
{
throw JsonException(localWhat + "s parent does not contain " + localWhat);
}
return requireIsType<T>(parent.value(key), localWhat);
}
template <typename T>
T ensureIsType(const QJsonObject &parent, const QString &key, const T default_ = T(), const QString &what = "__placeholder__")
{
const QString localWhat = QString(what).replace("__placeholder__", '\'' + key + '\'');
if (!parent.contains(key))
{
return default_;
}
return ensureIsType<T>(parent.value(key), default_, localWhat);
}
template <typename T>
QVector<T> requireIsArrayOf(const QJsonDocument &doc)
{
const QJsonArray array = requireArray(doc);
QVector<T> out;
for (const QJsonValue val : array)
{
out.append(requireIsType<T>(val, "Document"));
}
return out;
}
template <typename T>
QVector<T> ensureIsArrayOf(const QJsonValue &value, const QString &what = "Value")
{
const QJsonArray array = ensureIsType<QJsonArray>(value, QJsonArray(), what);
QVector<T> out;
for (const QJsonValue val : array)
{
out.append(requireIsType<T>(val, what));
}
return out;
}
template <typename T>
QVector<T> ensureIsArrayOf(const QJsonValue &value, const QVector<T> default_, const QString &what = "Value")
{
if (value.isUndefined())
{
return default_;
}
return ensureIsArrayOf<T>(value, what);
}
/// @throw JsonException
template <typename T>
QVector<T> requireIsArrayOf(const QJsonObject &parent, const QString &key, const QString &what = "__placeholder__")
{
const QString localWhat = QString(what).replace("__placeholder__", '\'' + key + '\'');
if (!parent.contains(key))
{
throw JsonException(localWhat + "s parent does not contain " + localWhat);
}
return ensureIsArrayOf<T>(parent.value(key), localWhat);
}
template <typename T>
QVector<T> ensureIsArrayOf(const QJsonObject &parent, const QString &key,
const QVector<T> &default_ = QVector<T>(), const QString &what = "__placeholder__")
{
const QString localWhat = QString(what).replace("__placeholder__", '\'' + key + '\'');
if (!parent.contains(key))
{
return default_;
}
return ensureIsArrayOf<T>(parent.value(key), default_, localWhat);
}
// this macro part could be replaced by variadic functions that just pass on their arguments, but that wouldn't work well with IDE helpers
#define JSON_HELPERFUNCTIONS(NAME, TYPE) \
inline TYPE require##NAME(const QJsonValue &value, const QString &what = "Value") \
{ \
return requireIsType<TYPE>(value, what); \
} \
inline TYPE ensure##NAME(const QJsonValue &value, const TYPE default_ = TYPE(), const QString &what = "Value") \
{ \
return ensureIsType<TYPE>(value, default_, what); \
} \
inline TYPE require##NAME(const QJsonObject &parent, const QString &key, const QString &what = "__placeholder__") \
{ \
return requireIsType<TYPE>(parent, key, what); \
} \
inline TYPE ensure##NAME(const QJsonObject &parent, const QString &key, const TYPE default_ = TYPE(), const QString &what = "__placeholder") \
{ \
return ensureIsType<TYPE>(parent, key, default_, what); \
}
JSON_HELPERFUNCTIONS(Array, QJsonArray)
JSON_HELPERFUNCTIONS(Object, QJsonObject)
JSON_HELPERFUNCTIONS(JsonValue, QJsonValue)
JSON_HELPERFUNCTIONS(String, QString)
JSON_HELPERFUNCTIONS(Boolean, bool)
JSON_HELPERFUNCTIONS(Double, double)
JSON_HELPERFUNCTIONS(Integer, int)
JSON_HELPERFUNCTIONS(DateTime, QDateTime)
JSON_HELPERFUNCTIONS(Url, QUrl)
JSON_HELPERFUNCTIONS(ByteArray, QByteArray)
JSON_HELPERFUNCTIONS(Dir, QDir)
JSON_HELPERFUNCTIONS(Uuid, QUuid)
JSON_HELPERFUNCTIONS(Variant, QVariant)
#undef JSON_HELPERFUNCTIONS
}
using JSONValidationError = Json::JsonException;

176
api/logic/LoggedProcess.cpp Normal file
View File

@@ -0,0 +1,176 @@
#include "LoggedProcess.h"
#include "MessageLevel.h"
#include <QDebug>
LoggedProcess::LoggedProcess(QObject *parent) : QProcess(parent)
{
// QProcess has a strange interface... let's map a lot of those into a few.
connect(this, &QProcess::readyReadStandardOutput, this, &LoggedProcess::on_stdOut);
connect(this, &QProcess::readyReadStandardError, this, &LoggedProcess::on_stdErr);
connect(this, SIGNAL(finished(int,QProcess::ExitStatus)), SLOT(on_exit(int,QProcess::ExitStatus)));
connect(this, SIGNAL(error(QProcess::ProcessError)), this, SLOT(on_error(QProcess::ProcessError)));
connect(this, &QProcess::stateChanged, this, &LoggedProcess::on_stateChange);
}
LoggedProcess::~LoggedProcess()
{
if(m_is_detachable)
{
setProcessState(QProcess::NotRunning);
}
}
QStringList reprocess(const QByteArray & data, QString & leftover)
{
QString str = leftover + QString::fromLocal8Bit(data);
str.remove('\r');
QStringList lines = str.split("\n");
leftover = lines.takeLast();
return lines;
}
void LoggedProcess::on_stdErr()
{
auto lines = reprocess(readAllStandardError(), m_err_leftover);
emit log(lines, MessageLevel::StdErr);
}
void LoggedProcess::on_stdOut()
{
auto lines = reprocess(readAllStandardOutput(), m_out_leftover);
emit log(lines, MessageLevel::StdOut);
}
void LoggedProcess::on_exit(int exit_code, QProcess::ExitStatus status)
{
// save the exit code
m_exit_code = exit_code;
// Flush console window
if (!m_err_leftover.isEmpty())
{
emit log({m_err_leftover}, MessageLevel::StdErr);
m_err_leftover.clear();
}
if (!m_out_leftover.isEmpty())
{
emit log({m_err_leftover}, MessageLevel::StdOut);
m_out_leftover.clear();
}
// based on state, send signals
if (!m_is_aborting)
{
if (status == QProcess::NormalExit)
{
//: Message displayed on instance exit
emit log({tr("Process exited with code %1.").arg(exit_code)}, MessageLevel::MultiMC);
changeState(LoggedProcess::Finished);
}
else
{
//: Message displayed on instance crashed
if(exit_code == -1)
emit log({tr("Process crashed.")}, MessageLevel::MultiMC);
else
emit log({tr("Process crashed with exitcode %1.").arg(exit_code)}, MessageLevel::MultiMC);
changeState(LoggedProcess::Crashed);
}
}
else
{
//: Message displayed after the instance exits due to kill request
emit log({tr("Process was killed by user.")}, MessageLevel::Error);
changeState(LoggedProcess::Aborted);
}
}
void LoggedProcess::on_error(QProcess::ProcessError error)
{
switch(error)
{
case QProcess::FailedToStart:
{
emit log({tr("The process failed to start.")}, MessageLevel::Fatal);
changeState(LoggedProcess::FailedToStart);
break;
}
// we'll just ignore those... never needed them
case QProcess::Crashed:
case QProcess::ReadError:
case QProcess::Timedout:
case QProcess::UnknownError:
case QProcess::WriteError:
break;
}
}
void LoggedProcess::kill()
{
m_is_aborting = true;
QProcess::kill();
}
int LoggedProcess::exitCode() const
{
return m_exit_code;
}
void LoggedProcess::changeState(LoggedProcess::State state)
{
if(state == m_state)
return;
m_state = state;
emit stateChanged(m_state);
}
LoggedProcess::State LoggedProcess::state() const
{
return m_state;
}
void LoggedProcess::on_stateChange(QProcess::ProcessState state)
{
switch(state)
{
case QProcess::NotRunning:
break; // let's not - there are too many that handle this already.
case QProcess::Starting:
{
if(m_state != LoggedProcess::NotRunning)
{
qWarning() << "Wrong state change for process from state" << m_state << "to" << (int) LoggedProcess::Starting;
}
changeState(LoggedProcess::Starting);
return;
}
case QProcess::Running:
{
if(m_state != LoggedProcess::Starting)
{
qWarning() << "Wrong state change for process from state" << m_state << "to" << (int) LoggedProcess::Running;
}
changeState(LoggedProcess::Running);
return;
}
}
}
#if defined Q_OS_WIN32
#include <windows.h>
#endif
qint64 LoggedProcess::processId() const
{
#ifdef Q_OS_WIN
return pid() ? pid()->dwProcessId : 0;
#else
return pid();
#endif
}
void LoggedProcess::setDetachable(bool detachable)
{
m_is_detachable = detachable;
}

80
api/logic/LoggedProcess.h Normal file
View File

@@ -0,0 +1,80 @@
/* Copyright 2013-2019 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <QProcess>
#include "MessageLevel.h"
#include "multimc_logic_export.h"
/*
* This is a basic process.
* It has line-based logging support and hides some of the nasty bits.
*/
class MULTIMC_LOGIC_EXPORT LoggedProcess : public QProcess
{
Q_OBJECT
public:
enum State
{
NotRunning,
Starting,
FailedToStart,
Running,
Finished,
Crashed,
Aborted
};
public:
explicit LoggedProcess(QObject* parent = 0);
virtual ~LoggedProcess();
State state() const;
int exitCode() const;
qint64 processId() const;
void setDetachable(bool detachable);
signals:
void log(QStringList lines, MessageLevel::Enum level);
void stateChanged(LoggedProcess::State state);
public slots:
/**
* @brief kill the process - equivalent to kill -9
*/
void kill();
private slots:
void on_stdErr();
void on_stdOut();
void on_exit(int exit_code, QProcess::ExitStatus status);
void on_error(QProcess::ProcessError error);
void on_stateChange(QProcess::ProcessState);
private:
void changeState(LoggedProcess::State state);
private:
QString m_err_leftover;
QString m_out_leftover;
bool m_killed = false;
State m_state = NotRunning;
int m_exit_code = 0;
bool m_is_aborting = false;
bool m_is_detachable = false;
};

76
api/logic/MMCStrings.cpp Normal file
View File

@@ -0,0 +1,76 @@
#include "MMCStrings.h"
/// TAKEN FROM Qt, because it doesn't expose it intelligently
static inline QChar getNextChar(const QString &s, int location)
{
return (location < s.length()) ? s.at(location) : QChar();
}
/// TAKEN FROM Qt, because it doesn't expose it intelligently
int Strings::naturalCompare(const QString &s1, const QString &s2, Qt::CaseSensitivity cs)
{
for (int l1 = 0, l2 = 0; l1 <= s1.count() && l2 <= s2.count(); ++l1, ++l2)
{
// skip spaces, tabs and 0's
QChar c1 = getNextChar(s1, l1);
while (c1.isSpace())
c1 = getNextChar(s1, ++l1);
QChar c2 = getNextChar(s2, l2);
while (c2.isSpace())
c2 = getNextChar(s2, ++l2);
if (c1.isDigit() && c2.isDigit())
{
while (c1.digitValue() == 0)
c1 = getNextChar(s1, ++l1);
while (c2.digitValue() == 0)
c2 = getNextChar(s2, ++l2);
int lookAheadLocation1 = l1;
int lookAheadLocation2 = l2;
int currentReturnValue = 0;
// find the last digit, setting currentReturnValue as we go if it isn't equal
for (QChar lookAhead1 = c1, lookAhead2 = c2;
(lookAheadLocation1 <= s1.length() && lookAheadLocation2 <= s2.length());
lookAhead1 = getNextChar(s1, ++lookAheadLocation1),
lookAhead2 = getNextChar(s2, ++lookAheadLocation2))
{
bool is1ADigit = !lookAhead1.isNull() && lookAhead1.isDigit();
bool is2ADigit = !lookAhead2.isNull() && lookAhead2.isDigit();
if (!is1ADigit && !is2ADigit)
break;
if (!is1ADigit)
return -1;
if (!is2ADigit)
return 1;
if (currentReturnValue == 0)
{
if (lookAhead1 < lookAhead2)
{
currentReturnValue = -1;
}
else if (lookAhead1 > lookAhead2)
{
currentReturnValue = 1;
}
}
}
if (currentReturnValue != 0)
return currentReturnValue;
}
if (cs == Qt::CaseInsensitive)
{
if (!c1.isLower())
c1 = c1.toLower();
if (!c2.isLower())
c2 = c2.toLower();
}
int r = QString::localeAwareCompare(c1, c2);
if (r < 0)
return -1;
if (r > 0)
return 1;
}
// The two strings are the same (02 == 2) so fall back to the normal sort
return QString::compare(s1, s2, cs);
}

10
api/logic/MMCStrings.h Normal file
View File

@@ -0,0 +1,10 @@
#pragma once
#include <QString>
#include "multimc_logic_export.h"
namespace Strings
{
int MULTIMC_LOGIC_EXPORT naturalCompare(const QString &s1, const QString &s2, Qt::CaseSensitivity cs);
}

255
api/logic/MMCZip.cpp Normal file
View File

@@ -0,0 +1,255 @@
/* Copyright 2013-2019 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <quazip.h>
#include <quazipdir.h>
#include <quazipfile.h>
#include <JlCompress.h>
#include "MMCZip.h"
#include "FileSystem.h"
#include <QDebug>
// ours
bool MMCZip::mergeZipFiles(QuaZip *into, QFileInfo from, QSet<QString> &contained, const JlCompress::FilterFunction filter)
{
QuaZip modZip(from.filePath());
modZip.open(QuaZip::mdUnzip);
QuaZipFile fileInsideMod(&modZip);
QuaZipFile zipOutFile(into);
for (bool more = modZip.goToFirstFile(); more; more = modZip.goToNextFile())
{
QString filename = modZip.getCurrentFileName();
if (filter && !filter(filename))
{
qDebug() << "Skipping file " << filename << " from "
<< from.fileName() << " - filtered";
continue;
}
if (contained.contains(filename))
{
qDebug() << "Skipping already contained file " << filename << " from "
<< from.fileName();
continue;
}
contained.insert(filename);
if (!fileInsideMod.open(QIODevice::ReadOnly))
{
qCritical() << "Failed to open " << filename << " from " << from.fileName();
return false;
}
QuaZipNewInfo info_out(fileInsideMod.getActualFileName());
if (!zipOutFile.open(QIODevice::WriteOnly, info_out))
{
qCritical() << "Failed to open " << filename << " in the jar";
fileInsideMod.close();
return false;
}
if (!JlCompress::copyData(fileInsideMod, zipOutFile))
{
zipOutFile.close();
fileInsideMod.close();
qCritical() << "Failed to copy data of " << filename << " into the jar";
return false;
}
zipOutFile.close();
fileInsideMod.close();
}
return true;
}
// ours
bool MMCZip::createModdedJar(QString sourceJarPath, QString targetJarPath, const QList<Mod>& mods)
{
QuaZip zipOut(targetJarPath);
if (!zipOut.open(QuaZip::mdCreate))
{
QFile::remove(targetJarPath);
qCritical() << "Failed to open the minecraft.jar for modding";
return false;
}
// Files already added to the jar.
// These files will be skipped.
QSet<QString> addedFiles;
// Modify the jar
QListIterator<Mod> i(mods);
i.toBack();
while (i.hasPrevious())
{
const Mod &mod = i.previous();
// do not merge disabled mods.
if (!mod.enabled())
continue;
if (mod.type() == Mod::MOD_ZIPFILE)
{
if (!mergeZipFiles(&zipOut, mod.filename(), addedFiles))
{
zipOut.close();
QFile::remove(targetJarPath);
qCritical() << "Failed to add" << mod.filename().fileName() << "to the jar.";
return false;
}
}
else if (mod.type() == Mod::MOD_SINGLEFILE)
{
// FIXME: buggy - does not work with addedFiles
auto filename = mod.filename();
if (!JlCompress::compressFile(&zipOut, filename.absoluteFilePath(), filename.fileName()))
{
zipOut.close();
QFile::remove(targetJarPath);
qCritical() << "Failed to add" << mod.filename().fileName() << "to the jar.";
return false;
}
addedFiles.insert(filename.fileName());
}
else if (mod.type() == Mod::MOD_FOLDER)
{
// FIXME: buggy - does not work with addedFiles
auto filename = mod.filename();
QString what_to_zip = filename.absoluteFilePath();
QDir dir(what_to_zip);
dir.cdUp();
QString parent_dir = dir.absolutePath();
if (!JlCompress::compressSubDir(&zipOut, what_to_zip, parent_dir, addedFiles))
{
zipOut.close();
QFile::remove(targetJarPath);
qCritical() << "Failed to add" << mod.filename().fileName() << "to the jar.";
return false;
}
qDebug() << "Adding folder " << filename.fileName() << " from "
<< filename.absoluteFilePath();
}
else
{
// Make sure we do not continue launching when something is missing or undefined...
zipOut.close();
QFile::remove(targetJarPath);
qCritical() << "Failed to add unknown mod type" << mod.filename().fileName() << "to the jar.";
return false;
}
}
if (!mergeZipFiles(&zipOut, QFileInfo(sourceJarPath), addedFiles, [](const QString key){return !key.contains("META-INF");}))
{
zipOut.close();
QFile::remove(targetJarPath);
qCritical() << "Failed to insert minecraft.jar contents.";
return false;
}
// Recompress the jar
zipOut.close();
if (zipOut.getZipError() != 0)
{
QFile::remove(targetJarPath);
qCritical() << "Failed to finalize minecraft.jar!";
return false;
}
return true;
}
// ours
QString MMCZip::findFolderOfFileInZip(QuaZip * zip, const QString & what, const QString &root)
{
QuaZipDir rootDir(zip, root);
for(auto fileName: rootDir.entryList(QDir::Files))
{
if(fileName == what)
return root;
}
for(auto fileName: rootDir.entryList(QDir::Dirs))
{
QString result = findFolderOfFileInZip(zip, what, root + fileName);
if(!result.isEmpty())
{
return result;
}
}
return QString();
}
// ours
bool MMCZip::findFilesInZip(QuaZip * zip, const QString & what, QStringList & result, const QString &root)
{
QuaZipDir rootDir(zip, root);
for(auto fileName: rootDir.entryList(QDir::Files))
{
if(fileName == what)
{
result.append(root);
return true;
}
}
for(auto fileName: rootDir.entryList(QDir::Dirs))
{
findFilesInZip(zip, what, result, root + fileName);
}
return !result.isEmpty();
}
// ours
QStringList MMCZip::extractSubDir(QuaZip *zip, const QString & subdir, const QString &target)
{
QDir directory(target);
QStringList extracted;
qDebug() << "Extracting subdir" << subdir << "from" << zip->getZipName() << "to" << target;
if (!zip->goToFirstFile())
{
qWarning() << "Failed to seek to first file in zip";
return QStringList();
}
do
{
QString name = zip->getCurrentFileName();
if(!name.startsWith(subdir))
{
continue;
}
name.remove(0, subdir.size());
QString absFilePath = directory.absoluteFilePath(name);
if(name.isEmpty())
{
absFilePath += "/";
}
if (!JlCompress::extractFile(zip, "", absFilePath))
{
qWarning() << "Failed to extract file" << name << "to" << absFilePath;
JlCompress::removeFile(extracted);
return QStringList();
}
extracted.append(absFilePath);
qDebug() << "Extracted file" << name;
} while (zip->goToNextFile());
return extracted;
}
// ours
QStringList MMCZip::extractDir(QString fileCompressed, QString dir)
{
QuaZip zip(fileCompressed);
if (!zip.open(QuaZip::mdUnzip))
{
return {};
}
return MMCZip::extractSubDir(&zip, "", dir);
}

71
api/logic/MMCZip.h Normal file
View File

@@ -0,0 +1,71 @@
/* Copyright 2013-2019 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <QString>
#include <QFileInfo>
#include <QSet>
#include "minecraft/Mod.h"
#include <functional>
#include "multimc_logic_export.h"
#include <JlCompress.h>
namespace MMCZip
{
/**
* Merge two zip files, using a filter function
*/
bool MULTIMC_LOGIC_EXPORT mergeZipFiles(QuaZip *into, QFileInfo from, QSet<QString> &contained,
const JlCompress::FilterFunction filter = nullptr);
/**
* take a source jar, add mods to it, resulting in target jar
*/
bool MULTIMC_LOGIC_EXPORT createModdedJar(QString sourceJarPath, QString targetJarPath, const QList<Mod>& mods);
/**
* Find a single file in archive by file name (not path)
*
* \return the path prefix where the file is
*/
QString MULTIMC_LOGIC_EXPORT findFolderOfFileInZip(QuaZip * zip, const QString & what, const QString &root = QString(""));
/**
* Find a multiple files of the same name in archive by file name
* If a file is found in a path, no deeper paths are searched
*
* \return true if anything was found
*/
bool MULTIMC_LOGIC_EXPORT findFilesInZip(QuaZip * zip, const QString & what, QStringList & result, const QString &root = QString());
/**
* Extract a subdirectory from an archive
*/
QStringList MULTIMC_LOGIC_EXPORT extractSubDir(QuaZip *zip, const QString & subdir, const QString &target);
/**
* Extract a whole archive.
*
* \param fileCompressed The name of the archive.
* \param dir The directory to extract to, the current directory if left empty.
* \return The list of the full paths of the files extracted, empty on failure.
*/
QStringList MULTIMC_LOGIC_EXPORT extractDir(QString fileCompressed, QString dir);
}

View File

@@ -0,0 +1,36 @@
#include "MessageLevel.h"
MessageLevel::Enum MessageLevel::getLevel(const QString& levelName)
{
if (levelName == "MultiMC")
return MessageLevel::MultiMC;
else if (levelName == "Debug")
return MessageLevel::Debug;
else if (levelName == "Info")
return MessageLevel::Info;
else if (levelName == "Message")
return MessageLevel::Message;
else if (levelName == "Warning")
return MessageLevel::Warning;
else if (levelName == "Error")
return MessageLevel::Error;
else if (levelName == "Fatal")
return MessageLevel::Fatal;
// Skip PrePost, it's not exposed to !![]!
// Also skip StdErr and StdOut
else
return MessageLevel::Unknown;
}
MessageLevel::Enum MessageLevel::fromLine(QString &line)
{
// Level prefix
int endmark = line.indexOf("]!");
if (line.startsWith("!![") && endmark != -1)
{
auto level = MessageLevel::getLevel(line.left(endmark).mid(3));
line = line.mid(endmark + 2);
return level;
}
return MessageLevel::Unknown;
}

28
api/logic/MessageLevel.h Normal file
View File

@@ -0,0 +1,28 @@
#pragma once
#include <QString>
/**
* @brief the MessageLevel Enum
* defines what level a log message is
*/
namespace MessageLevel
{
enum Enum
{
Unknown, /**< No idea what this is or where it came from */
StdOut, /**< Undetermined stderr messages */
StdErr, /**< Undetermined stdout messages */
MultiMC, /**< MultiMC Messages */
Debug, /**< Debug Messages */
Info, /**< Info Messages */
Message, /**< Standard Messages */
Warning, /**< Warnings */
Error, /**< Errors */
Fatal, /**< Fatal Errors */
};
MessageLevel::Enum getLevel(const QString &levelName);
/* Get message level from a line. Line is modified if it was successful. */
MessageLevel::Enum fromLine(QString &line);
}

76
api/logic/NullInstance.h Normal file
View File

@@ -0,0 +1,76 @@
#pragma once
#include "BaseInstance.h"
#include "launch/LaunchTask.h"
class NullInstance: public BaseInstance
{
Q_OBJECT
public:
NullInstance(SettingsObjectPtr globalSettings, SettingsObjectPtr settings, const QString& rootDir)
:BaseInstance(globalSettings, settings, rootDir)
{
setVersionBroken(true);
}
virtual ~NullInstance() {};
void saveNow() override
{
}
QString getStatusbarDescription() override
{
return tr("Unknown instance type");
};
QSet< QString > traits() const override
{
return {};
};
QString instanceConfigFolder() const override
{
return instanceRoot();
};
shared_qobject_ptr<LaunchTask> createLaunchTask(AuthSessionPtr) override
{
return nullptr;
}
shared_qobject_ptr< Task > createUpdateTask(Net::Mode mode) override
{
return nullptr;
}
QProcessEnvironment createEnvironment() override
{
return QProcessEnvironment();
}
QMap<QString, QString> getVariables() const override
{
return QMap<QString, QString>();
}
IPathMatcher::Ptr getLogFileMatcher() override
{
return nullptr;
}
QString getLogFileRoot() override
{
return instanceRoot();
}
QString typeName() const override
{
return "Null";
}
bool canExport() const override
{
return false;
}
bool canEdit() const override
{
return false;
}
bool canLaunch() const override
{
return false;
}
QStringList verboseDescription(AuthSessionPtr session) override
{
QStringList out;
out << "Null instance - placeholder.";
return out;
}
};

View File

@@ -0,0 +1,49 @@
#pragma once
#include "multimc_logic_export.h"
enum class ProblemSeverity
{
None,
Warning,
Error
};
struct PatchProblem
{
ProblemSeverity m_severity;
QString m_description;
};
class MULTIMC_LOGIC_EXPORT ProblemProvider
{
public:
virtual ~ProblemProvider() {};
virtual const QList<PatchProblem> getProblems() const = 0;
virtual ProblemSeverity getProblemSeverity() const = 0;
};
class MULTIMC_LOGIC_EXPORT ProblemContainer : public ProblemProvider
{
public:
const QList<PatchProblem> getProblems() const override
{
return m_problems;
}
ProblemSeverity getProblemSeverity() const override
{
return m_problemSeverity;
}
virtual void addProblem(ProblemSeverity severity, const QString &description)
{
if(severity > m_problemSeverity)
{
m_problemSeverity = severity;
}
m_problems.append({severity, description});
}
private:
QList<PatchProblem> m_problems;
ProblemSeverity m_problemSeverity = ProblemSeverity::None;
};

83
api/logic/QObjectPtr.h Normal file
View File

@@ -0,0 +1,83 @@
#pragma once
#include <functional>
#include <memory>
#include <QObject>
namespace details
{
struct DeleteQObjectLater
{
void operator()(QObject *obj) const
{
obj->deleteLater();
}
};
}
/**
* A unique pointer class with unique pointer semantics intended for derivates of QObject
* Calls deleteLater() instead of destroying the contained object immediately
*/
template<typename T> using unique_qobject_ptr = std::unique_ptr<T, details::DeleteQObjectLater>;
/**
* A shared pointer class with shared pointer semantics intended for derivates of QObject
* Calls deleteLater() instead of destroying the contained object immediately
*/
template <typename T>
class shared_qobject_ptr
{
public:
shared_qobject_ptr(){}
shared_qobject_ptr(T * wrap)
{
reset(wrap);
}
shared_qobject_ptr(const shared_qobject_ptr<T>& other)
{
m_ptr = other.m_ptr;
}
template<typename Derived>
shared_qobject_ptr(const shared_qobject_ptr<Derived> &other)
{
m_ptr = other.unwrap();
}
public:
void reset(T * wrap)
{
using namespace std::placeholders;
m_ptr.reset(wrap, std::bind(&QObject::deleteLater, _1));
}
void reset(const shared_qobject_ptr<T> &other)
{
m_ptr = other.m_ptr;
}
void reset()
{
m_ptr.reset();
}
T * get() const
{
return m_ptr.get();
}
T * operator->() const
{
return m_ptr.get();
}
T & operator*() const
{
return *m_ptr.get();
}
operator bool() const
{
return m_ptr.get() != nullptr;
}
const std::shared_ptr <T> unwrap() const
{
return m_ptr;
}
private:
std::shared_ptr <T> m_ptr;
};

63
api/logic/RWStorage.h Normal file
View File

@@ -0,0 +1,63 @@
#pragma once
#include <QWriteLocker>
#include <QReadLocker>
template <typename K, typename V>
class RWStorage
{
public:
void add(K key, V value)
{
QWriteLocker l(&lock);
cache[key] = value;
stale_entries.remove(key);
}
V get(K key)
{
QReadLocker l(&lock);
if(cache.contains(key))
{
return cache[key];
}
else return V();
}
bool get(K key, V& value)
{
QReadLocker l(&lock);
if(cache.contains(key))
{
value = cache[key];
return true;
}
else return false;
}
bool has(K key)
{
QReadLocker l(&lock);
return cache.contains(key);
}
bool stale(K key)
{
QReadLocker l(&lock);
if(!cache.contains(key))
return true;
return stale_entries.contains(key);
}
void setStale(K key)
{
QWriteLocker l(&lock);
if(cache.contains(key))
{
stale_entries.insert(key);
}
}
void clear()
{
QWriteLocker l(&lock);
cache.clear();
stale_entries.clear();
}
private:
QReadWriteLock lock;
QMap<K, V> cache;
QSet<K> stale_entries;
};

View File

@@ -0,0 +1,111 @@
#include "RecursiveFileSystemWatcher.h"
#include <QRegularExpression>
#include <QDebug>
RecursiveFileSystemWatcher::RecursiveFileSystemWatcher(QObject *parent)
: QObject(parent), m_watcher(new QFileSystemWatcher(this))
{
connect(m_watcher, &QFileSystemWatcher::fileChanged, this,
&RecursiveFileSystemWatcher::fileChange);
connect(m_watcher, &QFileSystemWatcher::directoryChanged, this,
&RecursiveFileSystemWatcher::directoryChange);
}
void RecursiveFileSystemWatcher::setRootDir(const QDir &root)
{
bool wasEnabled = m_isEnabled;
disable();
m_root = root;
setFiles(scanRecursive(m_root));
if (wasEnabled)
{
enable();
}
}
void RecursiveFileSystemWatcher::setWatchFiles(const bool watchFiles)
{
bool wasEnabled = m_isEnabled;
disable();
m_watchFiles = watchFiles;
if (wasEnabled)
{
enable();
}
}
void RecursiveFileSystemWatcher::enable()
{
if (m_isEnabled)
{
return;
}
Q_ASSERT(m_root != QDir::root());
addFilesToWatcherRecursive(m_root);
m_isEnabled = true;
}
void RecursiveFileSystemWatcher::disable()
{
if (!m_isEnabled)
{
return;
}
m_isEnabled = false;
m_watcher->removePaths(m_watcher->files());
m_watcher->removePaths(m_watcher->directories());
}
void RecursiveFileSystemWatcher::setFiles(const QStringList &files)
{
if (files != m_files)
{
m_files = files;
emit filesChanged();
}
}
void RecursiveFileSystemWatcher::addFilesToWatcherRecursive(const QDir &dir)
{
m_watcher->addPath(dir.absolutePath());
for (const QString &directory : dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot))
{
addFilesToWatcherRecursive(dir.absoluteFilePath(directory));
}
if (m_watchFiles)
{
for (const QFileInfo &info : dir.entryInfoList(QDir::Files))
{
m_watcher->addPath(info.absoluteFilePath());
}
}
}
QStringList RecursiveFileSystemWatcher::scanRecursive(const QDir &directory)
{
QStringList ret;
if(!m_matcher)
{
return {};
}
for (const QString &dir : directory.entryList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::Hidden))
{
ret.append(scanRecursive(directory.absoluteFilePath(dir)));
}
for (const QString &file : directory.entryList(QDir::Files | QDir::Hidden))
{
auto relPath = m_root.relativeFilePath(directory.absoluteFilePath(file));
if (m_matcher->matches(relPath))
{
ret.append(relPath);
}
}
return ret;
}
void RecursiveFileSystemWatcher::fileChange(const QString &path)
{
emit fileChanged(path);
}
void RecursiveFileSystemWatcher::directoryChange(const QString &path)
{
setFiles(scanRecursive(m_root));
}

View File

@@ -0,0 +1,63 @@
#pragma once
#include <QFileSystemWatcher>
#include <QDir>
#include "pathmatcher/IPathMatcher.h"
#include "multimc_logic_export.h"
class MULTIMC_LOGIC_EXPORT RecursiveFileSystemWatcher : public QObject
{
Q_OBJECT
public:
RecursiveFileSystemWatcher(QObject *parent);
void setRootDir(const QDir &root);
QDir rootDir() const
{
return m_root;
}
// WARNING: setting this to true may be bad for performance
void setWatchFiles(const bool watchFiles);
bool watchFiles() const
{
return m_watchFiles;
}
void setMatcher(IPathMatcher::Ptr matcher)
{
m_matcher = matcher;
}
QStringList files() const
{
return m_files;
}
signals:
void filesChanged();
void fileChanged(const QString &path);
public slots:
void enable();
void disable();
private:
QDir m_root;
bool m_watchFiles = false;
bool m_isEnabled = false;
IPathMatcher::Ptr m_matcher;
QFileSystemWatcher *m_watcher;
QStringList m_files;
void setFiles(const QStringList &files);
void addFilesToWatcherRecursive(const QDir &dir);
QStringList scanRecursive(const QDir &dir);
private slots:
void fileChange(const QString &path);
void directoryChange(const QString &path);
};

View File

@@ -0,0 +1,298 @@
#pragma once
#include <QString>
#include <QMap>
#include <QStringList>
template <char Tseparator>
class SeparatorPrefixTree
{
public:
SeparatorPrefixTree(QStringList paths)
{
insert(paths);
}
SeparatorPrefixTree(bool contained = false)
{
m_contained = contained;
}
void insert(QStringList paths)
{
for(auto &path: paths)
{
insert(path);
}
}
/// insert an exact path into the tree
SeparatorPrefixTree & insert(QString path)
{
auto sepIndex = path.indexOf(Tseparator);
if(sepIndex == -1)
{
children[path] = SeparatorPrefixTree(true);
return children[path];
}
else
{
auto prefix = path.left(sepIndex);
if(!children.contains(prefix))
{
children[prefix] = SeparatorPrefixTree(false);
}
return children[prefix].insert(path.mid(sepIndex + 1));
}
}
/// is the path fully contained in the tree?
bool contains(QString path) const
{
auto node = find(path);
return node != nullptr;
}
/// does the tree cover a path? That means the prefix of the path is contained in the tree
bool covers(QString path) const
{
// if we found some valid node, it's good enough. the tree covers the path
if(m_contained)
{
return true;
}
auto sepIndex = path.indexOf(Tseparator);
if(sepIndex == -1)
{
auto found = children.find(path);
if(found == children.end())
{
return false;
}
return (*found).covers(QString());
}
else
{
auto prefix = path.left(sepIndex);
auto found = children.find(prefix);
if(found == children.end())
{
return false;
}
return (*found).covers(path.mid(sepIndex + 1));
}
}
/// return the contained path that covers the path specified
QString cover(QString path) const
{
// if we found some valid node, it's good enough. the tree covers the path
if(m_contained)
{
return QString("");
}
auto sepIndex = path.indexOf(Tseparator);
if(sepIndex == -1)
{
auto found = children.find(path);
if(found == children.end())
{
return QString();
}
auto nested = (*found).cover(QString());
if(nested.isNull())
{
return nested;
}
if(nested.isEmpty())
return path;
return path + Tseparator + nested;
}
else
{
auto prefix = path.left(sepIndex);
auto found = children.find(prefix);
if(found == children.end())
{
return QString();
}
auto nested = (*found).cover(path.mid(sepIndex + 1));
if(nested.isNull())
{
return nested;
}
if(nested.isEmpty())
return prefix;
return prefix + Tseparator + nested;
}
}
/// Does the path-specified node exist in the tree? It does not have to be contained.
bool exists(QString path) const
{
auto sepIndex = path.indexOf(Tseparator);
if(sepIndex == -1)
{
auto found = children.find(path);
if(found == children.end())
{
return false;
}
return true;
}
else
{
auto prefix = path.left(sepIndex);
auto found = children.find(prefix);
if(found == children.end())
{
return false;
}
return (*found).exists(path.mid(sepIndex + 1));
}
}
/// find a node in the tree by name
const SeparatorPrefixTree * find(QString path) const
{
auto sepIndex = path.indexOf(Tseparator);
if(sepIndex == -1)
{
auto found = children.find(path);
if(found == children.end())
{
return nullptr;
}
return &(*found);
}
else
{
auto prefix = path.left(sepIndex);
auto found = children.find(prefix);
if(found == children.end())
{
return nullptr;
}
return (*found).find(path.mid(sepIndex + 1));
}
}
/// is this a leaf node?
bool leaf() const
{
return children.isEmpty();
}
/// is this node actually contained in the tree, or is it purely structural?
bool contained() const
{
return m_contained;
}
/// Remove a path from the tree
bool remove(QString path)
{
return removeInternal(path) != Failed;
}
/// Clear all children of this node tree node
void clear()
{
children.clear();
}
QStringList toStringList() const
{
QStringList collected;
// collecting these is more expensive.
auto iter = children.begin();
while(iter != children.end())
{
QStringList list = iter.value().toStringList();
for(int i = 0; i < list.size(); i++)
{
list[i] = iter.key() + Tseparator + list[i];
}
collected.append(list);
if((*iter).m_contained)
{
collected.append(iter.key());
}
iter++;
}
return collected;
}
private:
enum Removal
{
Failed,
Succeeded,
HasChildren
};
Removal removeInternal(QString path = QString())
{
if(path.isEmpty())
{
if(!m_contained)
{
// remove all children - we are removing a prefix
clear();
return Succeeded;
}
m_contained = false;
if(children.size())
{
return HasChildren;
}
return Succeeded;
}
Removal remStatus = Failed;
QString childToRemove;
auto sepIndex = path.indexOf(Tseparator);
if(sepIndex == -1)
{
childToRemove = path;
auto found = children.find(childToRemove);
if(found == children.end())
{
return Failed;
}
remStatus = (*found).removeInternal();
}
else
{
childToRemove = path.left(sepIndex);
auto found = children.find(childToRemove);
if(found == children.end())
{
return Failed;
}
remStatus = (*found).removeInternal(path.mid(sepIndex + 1));
}
switch (remStatus)
{
case Failed:
case HasChildren:
{
return remStatus;
}
case Succeeded:
{
children.remove(childToRemove);
if(m_contained)
{
return HasChildren;
}
if(children.size())
{
return HasChildren;
}
return Succeeded;
}
}
return Failed;
}
private:
QMap<QString,SeparatorPrefixTree<Tseparator>> children;
bool m_contained = false;
};

58
api/logic/Usable.h Normal file
View File

@@ -0,0 +1,58 @@
#pragma once
#include <cstddef>
#include <memory>
class Usable;
/**
* Base class for things that can be used by multiple other things and we want to track the use count.
*
* @see UseLock
*/
class Usable
{
friend class UseLock;
public:
std::size_t useCount()
{
return m_useCount;
}
bool isInUse()
{
return m_useCount > 0;
}
protected:
virtual void decrementUses()
{
m_useCount--;
}
virtual void incrementUses()
{
m_useCount++;
}
private:
std::size_t m_useCount = 0;
};
/**
* Lock class to use for keeping track of uses of other things derived from Usable
*
* @see Usable
*/
class UseLock
{
public:
UseLock(std::shared_ptr<Usable> usable)
: m_usable(usable)
{
// this doesn't use shared pointer use count, because that wouldn't be correct. this count is separate.
m_usable->incrementUses();
}
~UseLock()
{
m_usable->decrementUses();
}
private:
std::shared_ptr<Usable> m_usable;
};

85
api/logic/Version.cpp Normal file
View File

@@ -0,0 +1,85 @@
#include "Version.h"
#include <QStringList>
#include <QUrl>
#include <QRegularExpression>
#include <QRegularExpressionMatch>
Version::Version(const QString &str) : m_string(str)
{
parse();
}
bool Version::operator<(const Version &other) const
{
const int size = qMax(m_sections.size(), other.m_sections.size());
for (int i = 0; i < size; ++i)
{
const Section sec1 = (i >= m_sections.size()) ? Section("0") : m_sections.at(i);
const Section sec2 =
(i >= other.m_sections.size()) ? Section("0") : other.m_sections.at(i);
if (sec1 != sec2)
{
return sec1 < sec2;
}
}
return false;
}
bool Version::operator<=(const Version &other) const
{
return *this < other || *this == other;
}
bool Version::operator>(const Version &other) const
{
const int size = qMax(m_sections.size(), other.m_sections.size());
for (int i = 0; i < size; ++i)
{
const Section sec1 = (i >= m_sections.size()) ? Section("0") : m_sections.at(i);
const Section sec2 =
(i >= other.m_sections.size()) ? Section("0") : other.m_sections.at(i);
if (sec1 != sec2)
{
return sec1 > sec2;
}
}
return false;
}
bool Version::operator>=(const Version &other) const
{
return *this > other || *this == other;
}
bool Version::operator==(const Version &other) const
{
const int size = qMax(m_sections.size(), other.m_sections.size());
for (int i = 0; i < size; ++i)
{
const Section sec1 = (i >= m_sections.size()) ? Section("0") : m_sections.at(i);
const Section sec2 =
(i >= other.m_sections.size()) ? Section("0") : other.m_sections.at(i);
if (sec1 != sec2)
{
return false;
}
}
return true;
}
bool Version::operator!=(const Version &other) const
{
return !operator==(other);
}
void Version::parse()
{
m_sections.clear();
// FIXME: this is bad. versions can contain a lot more separators...
QStringList parts = m_string.split('.');
for (const auto part : parts)
{
m_sections.append(Section(part));
}
}

107
api/logic/Version.h Normal file
View File

@@ -0,0 +1,107 @@
#pragma once
#include <QString>
#include <QList>
#include "multimc_logic_export.h"
class QUrl;
class MULTIMC_LOGIC_EXPORT Version
{
public:
Version(const QString &str);
Version() {}
bool operator<(const Version &other) const;
bool operator<=(const Version &other) const;
bool operator>(const Version &other) const;
bool operator>=(const Version &other) const;
bool operator==(const Version &other) const;
bool operator!=(const Version &other) const;
QString toString() const
{
return m_string;
}
private:
QString m_string;
struct Section
{
explicit Section(const QString &fullString)
{
m_fullString = fullString;
int cutoff = m_fullString.size();
for(int i = 0; i < m_fullString.size(); i++)
{
if(!m_fullString[i].isDigit())
{
cutoff = i;
break;
}
}
auto numPart = m_fullString.leftRef(cutoff);
if(numPart.size())
{
numValid = true;
m_numPart = numPart.toInt();
}
auto stringPart = m_fullString.midRef(cutoff);
if(stringPart.size())
{
m_stringPart = stringPart.toString();
}
}
explicit Section() {}
bool numValid = false;
int m_numPart = 0;
QString m_stringPart;
QString m_fullString;
inline bool operator!=(const Section &other) const
{
if(numValid && other.numValid)
{
return m_numPart != other.m_numPart || m_stringPart != other.m_stringPart;
}
else
{
return m_fullString != other.m_fullString;
}
}
inline bool operator<(const Section &other) const
{
if(numValid && other.numValid)
{
if(m_numPart < other.m_numPart)
return true;
if(m_numPart == other.m_numPart && m_stringPart < other.m_stringPart)
return true;
return false;
}
else
{
return m_fullString < other.m_fullString;
}
}
inline bool operator>(const Section &other) const
{
if(numValid && other.numValid)
{
if(m_numPart > other.m_numPart)
return true;
if(m_numPart == other.m_numPart && m_stringPart > other.m_stringPart)
return true;
return false;
}
else
{
return m_fullString > other.m_fullString;
}
}
};
QList<Section> m_sections;
void parse();
};

View File

@@ -0,0 +1,85 @@
/* Copyright 2013-2019 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <QTest>
#include "TestUtil.h"
#include <Version.h>
class ModUtilsTest : public QObject
{
Q_OBJECT
void setupVersions()
{
QTest::addColumn<QString>("first");
QTest::addColumn<QString>("second");
QTest::addColumn<bool>("lessThan");
QTest::addColumn<bool>("equal");
QTest::newRow("equal, explicit") << "1.2.0" << "1.2.0" << false << true;
QTest::newRow("equal, implicit 1") << "1.2" << "1.2.0" << false << true;
QTest::newRow("equal, implicit 2") << "1.2.0" << "1.2" << false << true;
QTest::newRow("equal, two-digit") << "1.42" << "1.42" << false << true;
QTest::newRow("lessThan, explicit 1") << "1.2.0" << "1.2.1" << true << false;
QTest::newRow("lessThan, explicit 2") << "1.2.0" << "1.3.0" << true << false;
QTest::newRow("lessThan, explicit 3") << "1.2.0" << "2.2.0" << true << false;
QTest::newRow("lessThan, implicit 1") << "1.2" << "1.2.1" << true << false;
QTest::newRow("lessThan, implicit 2") << "1.2" << "1.3.0" << true << false;
QTest::newRow("lessThan, implicit 3") << "1.2" << "2.2.0" << true << false;
QTest::newRow("lessThan, two-digit") << "1.41" << "1.42" << true << false;
QTest::newRow("greaterThan, explicit 1") << "1.2.1" << "1.2.0" << false << false;
QTest::newRow("greaterThan, explicit 2") << "1.3.0" << "1.2.0" << false << false;
QTest::newRow("greaterThan, explicit 3") << "2.2.0" << "1.2.0" << false << false;
QTest::newRow("greaterThan, implicit 1") << "1.2.1" << "1.2" << false << false;
QTest::newRow("greaterThan, implicit 2") << "1.3.0" << "1.2" << false << false;
QTest::newRow("greaterThan, implicit 3") << "2.2.0" << "1.2" << false << false;
QTest::newRow("greaterThan, two-digit") << "1.42" << "1.41" << false << false;
}
private slots:
void initTestCase()
{
}
void cleanupTestCase()
{
}
void test_versionCompare_data()
{
setupVersions();
}
void test_versionCompare()
{
QFETCH(QString, first);
QFETCH(QString, second);
QFETCH(bool, lessThan);
QFETCH(bool, equal);
const auto v1 = Version(first);
const auto v2 = Version(second);
QCOMPARE(v1 < v2, lessThan);
QCOMPARE(v1 > v2, !lessThan && !equal);
QCOMPARE(v1 == v2, equal);
}
};
QTEST_GUILESS_MAIN(ModUtilsTest)
#include "Version_test.moc"

20
api/logic/WatchLock.h Normal file
View File

@@ -0,0 +1,20 @@
#pragma once
#include <QString>
#include <QFileSystemWatcher>
struct WatchLock
{
WatchLock(QFileSystemWatcher * watcher, const QString& directory)
: m_watcher(watcher), m_directory(directory)
{
m_watcher->removePath(m_directory);
}
~WatchLock()
{
m_watcher->addPath(m_directory);
}
QFileSystemWatcher * m_watcher;
QString m_directory;
};

View File

@@ -0,0 +1,7 @@
#include "IIconList.h"
// blargh
IIconList::~IIconList()
{
}

View File

@@ -0,0 +1,26 @@
#pragma once
#include <QString>
#include <QStringList>
#include "multimc_logic_export.h"
enum IconType : unsigned
{
Builtin,
Transient,
FileBased,
ICONS_TOTAL,
ToBeDeleted
};
class MULTIMC_LOGIC_EXPORT IIconList
{
public:
virtual ~IIconList();
virtual bool addIcon(const QString &key, const QString &name, const QString &path, const IconType type) = 0;
virtual bool deleteIcon(const QString &key) = 0;
virtual void saveIcon(const QString &key, const QString &path, const char * format) const = 0;
virtual bool iconFileExists(const QString &key) const = 0;
virtual void installIcons(const QStringList &iconFiles) = 0;
virtual void installIcon(const QString &file, const QString &name) = 0;
};

View File

@@ -0,0 +1,62 @@
#include "IconUtils.h"
#include "FileSystem.h"
#include <QDirIterator>
#include <array>
namespace {
std::array<const char *, 6> validIconExtensions = {{
"svg",
"png",
"ico",
"gif",
"jpg",
"jpeg"
}};
}
namespace IconUtils{
QString findBestIconIn(const QString &folder, const QString & iconKey) {
int best_found = validIconExtensions.size();
QString best_filename;
QDirIterator it(folder, QDir::NoDotAndDotDot | QDir::Files, QDirIterator::NoIteratorFlags);
while (it.hasNext()) {
it.next();
auto fileInfo = it.fileInfo();
if(fileInfo.completeBaseName() != iconKey)
continue;
auto extension = fileInfo.suffix();
for(int i = 0; i < best_found; i++) {
if(extension == validIconExtensions[i]) {
best_found = i;
qDebug() << i << " : " << fileInfo.fileName();
best_filename = fileInfo.fileName();
}
}
}
return FS::PathCombine(folder, best_filename);
}
QString getIconFilter() {
QString out;
QTextStream stream(&out);
stream << '(';
for(size_t i = 0; i < validIconExtensions.size() - 1; i++) {
if(i > 0) {
stream << " ";
}
stream << "*." << validIconExtensions[i];
}
stream << " *." << validIconExtensions[validIconExtensions.size() - 1];
stream << ')';
return out;
}
}

View File

@@ -0,0 +1,14 @@
#pragma once
#include <QString>
#include "multimc_logic_export.h"
namespace IconUtils {
// Given a folder and an icon key, find 'best' of the icons with the given key in there and return its path
MULTIMC_LOGIC_EXPORT QString findBestIconIn(const QString &folder, const QString & iconKey);
// Get icon file type filter for file browser dialogs
MULTIMC_LOGIC_EXPORT QString getIconFilter();
}

View File

@@ -0,0 +1,164 @@
#include "JavaChecker.h"
#include "JavaUtils.h"
#include <FileSystem.h>
#include <Commandline.h>
#include <QFile>
#include <QProcess>
#include <QMap>
#include <QCoreApplication>
#include <QDebug>
#include "Env.h"
JavaChecker::JavaChecker(QObject *parent) : QObject(parent)
{
}
void JavaChecker::performCheck()
{
QString checkerJar = FS::PathCombine(ENV.getJarsPath(), "JavaCheck.jar");
QStringList args;
process.reset(new QProcess());
if(m_args.size())
{
auto extraArgs = Commandline::splitArgs(m_args);
args.append(extraArgs);
}
if(m_minMem != 0)
{
args << QString("-Xms%1m").arg(m_minMem);
}
if(m_maxMem != 0)
{
args << QString("-Xmx%1m").arg(m_maxMem);
}
if(m_permGen != 64)
{
args << QString("-XX:PermSize=%1m").arg(m_permGen);
}
args.append({"-jar", checkerJar});
process->setArguments(args);
process->setProgram(m_path);
process->setProcessChannelMode(QProcess::SeparateChannels);
process->setProcessEnvironment(CleanEnviroment());
qDebug() << "Running java checker: " + m_path + args.join(" ");;
connect(process.get(), SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(finished(int, QProcess::ExitStatus)));
connect(process.get(), SIGNAL(error(QProcess::ProcessError)), this, SLOT(error(QProcess::ProcessError)));
connect(process.get(), SIGNAL(readyReadStandardOutput()), this, SLOT(stdoutReady()));
connect(process.get(), SIGNAL(readyReadStandardError()), this, SLOT(stderrReady()));
connect(&killTimer, SIGNAL(timeout()), SLOT(timeout()));
killTimer.setSingleShot(true);
killTimer.start(15000);
process->start();
}
void JavaChecker::stdoutReady()
{
QByteArray data = process->readAllStandardOutput();
QString added = QString::fromLocal8Bit(data);
added.remove('\r');
m_stdout += added;
}
void JavaChecker::stderrReady()
{
QByteArray data = process->readAllStandardError();
QString added = QString::fromLocal8Bit(data);
added.remove('\r');
m_stderr += added;
}
void JavaChecker::finished(int exitcode, QProcess::ExitStatus status)
{
killTimer.stop();
QProcessPtr _process = process;
process.reset();
JavaCheckResult result;
{
result.path = m_path;
result.id = m_id;
}
result.errorLog = m_stderr;
result.outLog = m_stdout;
qDebug() << "STDOUT" << m_stdout;
qWarning() << "STDERR" << m_stderr;
qDebug() << "Java checker finished with status " << status << " exit code " << exitcode;
if (status == QProcess::CrashExit || exitcode == 1)
{
result.validity = JavaCheckResult::Validity::Errored;
emit checkFinished(result);
return;
}
bool success = true;
QMap<QString, QString> results;
QStringList lines = m_stdout.split("\n", QString::SkipEmptyParts);
for(QString line : lines)
{
line = line.trimmed();
auto parts = line.split('=', QString::SkipEmptyParts);
if(parts.size() != 2 || parts[0].isEmpty() || parts[1].isEmpty())
{
success = false;
}
else
{
results.insert(parts[0], parts[1]);
}
}
if(!results.contains("os.arch") || !results.contains("java.version") || !success)
{
result.validity = JavaCheckResult::Validity::ReturnedInvalidData;
emit checkFinished(result);
return;
}
auto os_arch = results["os.arch"];
auto java_version = results["java.version"];
bool is_64 = os_arch == "x86_64" || os_arch == "amd64";
result.validity = JavaCheckResult::Validity::Valid;
result.is_64bit = is_64;
result.mojangPlatform = is_64 ? "64" : "32";
result.realPlatform = os_arch;
result.javaVersion = java_version;
qDebug() << "Java checker succeeded.";
emit checkFinished(result);
}
void JavaChecker::error(QProcess::ProcessError err)
{
if(err == QProcess::FailedToStart)
{
killTimer.stop();
qDebug() << "Java checker has failed to start.";
JavaCheckResult result;
{
result.path = m_path;
result.id = m_id;
}
emit checkFinished(result);
return;
}
}
void JavaChecker::timeout()
{
// NO MERCY. NO ABUSE.
if(process)
{
qDebug() << "Java checker has been killed by timeout.";
process->kill();
}
}

View File

@@ -0,0 +1,62 @@
#pragma once
#include <QProcess>
#include <QTimer>
#include <memory>
#include "QObjectPtr.h"
#include "multimc_logic_export.h"
#include "JavaVersion.h"
class JavaChecker;
struct MULTIMC_LOGIC_EXPORT JavaCheckResult
{
QString path;
QString mojangPlatform;
QString realPlatform;
JavaVersion javaVersion;
QString outLog;
QString errorLog;
bool is_64bit = false;
int id;
enum class Validity
{
Errored,
ReturnedInvalidData,
Valid
} validity = Validity::Errored;
};
typedef shared_qobject_ptr<QProcess> QProcessPtr;
typedef shared_qobject_ptr<JavaChecker> JavaCheckerPtr;
class MULTIMC_LOGIC_EXPORT JavaChecker : public QObject
{
Q_OBJECT
public:
explicit JavaChecker(QObject *parent = 0);
void performCheck();
QString m_path;
QString m_args;
int m_id = 0;
int m_minMem = 0;
int m_maxMem = 0;
int m_permGen = 64;
signals:
void checkFinished(JavaCheckResult result);
private:
QProcessPtr process;
QTimer killTimer;
QString m_stdout;
QString m_stderr;
public
slots:
void timeout();
void finished(int exitcode, QProcess::ExitStatus);
void error(QProcess::ProcessError);
void stdoutReady();
void stderrReady();
};

View File

@@ -1,4 +1,4 @@
/* Copyright 2013-2015 MultiMC Contributors
/* Copyright 2013-2019 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -14,33 +14,31 @@
*/
#include "JavaCheckerJob.h"
#include "pathutils.h"
#include <QDebug>
void JavaCheckerJob::partFinished(JavaCheckResult result)
{
num_finished++;
qDebug() << m_job_name.toLocal8Bit() << "progress:" << num_finished << "/"
<< javacheckers.size();
emit progress(num_finished, javacheckers.size());
num_finished++;
qDebug() << m_job_name.toLocal8Bit() << "progress:" << num_finished << "/"
<< javacheckers.size();
setProgress(num_finished, javacheckers.size());
javaresults.replace(result.id, result);
javaresults.replace(result.id, result);
if (num_finished == javacheckers.size())
{
emit finished(javaresults);
}
if (num_finished == javacheckers.size())
{
emitSucceeded();
}
}
void JavaCheckerJob::executeTask()
{
qDebug() << m_job_name.toLocal8Bit() << " started.";
m_running = true;
for (auto iter : javacheckers)
{
javaresults.append(JavaCheckResult());
connect(iter.get(), SIGNAL(checkFinished(JavaCheckResult)), SLOT(partFinished(JavaCheckResult)));
iter->performCheck();
}
qDebug() << m_job_name.toLocal8Bit() << " started.";
for (auto iter : javacheckers)
{
javaresults.append(JavaCheckResult());
connect(iter.get(), SIGNAL(checkFinished(JavaCheckResult)), SLOT(partFinished(JavaCheckResult)));
iter->performCheck();
}
}

View File

@@ -0,0 +1,61 @@
/* Copyright 2013-2019 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <QtNetwork>
#include "JavaChecker.h"
#include "tasks/Task.h"
class JavaCheckerJob;
typedef shared_qobject_ptr<JavaCheckerJob> JavaCheckerJobPtr;
// FIXME: this just seems horribly redundant
class JavaCheckerJob : public Task
{
Q_OBJECT
public:
explicit JavaCheckerJob(QString job_name) : Task(), m_job_name(job_name) {};
virtual ~JavaCheckerJob() {};
bool addJavaCheckerAction(JavaCheckerPtr base)
{
javacheckers.append(base);
// if this is already running, the action needs to be started right away!
if (isRunning())
{
setProgress(num_finished, javacheckers.size());
connect(base.get(), &JavaChecker::checkFinished, this, &JavaCheckerJob::partFinished);
base->performCheck();
}
return true;
}
QList<JavaCheckResult> getResults()
{
return javaresults;
}
private slots:
void partFinished(JavaCheckResult result);
protected:
virtual void executeTask() override;
private:
QString m_job_name;
QList<JavaCheckerPtr> javacheckers;
QList<JavaCheckResult> javaresults;
int num_finished = 0;
};

View File

@@ -0,0 +1,28 @@
#include "JavaInstall.h"
#include <MMCStrings.h>
bool JavaInstall::operator<(const JavaInstall &rhs)
{
auto archCompare = Strings::naturalCompare(arch, rhs.arch, Qt::CaseInsensitive);
if(archCompare != 0)
return archCompare < 0;
if(id < rhs.id)
{
return true;
}
if(id > rhs.id)
{
return false;
}
return Strings::naturalCompare(path, rhs.path, Qt::CaseInsensitive) < 0;
}
bool JavaInstall::operator==(const JavaInstall &rhs)
{
return arch == rhs.arch && id == rhs.id && path == rhs.path;
}
bool JavaInstall::operator>(const JavaInstall &rhs)
{
return (!operator<(rhs)) && (!operator==(rhs));
}

View File

@@ -0,0 +1,38 @@
#pragma once
#include "BaseVersion.h"
#include "JavaVersion.h"
struct JavaInstall : public BaseVersion
{
JavaInstall(){}
JavaInstall(QString id, QString arch, QString path)
: id(id), arch(arch), path(path)
{
}
virtual QString descriptor()
{
return id.toString();
}
virtual QString name()
{
return id.toString();
}
virtual QString typeString() const
{
return arch;
}
bool operator<(const JavaInstall & rhs);
bool operator==(const JavaInstall & rhs);
bool operator>(const JavaInstall & rhs);
JavaVersion id;
QString arch;
QString path;
bool recommended = false;
};
typedef std::shared_ptr<JavaInstall> JavaInstallPtr;

View File

@@ -0,0 +1,208 @@
/* Copyright 2013-2019 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <QtNetwork>
#include <QtXml>
#include <QRegExp>
#include <QDebug>
#include "java/JavaInstallList.h"
#include "java/JavaCheckerJob.h"
#include "java/JavaUtils.h"
#include "MMCStrings.h"
#include "minecraft/VersionFilterData.h"
JavaInstallList::JavaInstallList(QObject *parent) : BaseVersionList(parent)
{
}
shared_qobject_ptr<Task> JavaInstallList::getLoadTask()
{
load();
return getCurrentTask();
}
shared_qobject_ptr<Task> JavaInstallList::getCurrentTask()
{
if(m_status == Status::InProgress)
{
return m_loadTask;
}
return nullptr;
}
void JavaInstallList::load()
{
if(m_status != Status::InProgress)
{
m_status = Status::InProgress;
m_loadTask = new JavaListLoadTask(this);
m_loadTask->start();
}
}
const BaseVersionPtr JavaInstallList::at(int i) const
{
return m_vlist.at(i);
}
bool JavaInstallList::isLoaded()
{
return m_status == JavaInstallList::Status::Done;
}
int JavaInstallList::count() const
{
return m_vlist.count();
}
QVariant JavaInstallList::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
if (index.row() > count())
return QVariant();
auto version = std::dynamic_pointer_cast<JavaInstall>(m_vlist[index.row()]);
switch (role)
{
case VersionPointerRole:
return qVariantFromValue(m_vlist[index.row()]);
case VersionIdRole:
return version->descriptor();
case VersionRole:
return version->id.toString();
case RecommendedRole:
return version->recommended;
case PathRole:
return version->path;
case ArchitectureRole:
return version->arch;
default:
return QVariant();
}
}
BaseVersionList::RoleList JavaInstallList::providesRoles() const
{
return {VersionPointerRole, VersionIdRole, VersionRole, RecommendedRole, PathRole, ArchitectureRole};
}
void JavaInstallList::updateListData(QList<BaseVersionPtr> versions)
{
beginResetModel();
m_vlist = versions;
sortVersions();
if(m_vlist.size())
{
auto best = std::dynamic_pointer_cast<JavaInstall>(m_vlist[0]);
best->recommended = true;
}
endResetModel();
m_status = Status::Done;
m_loadTask.reset();
}
bool sortJavas(BaseVersionPtr left, BaseVersionPtr right)
{
auto rleft = std::dynamic_pointer_cast<JavaInstall>(left);
auto rright = std::dynamic_pointer_cast<JavaInstall>(right);
return (*rleft) > (*rright);
}
void JavaInstallList::sortVersions()
{
beginResetModel();
std::sort(m_vlist.begin(), m_vlist.end(), sortJavas);
endResetModel();
}
JavaListLoadTask::JavaListLoadTask(JavaInstallList *vlist) : Task()
{
m_list = vlist;
m_currentRecommended = NULL;
}
JavaListLoadTask::~JavaListLoadTask()
{
}
void JavaListLoadTask::executeTask()
{
setStatus(tr("Detecting Java installations..."));
JavaUtils ju;
QList<QString> candidate_paths = ju.FindJavaPaths();
m_job = new JavaCheckerJob("Java detection");
connect(m_job.get(), &Task::finished, this, &JavaListLoadTask::javaCheckerFinished);
connect(m_job.get(), &Task::progress, this, &Task::setProgress);
qDebug() << "Probing the following Java paths: ";
int id = 0;
for(QString candidate : candidate_paths)
{
qDebug() << " " << candidate;
auto candidate_checker = new JavaChecker();
candidate_checker->m_path = candidate;
candidate_checker->m_id = id;
m_job->addJavaCheckerAction(JavaCheckerPtr(candidate_checker));
id++;
}
m_job->start();
}
void JavaListLoadTask::javaCheckerFinished()
{
QList<JavaInstallPtr> candidates;
auto results = m_job->getResults();
qDebug() << "Found the following valid Java installations:";
for(JavaCheckResult result : results)
{
if(result.validity == JavaCheckResult::Validity::Valid)
{
JavaInstallPtr javaVersion(new JavaInstall());
javaVersion->id = result.javaVersion;
javaVersion->arch = result.mojangPlatform;
javaVersion->path = result.path;
candidates.append(javaVersion);
qDebug() << " " << javaVersion->id.toString() << javaVersion->arch << javaVersion->path;
}
}
QList<BaseVersionPtr> javas_bvp;
for (auto java : candidates)
{
//qDebug() << java->id << java->arch << " at " << java->path;
BaseVersionPtr bp_java = std::dynamic_pointer_cast<BaseVersion>(java);
if (bp_java)
{
javas_bvp.append(java);
}
}
m_list->updateListData(javas_bvp);
emitSucceeded();
}

View File

@@ -0,0 +1,83 @@
/* Copyright 2013-2019 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <QObject>
#include <QAbstractListModel>
#include "BaseVersionList.h"
#include "tasks/Task.h"
#include "JavaCheckerJob.h"
#include "JavaInstall.h"
#include "QObjectPtr.h"
#include "multimc_logic_export.h"
class JavaListLoadTask;
class MULTIMC_LOGIC_EXPORT JavaInstallList : public BaseVersionList
{
Q_OBJECT
enum class Status
{
NotDone,
InProgress,
Done
};
public:
explicit JavaInstallList(QObject *parent = 0);
shared_qobject_ptr<Task> getLoadTask() override;
bool isLoaded() override;
const BaseVersionPtr at(int i) const override;
int count() const override;
void sortVersions() override;
QVariant data(const QModelIndex &index, int role) const override;
RoleList providesRoles() const override;
public slots:
void updateListData(QList<BaseVersionPtr> versions) override;
protected:
void load();
shared_qobject_ptr<Task> getCurrentTask();
protected:
Status m_status = Status::NotDone;
shared_qobject_ptr<JavaListLoadTask> m_loadTask;
QList<BaseVersionPtr> m_vlist;
};
class JavaListLoadTask : public Task
{
Q_OBJECT
public:
explicit JavaListLoadTask(JavaInstallList *vlist);
virtual ~JavaListLoadTask();
void executeTask() override;
public slots:
void javaCheckerFinished();
protected:
shared_qobject_ptr<JavaCheckerJob> m_job;
JavaInstallList *m_list;
JavaInstall *m_currentRecommended;
};

View File

@@ -0,0 +1,345 @@
/* Copyright 2013-2019 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <QStringList>
#include <QString>
#include <QDir>
#include <QStringList>
#include <settings/Setting.h>
#include <QDebug>
#include "java/JavaUtils.h"
#include "java/JavaInstallList.h"
#include "FileSystem.h"
#define IBUS "@im=ibus"
JavaUtils::JavaUtils()
{
}
#ifdef Q_OS_LINUX
static QString processLD_LIBRARY_PATH(const QString & LD_LIBRARY_PATH)
{
QDir mmcBin(QCoreApplication::applicationDirPath());
auto items = LD_LIBRARY_PATH.split(':');
QStringList final;
for(auto & item: items)
{
QDir test(item);
if(test == mmcBin)
{
qDebug() << "Env:LD_LIBRARY_PATH ignoring path" << item;
continue;
}
final.append(item);
}
return final.join(':');
}
#endif
QProcessEnvironment CleanEnviroment()
{
// prepare the process environment
QProcessEnvironment rawenv = QProcessEnvironment::systemEnvironment();
QProcessEnvironment env;
QStringList ignored =
{
"JAVA_ARGS",
"CLASSPATH",
"CONFIGPATH",
"JAVA_HOME",
"JRE_HOME",
"_JAVA_OPTIONS",
"JAVA_OPTIONS",
"JAVA_TOOL_OPTIONS"
};
for(auto key: rawenv.keys())
{
auto value = rawenv.value(key);
// filter out dangerous java crap
if(ignored.contains(key))
{
qDebug() << "Env: ignoring" << key << value;
continue;
}
// filter MultiMC-related things
if(key.startsWith("QT_"))
{
qDebug() << "Env: ignoring" << key << value;
continue;
}
#ifdef Q_OS_LINUX
// Do not pass LD_* variables to java. They were intended for MultiMC
if(key.startsWith("LD_"))
{
qDebug() << "Env: ignoring" << key << value;
continue;
}
// Strip IBus
// IBus is a Linux IME framework. For some reason, it breaks MC?
if (key == "XMODIFIERS" && value.contains(IBUS))
{
QString save = value;
value.replace(IBUS, "");
qDebug() << "Env: stripped" << IBUS << "from" << save << ":" << value;
}
if(key == "GAME_PRELOAD")
{
env.insert("LD_PRELOAD", value);
continue;
}
if(key == "GAME_LIBRARY_PATH")
{
env.insert("LD_LIBRARY_PATH", processLD_LIBRARY_PATH(value));
continue;
}
#endif
// qDebug() << "Env: " << key << value;
env.insert(key, value);
}
#ifdef Q_OS_LINUX
// HACK: Workaround for QTBUG42500
if(!env.contains("LD_LIBRARY_PATH"))
{
env.insert("LD_LIBRARY_PATH", "");
}
#endif
return env;
}
JavaInstallPtr JavaUtils::MakeJavaPtr(QString path, QString id, QString arch)
{
JavaInstallPtr javaVersion(new JavaInstall());
javaVersion->id = id;
javaVersion->arch = arch;
javaVersion->path = path;
return javaVersion;
}
JavaInstallPtr JavaUtils::GetDefaultJava()
{
JavaInstallPtr javaVersion(new JavaInstall());
javaVersion->id = "java";
javaVersion->arch = "unknown";
#if defined(Q_OS_WIN32)
javaVersion->path = "javaw";
#else
javaVersion->path = "java";
#endif
return javaVersion;
}
#if defined(Q_OS_WIN32)
QList<JavaInstallPtr> JavaUtils::FindJavaFromRegistryKey(DWORD keyType, QString keyName)
{
QList<JavaInstallPtr> javas;
QString archType = "unknown";
if (keyType == KEY_WOW64_64KEY)
archType = "64";
else if (keyType == KEY_WOW64_32KEY)
archType = "32";
HKEY jreKey;
if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, keyName.toStdString().c_str(), 0,
KEY_READ | keyType | KEY_ENUMERATE_SUB_KEYS, &jreKey) == ERROR_SUCCESS)
{
// Read the current type version from the registry.
// This will be used to find any key that contains the JavaHome value.
char *value = new char[0];
DWORD valueSz = 0;
if (RegQueryValueExA(jreKey, "CurrentVersion", NULL, NULL, (BYTE *)value, &valueSz) ==
ERROR_MORE_DATA)
{
value = new char[valueSz];
RegQueryValueExA(jreKey, "CurrentVersion", NULL, NULL, (BYTE *)value, &valueSz);
}
QString recommended = value;
TCHAR subKeyName[255];
DWORD subKeyNameSize, numSubKeys, retCode;
// Get the number of subkeys
RegQueryInfoKey(jreKey, NULL, NULL, NULL, &numSubKeys, NULL, NULL, NULL, NULL, NULL,
NULL, NULL);
// Iterate until RegEnumKeyEx fails
if (numSubKeys > 0)
{
for (DWORD i = 0; i < numSubKeys; i++)
{
subKeyNameSize = 255;
retCode = RegEnumKeyEx(jreKey, i, subKeyName, &subKeyNameSize, NULL, NULL, NULL,
NULL);
if (retCode == ERROR_SUCCESS)
{
// Now open the registry key for the version that we just got.
QString newKeyName = keyName + "\\" + subKeyName;
HKEY newKey;
if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, newKeyName.toStdString().c_str(), 0,
KEY_READ | KEY_WOW64_64KEY, &newKey) == ERROR_SUCCESS)
{
// Read the JavaHome value to find where Java is installed.
value = new char[0];
valueSz = 0;
if (RegQueryValueEx(newKey, "JavaHome", NULL, NULL, (BYTE *)value,
&valueSz) == ERROR_MORE_DATA)
{
value = new char[valueSz];
RegQueryValueEx(newKey, "JavaHome", NULL, NULL, (BYTE *)value,
&valueSz);
// Now, we construct the version object and add it to the list.
JavaInstallPtr javaVersion(new JavaInstall());
javaVersion->id = subKeyName;
javaVersion->arch = archType;
javaVersion->path =
QDir(FS::PathCombine(value, "bin")).absoluteFilePath("javaw.exe");
javas.append(javaVersion);
}
RegCloseKey(newKey);
}
}
}
}
RegCloseKey(jreKey);
}
return javas;
}
QList<QString> JavaUtils::FindJavaPaths()
{
QList<JavaInstallPtr> java_candidates;
QList<JavaInstallPtr> JRE64s = this->FindJavaFromRegistryKey(
KEY_WOW64_64KEY, "SOFTWARE\\JavaSoft\\Java Runtime Environment");
QList<JavaInstallPtr> JDK64s = this->FindJavaFromRegistryKey(
KEY_WOW64_64KEY, "SOFTWARE\\JavaSoft\\Java Development Kit");
QList<JavaInstallPtr> JRE32s = this->FindJavaFromRegistryKey(
KEY_WOW64_32KEY, "SOFTWARE\\JavaSoft\\Java Runtime Environment");
QList<JavaInstallPtr> JDK32s = this->FindJavaFromRegistryKey(
KEY_WOW64_32KEY, "SOFTWARE\\JavaSoft\\Java Development Kit");
java_candidates.append(JRE64s);
java_candidates.append(MakeJavaPtr("C:/Program Files/Java/jre8/bin/javaw.exe"));
java_candidates.append(MakeJavaPtr("C:/Program Files/Java/jre7/bin/javaw.exe"));
java_candidates.append(MakeJavaPtr("C:/Program Files/Java/jre6/bin/javaw.exe"));
java_candidates.append(JDK64s);
java_candidates.append(JRE32s);
java_candidates.append(MakeJavaPtr("C:/Program Files (x86)/Java/jre8/bin/javaw.exe"));
java_candidates.append(MakeJavaPtr("C:/Program Files (x86)/Java/jre7/bin/javaw.exe"));
java_candidates.append(MakeJavaPtr("C:/Program Files (x86)/Java/jre6/bin/javaw.exe"));
java_candidates.append(JDK32s);
java_candidates.append(MakeJavaPtr(this->GetDefaultJava()->path));
QList<QString> candidates;
for(JavaInstallPtr java_candidate : java_candidates)
{
if(!candidates.contains(java_candidate->path))
{
candidates.append(java_candidate->path);
}
}
return candidates;
}
#elif defined(Q_OS_MAC)
QList<QString> JavaUtils::FindJavaPaths()
{
QList<QString> javas;
javas.append(this->GetDefaultJava()->path);
javas.append("/Applications/Xcode.app/Contents/Applications/Application Loader.app/Contents/MacOS/itms/java/bin/java");
javas.append("/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/bin/java");
javas.append("/System/Library/Frameworks/JavaVM.framework/Versions/Current/Commands/java");
QDir libraryJVMDir("/Library/Java/JavaVirtualMachines/");
QStringList libraryJVMJavas = libraryJVMDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot);
foreach (const QString &java, libraryJVMJavas) {
javas.append(libraryJVMDir.absolutePath() + "/" + java + "/Contents/Home/bin/java");
javas.append(libraryJVMDir.absolutePath() + "/" + java + "/Contents/Home/jre/bin/java");
}
QDir systemLibraryJVMDir("/System/Library/Java/JavaVirtualMachines/");
QStringList systemLibraryJVMJavas = systemLibraryJVMDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot);
foreach (const QString &java, systemLibraryJVMJavas) {
javas.append(systemLibraryJVMDir.absolutePath() + "/" + java + "/Contents/Home/bin/java");
javas.append(systemLibraryJVMDir.absolutePath() + "/" + java + "/Contents/Commands/java");
}
return javas;
}
#elif defined(Q_OS_LINUX)
QList<QString> JavaUtils::FindJavaPaths()
{
qDebug() << "Linux Java detection incomplete - defaulting to \"java\"";
QList<QString> javas;
javas.append(this->GetDefaultJava()->path);
auto scanJavaDir = [&](const QString & dirPath)
{
QDir dir(dirPath);
if(!dir.exists())
return;
auto entries = dir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks);
for(auto & entry: entries)
{
QString prefix;
if(entry.isAbsolute())
{
prefix = entry.absoluteFilePath();
}
else
{
prefix = entry.filePath();
}
javas.append(FS::PathCombine(prefix, "jre/bin/java"));
javas.append(FS::PathCombine(prefix, "bin/java"));
}
};
// oracle RPMs
scanJavaDir("/usr/java");
// general locations used by distro packaging
scanJavaDir("/usr/lib/jvm");
scanJavaDir("/usr/lib32/jvm");
// javas stored in MultiMC's folder
scanJavaDir("java");
return javas;
}
#else
QList<QString> JavaUtils::FindJavaPaths()
{
qDebug() << "Unknown operating system build - defaulting to \"java\"";
QList<QString> javas;
javas.append(this->GetDefaultJava()->path);
return javas;
}
#endif

View File

@@ -1,4 +1,4 @@
/* Copyright 2013-2015 MultiMC Contributors
/* Copyright 2013-2019 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,28 +16,29 @@
#pragma once
#include <QStringList>
#include <QWidget>
#include <osutils.h>
#include "JavaCheckerJob.h"
#include "JavaChecker.h"
#include "JavaVersionList.h"
#include "JavaInstallList.h"
#if WINDOWS
#ifdef Q_OS_WIN
#include <windows.h>
#endif
class JavaUtils : public QObject
#include "multimc_logic_export.h"
QProcessEnvironment CleanEnviroment();
class MULTIMC_LOGIC_EXPORT JavaUtils : public QObject
{
Q_OBJECT
Q_OBJECT
public:
JavaUtils();
JavaUtils();
JavaVersionPtr MakeJavaPtr(QString path, QString id = "unknown", QString arch = "unknown");
QList<QString> FindJavaPaths();
JavaVersionPtr GetDefaultJava();
JavaInstallPtr MakeJavaPtr(QString path, QString id = "unknown", QString arch = "unknown");
QList<QString> FindJavaPaths();
JavaInstallPtr GetDefaultJava();
#if WINDOWS
QList<JavaVersionPtr> FindJavaFromRegistryKey(DWORD keyType, QString keyName);
#ifdef Q_OS_WIN
QList<JavaInstallPtr> FindJavaFromRegistryKey(DWORD keyType, QString keyName);
#endif
};

View File

@@ -0,0 +1,121 @@
#include "JavaVersion.h"
#include <MMCStrings.h>
#include <QRegularExpression>
#include <QString>
JavaVersion & JavaVersion::operator=(const QString & javaVersionString)
{
m_string = javaVersionString;
auto getCapturedInteger = [](const QRegularExpressionMatch & match, const QString &what) -> int
{
auto str = match.captured(what);
if(str.isEmpty())
{
return 0;
}
return str.toInt();
};
QRegularExpression pattern;
if(javaVersionString.startsWith("1."))
{
pattern = QRegularExpression ("1[.](?<major>[0-9]+)([.](?<minor>[0-9]+))?(_(?<security>[0-9]+)?)?(-(?<prerelease>[a-zA-Z0-9]+))?");
}
else
{
pattern = QRegularExpression("(?<major>[0-9]+)([.](?<minor>[0-9]+))?([.](?<security>[0-9]+))?(-(?<prerelease>[a-zA-Z0-9]+))?");
}
auto match = pattern.match(m_string);
m_parseable = match.hasMatch();
m_major = getCapturedInteger(match, "major");
m_minor = getCapturedInteger(match, "minor");
m_security = getCapturedInteger(match, "security");
m_prerelease = match.captured("prerelease");
return *this;
}
JavaVersion::JavaVersion(const QString &rhs)
{
operator=(rhs);
}
QString JavaVersion::toString()
{
return m_string;
}
bool JavaVersion::requiresPermGen()
{
if(m_parseable)
{
return m_major < 8;
}
return true;
}
bool JavaVersion::operator<(const JavaVersion &rhs)
{
if(m_parseable && rhs.m_parseable)
{
auto major = m_major;
auto rmajor = rhs.m_major;
// HACK: discourage using java 9
if(major > 8)
major = -major;
if(rmajor > 8)
rmajor = -rmajor;
if(major < rmajor)
return true;
if(major > rmajor)
return false;
if(m_minor < rhs.m_minor)
return true;
if(m_minor > rhs.m_minor)
return false;
if(m_security < rhs.m_security)
return true;
if(m_security > rhs.m_security)
return false;
// everything else being equal, consider prerelease status
bool thisPre = !m_prerelease.isEmpty();
bool rhsPre = !rhs.m_prerelease.isEmpty();
if(thisPre && !rhsPre)
{
// this is a prerelease and the other one isn't -> lesser
return true;
}
else if(!thisPre && rhsPre)
{
// this isn't a prerelease and the other one is -> greater
return false;
}
else if(thisPre && rhsPre)
{
// both are prereleases - use natural compare...
return Strings::naturalCompare(m_prerelease, rhs.m_prerelease, Qt::CaseSensitive) < 0;
}
// neither is prerelease, so they are the same -> this cannot be less than rhs
return false;
}
else return Strings::naturalCompare(m_string, rhs.m_string, Qt::CaseSensitive) < 0;
}
bool JavaVersion::operator==(const JavaVersion &rhs)
{
if(m_parseable && rhs.m_parseable)
{
return m_major == rhs.m_major && m_minor == rhs.m_minor && m_security == rhs.m_security && m_prerelease == rhs.m_prerelease;
}
return m_string == rhs.m_string;
}
bool JavaVersion::operator>(const JavaVersion &rhs)
{
return (!operator<(rhs)) && (!operator==(rhs));
}

View File

@@ -0,0 +1,50 @@
#pragma once
#include "multimc_logic_export.h"
#include <QString>
// NOTE: apparently the GNU C library pollutes the global namespace with these... undef them.
#ifdef major
#undef major
#endif
#ifdef minor
#undef minor
#endif
class MULTIMC_LOGIC_EXPORT JavaVersion
{
friend class JavaVersionTest;
public:
JavaVersion() {};
JavaVersion(const QString & rhs);
JavaVersion & operator=(const QString & rhs);
bool operator<(const JavaVersion & rhs);
bool operator==(const JavaVersion & rhs);
bool operator>(const JavaVersion & rhs);
bool requiresPermGen();
QString toString();
int major()
{
return m_major;
}
int minor()
{
return m_minor;
}
int security()
{
return m_security;
}
private:
QString m_string;
int m_major = 0;
int m_minor = 0;
int m_security = 0;
bool m_parseable = false;
QString m_prerelease;
};

View File

@@ -0,0 +1,116 @@
#include <QTest>
#include "TestUtil.h"
#include "java/JavaVersion.h"
class JavaVersionTest : public QObject
{
Q_OBJECT
private
slots:
void test_Parse_data()
{
QTest::addColumn<QString>("string");
QTest::addColumn<int>("major");
QTest::addColumn<int>("minor");
QTest::addColumn<int>("security");
QTest::addColumn<QString>("prerelease");
QTest::newRow("old format") << "1.6.0_33" << 6 << 0 << 33 << QString();
QTest::newRow("old format prerelease") << "1.9.0_1-ea" << 9 << 0 << 1 << "ea";
QTest::newRow("new format major") << "9" << 9 << 0 << 0 << QString();
QTest::newRow("new format minor") << "9.1" << 9 << 1 << 0 << QString();
QTest::newRow("new format security") << "9.0.1" << 9 << 0 << 1 << QString();
QTest::newRow("new format prerelease") << "9-ea" << 9 << 0 << 0 << "ea";
QTest::newRow("new format long prerelease") << "9.0.1-ea" << 9 << 0 << 1 << "ea";
}
void test_Parse()
{
QFETCH(QString, string);
QFETCH(int, major);
QFETCH(int, minor);
QFETCH(int, security);
QFETCH(QString, prerelease);
JavaVersion test(string);
QCOMPARE(test.m_string, string);
QCOMPARE(test.toString(), string);
QCOMPARE(test.m_major, major);
QCOMPARE(test.m_minor, minor);
QCOMPARE(test.m_security, security);
QCOMPARE(test.m_prerelease, prerelease);
}
void test_Sort_data()
{
QTest::addColumn<QString>("lhs");
QTest::addColumn<QString>("rhs");
QTest::addColumn<bool>("smaller");
QTest::addColumn<bool>("equal");
QTest::addColumn<bool>("bigger");
// old format and new format equivalence
QTest::newRow("1.6.0_33 == 6.0.33") << "1.6.0_33" << "6.0.33" << false << true << false;
// old format major version
QTest::newRow("1.5.0_33 < 1.6.0_33") << "1.5.0_33" << "1.6.0_33" << true << false << false;
// new format - first release vs first security patch
QTest::newRow("9 < 9.0.1") << "9" << "9.0.1" << true << false << false;
QTest::newRow("9.0.1 > 9") << "9.0.1" << "9" << false << false << true;
// new format - first minor vs first release/security patch
QTest::newRow("9.1 > 9.0.1") << "9.1" << "9.0.1" << false << false << true;
QTest::newRow("9.0.1 < 9.1") << "9.0.1" << "9.1" << true << false << false;
QTest::newRow("9.1 > 9") << "9.1" << "9" << false << false << true;
QTest::newRow("9 > 9.1") << "9" << "9.1" << true << false << false;
// new format - omitted numbers
QTest::newRow("9 == 9.0") << "9" << "9.0" << false << true << false;
QTest::newRow("9 == 9.0.0") << "9" << "9.0.0" << false << true << false;
QTest::newRow("9.0 == 9.0.0") << "9.0" << "9.0.0" << false << true << false;
// early access and prereleases compared to final release
QTest::newRow("9-ea < 9") << "9-ea" << "9" << true << false << false;
QTest::newRow("9 < 9.0.1-ea") << "9" << "9.0.1-ea" << true << false << false;
QTest::newRow("9.0.1-ea > 9") << "9.0.1-ea" << "9" << false << false << true;
// prerelease difference only testing
QTest::newRow("9-1 == 9-1") << "9-1" << "9-1" << false << true << false;
QTest::newRow("9-1 < 9-2") << "9-1" << "9-2" << true << false << false;
QTest::newRow("9-5 < 9-20") << "9-5" << "9-20" << true << false << false;
QTest::newRow("9-rc1 < 9-rc2") << "9-rc1" << "9-rc2" << true << false << false;
QTest::newRow("9-rc5 < 9-rc20") << "9-rc5" << "9-rc20" << true << false << false;
QTest::newRow("9-rc < 9-rc2") << "9-rc" << "9-rc2" << true << false << false;
QTest::newRow("9-ea < 9-rc") << "9-ea" << "9-rc" << true << false << false;
}
void test_Sort()
{
QFETCH(QString, lhs);
QFETCH(QString, rhs);
QFETCH(bool, smaller);
QFETCH(bool, equal);
QFETCH(bool, bigger);
JavaVersion lver(lhs);
JavaVersion rver(rhs);
QCOMPARE(lver < rver, smaller);
QCOMPARE(lver == rver, equal);
QCOMPARE(lver > rver, bigger);
}
void test_PermGen_data()
{
QTest::addColumn<QString>("version");
QTest::addColumn<bool>("needs_permgen");
QTest::newRow("1.6.0_33") << "1.6.0_33" << true;
QTest::newRow("1.7.0_60") << "1.7.0_60" << true;
QTest::newRow("1.8.0_22") << "1.8.0_22" << false;
QTest::newRow("9-ea") << "9-ea" << false;
QTest::newRow("9.2.4") << "9.2.4" << false;
}
void test_PermGen()
{
QFETCH(QString, version);
QFETCH(bool, needs_permgen);
JavaVersion v(version);
QCOMPARE(needs_permgen, v.requiresPermGen());
}
};
QTEST_GUILESS_MAIN(JavaVersionTest)
#include "JavaVersion_test.moc"

View File

@@ -0,0 +1,136 @@
/* Copyright 2013-2019 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "CheckJava.h"
#include <launch/LaunchTask.h>
#include <FileSystem.h>
#include <QStandardPaths>
#include <QFileInfo>
#include <sys.h>
void CheckJava::executeTask()
{
auto instance = m_parent->instance();
auto settings = instance->settings();
m_javaPath = FS::ResolveExecutable(settings->get("JavaPath").toString());
bool perInstance = settings->get("OverrideJava").toBool() || settings->get("OverrideJavaLocation").toBool();
auto realJavaPath = QStandardPaths::findExecutable(m_javaPath);
if (realJavaPath.isEmpty())
{
if (perInstance)
{
emit logLine(
tr("The java binary \"%1\" couldn't be found. Please fix the java path "
"override in the instance's settings or disable it.").arg(m_javaPath),
MessageLevel::Warning);
}
else
{
emit logLine(tr("The java binary \"%1\" couldn't be found. Please set up java in "
"the settings.").arg(m_javaPath),
MessageLevel::Warning);
}
emitFailed(tr("Java path is not valid."));
return;
}
else
{
emit logLine("Java path is:\n" + m_javaPath + "\n\n", MessageLevel::MultiMC);
}
QFileInfo javaInfo(realJavaPath);
qlonglong javaUnixTime = javaInfo.lastModified().toMSecsSinceEpoch();
auto storedUnixTime = settings->get("JavaTimestamp").toLongLong();
auto storedArchitecture = settings->get("JavaArchitecture").toString();
auto storedVersion = settings->get("JavaVersion").toString();
m_javaUnixTime = javaUnixTime;
// if timestamps are not the same, or something is missing, check!
if (javaUnixTime != storedUnixTime || storedVersion.size() == 0 || storedArchitecture.size() == 0)
{
m_JavaChecker = new JavaChecker();
emit logLine(tr("Checking Java version..."), MessageLevel::MultiMC);
connect(m_JavaChecker.get(), &JavaChecker::checkFinished, this, &CheckJava::checkJavaFinished);
m_JavaChecker->m_path = realJavaPath;
m_JavaChecker->performCheck();
return;
}
else
{
auto verString = instance->settings()->get("JavaVersion").toString();
auto archString = instance->settings()->get("JavaArchitecture").toString();
printJavaInfo(verString, archString);
}
emitSucceeded();
}
void CheckJava::checkJavaFinished(JavaCheckResult result)
{
switch (result.validity)
{
case JavaCheckResult::Validity::Errored:
{
// Error message displayed if java can't start
emit logLine(tr("Could not start java:"), MessageLevel::Error);
emit logLines(result.errorLog.split('\n'), MessageLevel::Error);
emit logLine("\nCheck your MultiMC Java settings.", MessageLevel::MultiMC);
printSystemInfo(false, false);
emitFailed(tr("Could not start java!"));
return;
}
case JavaCheckResult::Validity::ReturnedInvalidData:
{
emit logLine(tr("Java checker returned some invalid data MultiMC doesn't understand:"), MessageLevel::Error);
emit logLines(result.outLog.split('\n'), MessageLevel::Warning);
emit logLine("\nMinecraft might not start properly.", MessageLevel::MultiMC);
printSystemInfo(false, false);
emitSucceeded();
return;
}
case JavaCheckResult::Validity::Valid:
{
auto instance = m_parent->instance();
printJavaInfo(result.javaVersion.toString(), result.mojangPlatform);
instance->settings()->set("JavaVersion", result.javaVersion.toString());
instance->settings()->set("JavaArchitecture", result.mojangPlatform);
instance->settings()->set("JavaTimestamp", m_javaUnixTime);
emitSucceeded();
return;
}
}
}
void CheckJava::printJavaInfo(const QString& version, const QString& architecture)
{
emit logLine(tr("Java is version %1, using %2-bit architecture.\n\n").arg(version, architecture), MessageLevel::MultiMC);
printSystemInfo(true, architecture == "64");
}
void CheckJava::printSystemInfo(bool javaIsKnown, bool javaIs64bit)
{
auto cpu64 = Sys::isCPU64bit();
auto system64 = Sys::isSystem64bit();
if(cpu64 != system64)
{
emit logLine(tr("Your CPU architecture is not matching your system architecture. You might want to install a 64bit Operating System.\n\n"), MessageLevel::Error);
}
if(javaIsKnown)
{
if(javaIs64bit != system64)
{
emit logLine(tr("Your Java architecture is not matching your system architecture. You might want to install a 64bit Java version.\n\n"), MessageLevel::Error);
}
}
}

View File

@@ -0,0 +1,45 @@
/* Copyright 2013-2019 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <launch/LaunchStep.h>
#include <LoggedProcess.h>
#include <java/JavaChecker.h>
class CheckJava: public LaunchStep
{
Q_OBJECT
public:
explicit CheckJava(LaunchTask *parent) :LaunchStep(parent){};
virtual ~CheckJava() {};
virtual void executeTask();
virtual bool canAbort() const
{
return false;
}
private slots:
void checkJavaFinished(JavaCheckResult result);
private:
void printJavaInfo(const QString & version, const QString & architecture);
void printSystemInfo(bool javaIsKnown, bool javaIs64bit);
private:
QString m_javaPath;
qlonglong m_javaUnixTime;
JavaCheckerPtr m_JavaChecker;
};

View File

@@ -0,0 +1,27 @@
/* Copyright 2013-2019 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "LaunchStep.h"
#include "LaunchTask.h"
void LaunchStep::bind(LaunchTask *parent)
{
m_parent = parent;
connect(this, &LaunchStep::readyForLaunch, parent, &LaunchTask::onReadyForLaunch);
connect(this, &LaunchStep::logLine, parent, &LaunchTask::onLogLine);
connect(this, &LaunchStep::logLines, parent, &LaunchTask::onLogLines);
connect(this, &LaunchStep::finished, parent, &LaunchTask::onStepFinished);
connect(this, &LaunchStep::progressReportingRequest, parent, &LaunchTask::onProgressReportingRequested);
}

View File

@@ -0,0 +1,50 @@
/* Copyright 2013-2019 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include "tasks/Task.h"
#include "MessageLevel.h"
#include <QStringList>
class LaunchTask;
class LaunchStep: public Task
{
Q_OBJECT
public: /* methods */
explicit LaunchStep(LaunchTask *parent):Task(nullptr), m_parent(parent)
{
bind(parent);
};
virtual ~LaunchStep() {};
private: /* methods */
void bind(LaunchTask *parent);
signals:
void logLines(QStringList lines, MessageLevel::Enum level);
void logLine(QString line, MessageLevel::Enum level);
void readyForLaunch();
void progressReportingRequest();
public slots:
virtual void proceed() {};
// called in the opposite order than the Task launch(), used to clean up or otherwise undo things after the launch ends
virtual void finalize() {};
protected: /* data */
LaunchTask *m_parent;
};

View File

@@ -0,0 +1,280 @@
/* Copyright 2013-2019 MultiMC Contributors
*
* Authors: Orochimarufan <orochimarufan.x3@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "launch/LaunchTask.h"
#include "MessageLevel.h"
#include "MMCStrings.h"
#include "java/JavaChecker.h"
#include "tasks/Task.h"
#include <QDebug>
#include <QDir>
#include <QEventLoop>
#include <QRegularExpression>
#include <QCoreApplication>
#include <QStandardPaths>
#include <assert.h>
void LaunchTask::init()
{
m_instance->setRunning(true);
}
shared_qobject_ptr<LaunchTask> LaunchTask::create(InstancePtr inst)
{
shared_qobject_ptr<LaunchTask> proc(new LaunchTask(inst));
proc->init();
return proc;
}
LaunchTask::LaunchTask(InstancePtr instance): m_instance(instance)
{
}
void LaunchTask::appendStep(shared_qobject_ptr<LaunchStep> step)
{
m_steps.append(step);
}
void LaunchTask::prependStep(shared_qobject_ptr<LaunchStep> step)
{
m_steps.prepend(step);
}
void LaunchTask::executeTask()
{
m_instance->setCrashed(false);
if(!m_steps.size())
{
state = LaunchTask::Finished;
emitSucceeded();
}
state = LaunchTask::Running;
onStepFinished();
}
void LaunchTask::onReadyForLaunch()
{
state = LaunchTask::Waiting;
emit readyForLaunch();
}
void LaunchTask::onStepFinished()
{
// initial -> just start the first step
if(currentStep == -1)
{
currentStep ++;
m_steps[currentStep]->start();
return;
}
auto step = m_steps[currentStep];
if(step->wasSuccessful())
{
// end?
if(currentStep == m_steps.size() - 1)
{
finalizeSteps(true, QString());
}
else
{
currentStep ++;
step = m_steps[currentStep];
step->start();
}
}
else
{
finalizeSteps(false, step->failReason());
}
}
void LaunchTask::finalizeSteps(bool successful, const QString& error)
{
for(auto step = currentStep; step >= 0; step--)
{
m_steps[step]->finalize();
}
if(successful)
{
emitSucceeded();
}
else
{
emitFailed(error);
}
}
void LaunchTask::onProgressReportingRequested()
{
state = LaunchTask::Waiting;
emit requestProgress(m_steps[currentStep].get());
}
void LaunchTask::setCensorFilter(QMap<QString, QString> filter)
{
m_censorFilter = filter;
}
QString LaunchTask::censorPrivateInfo(QString in)
{
auto iter = m_censorFilter.begin();
while (iter != m_censorFilter.end())
{
in.replace(iter.key(), iter.value());
iter++;
}
return in;
}
void LaunchTask::proceed()
{
if(state != LaunchTask::Waiting)
{
return;
}
m_steps[currentStep]->proceed();
}
bool LaunchTask::canAbort() const
{
switch(state)
{
case LaunchTask::Aborted:
case LaunchTask::Failed:
case LaunchTask::Finished:
return false;
case LaunchTask::NotStarted:
return true;
case LaunchTask::Running:
case LaunchTask::Waiting:
{
auto step = m_steps[currentStep];
return step->canAbort();
}
}
return false;
}
bool LaunchTask::abort()
{
switch(state)
{
case LaunchTask::Aborted:
case LaunchTask::Failed:
case LaunchTask::Finished:
return true;
case LaunchTask::NotStarted:
{
state = LaunchTask::Aborted;
emitFailed("Aborted");
return true;
}
case LaunchTask::Running:
case LaunchTask::Waiting:
{
auto step = m_steps[currentStep];
if(!step->canAbort())
{
return false;
}
if(step->abort())
{
state = LaunchTask::Aborted;
return true;
}
}
default:
break;
}
return false;
}
shared_qobject_ptr<LogModel> LaunchTask::getLogModel()
{
if(!m_logModel)
{
m_logModel.reset(new LogModel());
m_logModel->setMaxLines(m_instance->getConsoleMaxLines());
m_logModel->setStopOnOverflow(m_instance->shouldStopOnConsoleOverflow());
// FIXME: should this really be here?
m_logModel->setOverflowMessage(tr("MultiMC stopped watching the game log because the log length surpassed %1 lines.\n"
"You may have to fix your mods because the game is still logging to files and"
" likely wasting harddrive space at an alarming rate!").arg(m_logModel->getMaxLines()));
}
return m_logModel;
}
void LaunchTask::onLogLines(const QStringList &lines, MessageLevel::Enum defaultLevel)
{
for (auto & line: lines)
{
onLogLine(line, defaultLevel);
}
}
void LaunchTask::onLogLine(QString line, MessageLevel::Enum level)
{
// if the launcher part set a log level, use it
auto innerLevel = MessageLevel::fromLine(line);
if(innerLevel != MessageLevel::Unknown)
{
level = innerLevel;
}
// If the level is still undetermined, guess level
if (level == MessageLevel::StdErr || level == MessageLevel::StdOut || level == MessageLevel::Unknown)
{
level = m_instance->guessLevel(line, level);
}
// censor private user info
line = censorPrivateInfo(line);
auto &model = *getLogModel();
model.append(level, line);
}
void LaunchTask::emitSucceeded()
{
m_instance->setRunning(false);
Task::emitSucceeded();
}
void LaunchTask::emitFailed(QString reason)
{
m_instance->setRunning(false);
m_instance->setCrashed(true);
Task::emitFailed(reason);
}
QString LaunchTask::substituteVariables(const QString &cmd) const
{
QString out = cmd;
auto variables = m_instance->getVariables();
for (auto it = variables.begin(); it != variables.end(); ++it)
{
out.replace("$" + it.key(), it.value());
}
auto env = QProcessEnvironment::systemEnvironment();
for (auto var : env.keys())
{
out.replace("$" + var, env.value(var));
}
return out;
}

View File

@@ -0,0 +1,125 @@
/* Copyright 2013-2019 MultiMC Contributors
*
* Authors: Orochimarufan <orochimarufan.x3@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <QProcess>
#include <QObjectPtr.h>
#include "LogModel.h"
#include "BaseInstance.h"
#include "MessageLevel.h"
#include "LoggedProcess.h"
#include "LaunchStep.h"
#include "multimc_logic_export.h"
class MULTIMC_LOGIC_EXPORT LaunchTask: public Task
{
Q_OBJECT
protected:
explicit LaunchTask(InstancePtr instance);
void init();
public:
enum State
{
NotStarted,
Running,
Waiting,
Failed,
Aborted,
Finished
};
public: /* methods */
static shared_qobject_ptr<LaunchTask> create(InstancePtr inst);
virtual ~LaunchTask() {};
void appendStep(shared_qobject_ptr<LaunchStep> step);
void prependStep(shared_qobject_ptr<LaunchStep> step);
void setCensorFilter(QMap<QString, QString> filter);
InstancePtr instance()
{
return m_instance;
}
void setPid(qint64 pid)
{
m_pid = pid;
}
qint64 pid()
{
return m_pid;
}
/**
* @brief prepare the process for launch (for multi-stage launch)
*/
virtual void executeTask() override;
/**
* @brief launch the armed instance
*/
void proceed();
/**
* @brief abort launch
*/
bool abort() override;
bool canAbort() const override;
shared_qobject_ptr<LogModel> getLogModel();
public:
QString substituteVariables(const QString &cmd) const;
QString censorPrivateInfo(QString in);
protected: /* methods */
virtual void emitFailed(QString reason) override;
virtual void emitSucceeded() override;
signals:
/**
* @brief emitted when the launch preparations are done
*/
void readyForLaunch();
void requestProgress(Task *task);
void requestLogging();
public slots:
void onLogLines(const QStringList& lines, MessageLevel::Enum defaultLevel = MessageLevel::MultiMC);
void onLogLine(QString line, MessageLevel::Enum defaultLevel = MessageLevel::MultiMC);
void onReadyForLaunch();
void onStepFinished();
void onProgressReportingRequested();
private: /*methods */
void finalizeSteps(bool successful, const QString & error);
protected: /* data */
InstancePtr m_instance;
shared_qobject_ptr<LogModel> m_logModel;
QList <shared_qobject_ptr<LaunchStep>> m_steps;
QMap<QString, QString> m_censorFilter;
int currentStep = -1;
State state = NotStarted;
qint64 m_pid = -1;
};

View File

@@ -0,0 +1,167 @@
#include "LogModel.h"
LogModel::LogModel(QObject *parent):QAbstractListModel(parent)
{
m_content.resize(m_maxLines);
}
int LogModel::rowCount(const QModelIndex &parent) const
{
if (parent.isValid())
return 0;
return m_numLines;
}
QVariant LogModel::data(const QModelIndex &index, int role) const
{
if (index.row() < 0 || index.row() >= m_numLines)
return QVariant();
auto row = index.row();
auto realRow = (row + m_firstLine) % m_maxLines;
if (role == Qt::DisplayRole || role == Qt::EditRole)
{
return m_content[realRow].line;
}
if(role == LevelRole)
{
return m_content[realRow].level;
}
return QVariant();
}
void LogModel::append(MessageLevel::Enum level, QString line)
{
if(m_suspended)
{
return;
}
int lineNum = (m_firstLine + m_numLines) % m_maxLines;
// overflow
if(m_numLines == m_maxLines)
{
if(m_stopOnOverflow)
{
// nothing more to do, the buffer is full
return;
}
beginRemoveRows(QModelIndex(), 0, 0);
m_firstLine = (m_firstLine + 1) % m_maxLines;
m_numLines --;
endRemoveRows();
}
else if (m_numLines == m_maxLines - 1 && m_stopOnOverflow)
{
level = MessageLevel::Fatal;
line = m_overflowMessage;
}
beginInsertRows(QModelIndex(), m_numLines, m_numLines);
m_numLines ++;
m_content[lineNum].level = level;
m_content[lineNum].line = line;
endInsertRows();
}
void LogModel::suspend(bool suspend)
{
m_suspended = suspend;
}
bool LogModel::suspended()
{
return m_suspended;
}
void LogModel::clear()
{
beginResetModel();
m_firstLine = 0;
m_numLines = 0;
endResetModel();
}
QString LogModel::toPlainText()
{
QString out;
out.reserve(m_numLines * 80);
for(int i = 0; i < m_numLines; i++)
{
QString & line = m_content[(m_firstLine + i) % m_maxLines].line;
out.append(line + '\n');
}
out.squeeze();
return out;
}
void LogModel::setMaxLines(int maxLines)
{
// no-op
if(maxLines == m_maxLines)
{
return;
}
// if it all still fits in the buffer, just resize it
if(m_firstLine + m_numLines < m_maxLines)
{
m_maxLines = maxLines;
m_content.resize(maxLines);
return;
}
// otherwise, we need to reorganize the data because it crosses the wrap boundary
QVector<entry> newContent;
newContent.resize(maxLines);
if(m_numLines <= maxLines)
{
// if it all fits in the new buffer, just copy it over
for(int i = 0; i < m_numLines; i++)
{
newContent[i] = m_content[(m_firstLine + i) % m_maxLines];
}
m_content.swap(newContent);
}
else
{
// if it doesn't fit, part of the data needs to be thrown away (the oldest log messages)
int lead = m_numLines - maxLines;
beginRemoveRows(QModelIndex(), 0, lead - 1);
for(int i = 0; i < maxLines; i++)
{
newContent[i] = m_content[(m_firstLine + lead + i) % m_maxLines];
}
m_numLines = m_maxLines;
m_content.swap(newContent);
endRemoveRows();
}
m_firstLine = 0;
m_maxLines = maxLines;
}
int LogModel::getMaxLines()
{
return m_maxLines;
}
void LogModel::setStopOnOverflow(bool stop)
{
m_stopOnOverflow = stop;
}
void LogModel::setOverflowMessage(const QString& overflowMessage)
{
m_overflowMessage = overflowMessage;
}
void LogModel::setLineWrap(bool state)
{
if(m_lineWrap != state)
{
m_lineWrap = state;
}
}
bool LogModel::wrapLines() const
{
return m_lineWrap;
}

View File

@@ -0,0 +1,60 @@
#pragma once
#include <QAbstractListModel>
#include <QString>
#include "MessageLevel.h"
#include <multimc_logic_export.h>
class MULTIMC_LOGIC_EXPORT LogModel : public QAbstractListModel
{
Q_OBJECT
public:
explicit LogModel(QObject *parent = 0);
int rowCount(const QModelIndex &parent = QModelIndex()) const;
QVariant data(const QModelIndex &index, int role) const;
void append(MessageLevel::Enum, QString line);
void clear();
void suspend(bool suspend);
bool suspended();
QString toPlainText();
int getMaxLines();
void setMaxLines(int maxLines);
void setStopOnOverflow(bool stop);
void setOverflowMessage(const QString & overflowMessage);
void setLineWrap(bool state);
bool wrapLines() const;
enum Roles
{
LevelRole = Qt::UserRole
};
private /* types */:
struct entry
{
MessageLevel::Enum level;
QString line;
};
private: /* data */
QVector <entry> m_content;
int m_maxLines = 1000;
// first line in the circular buffer
int m_firstLine = 0;
// number of lines occupied in the circular buffer
int m_numLines = 0;
bool m_stopOnOverflow = false;
QString m_overflowMessage = "OVERFLOW";
bool m_suspended = false;
bool m_lineWrap = true;
private:
Q_DISABLE_COPY(LogModel)
};

Some files were not shown because too many files have changed in this diff Show More