From bb7e8985f6d189de0acac6a1c3033cb16378c1fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Petr=20Mr=C3=A1zek?= Date: Mon, 4 Nov 2013 02:53:05 +0100 Subject: Reformat and (slightly) decruft all the things. --- CMakeLists.txt | 134 ++-- MultiMC.cpp | 6 +- depends/classparser/include/classparser_config.h | 5 +- depends/classparser/include/javautils.h | 8 +- depends/classparser/src/annotations.cpp | 136 ++-- depends/classparser/src/annotations.h | 487 +++++------ depends/classparser/src/classfile.h | 269 ++++--- depends/classparser/src/constants.h | 374 ++++----- depends/classparser/src/errors.h | 4 +- depends/classparser/src/javaendian.h | 54 +- depends/classparser/src/javautils.cpp | 17 +- depends/classparser/src/membuffer.h | 105 ++- depends/launcher/MCFrame.java | 163 ++-- depends/pack200/src/unpack.cpp | 8 +- depends/settings/include/basicsettingsobject.h | 16 +- depends/settings/include/inifile.h | 7 +- depends/settings/include/inisettingsobject.h | 31 +- depends/settings/include/keyring.h | 12 +- depends/settings/include/libsettings_config.h | 14 +- depends/settings/include/overridesetting.h | 13 +- depends/settings/include/setting.h | 51 +- depends/settings/include/settingsobject.h | 77 +- depends/settings/src/basicsettingsobject.cpp | 8 +- depends/settings/src/inifile.cpp | 32 +- depends/settings/src/inisettingsobject.cpp | 10 +- depends/settings/src/overridesetting.cpp | 6 +- depends/settings/src/setting.cpp | 9 +- depends/settings/src/settingsobject.cpp | 66 +- depends/settings/src/stubkeyring.cpp | 15 +- depends/settings/src/stubkeyring.h | 11 +- depends/util/CMakeLists.txt | 17 +- depends/util/include/apputils.h | 21 - depends/util/include/cmdutils.h | 77 +- depends/util/include/libutil_config.h | 15 +- depends/util/include/osutils.h | 11 +- depends/util/include/pathutils.h | 15 +- depends/util/include/siglist.h | 129 --- depends/util/include/siglist_impl.h | 156 ---- depends/util/include/userutils.h | 8 +- depends/util/src/cmdutils.cpp | 194 ++--- depends/util/src/osutils.cpp | 19 - depends/util/src/pathutils.cpp | 35 +- depends/util/src/userutils.cpp | 82 +- depends/xz-embedded/include/xz.h | 44 +- depends/xz-embedded/src/xz_config.h | 35 +- depends/xz-embedded/src/xz_crc32.c | 8 +- depends/xz-embedded/src/xz_crc64.c | 8 +- depends/xz-embedded/src/xz_dec_bcj.c | 148 ++-- depends/xz-embedded/src/xz_dec_lzma2.c | 324 +++++--- depends/xz-embedded/src/xz_dec_stream.c | 207 ++--- depends/xz-embedded/src/xz_lzma2.h | 8 +- depends/xz-embedded/src/xz_private.h | 124 ++- depends/xz-embedded/src/xz_stream.h | 14 +- depends/xz-embedded/xzminidec.c | 35 +- gui/ConsoleWindow.cpp | 135 ++++ gui/ConsoleWindow.h | 79 ++ gui/ConsoleWindow.ui | 85 ++ gui/CopyInstanceDialog.cpp | 84 -- gui/CopyInstanceDialog.h | 50 -- gui/CopyInstanceDialog.ui | 134 ---- gui/CustomMessageBox.cpp | 19 - gui/CustomMessageBox.h | 11 - gui/EditNotesDialog.cpp | 29 - gui/EditNotesDialog.h | 20 - gui/EditNotesDialog.ui | 77 -- gui/IconPickerDialog.cpp | 147 ---- gui/IconPickerDialog.h | 29 - gui/IconPickerDialog.ui | 67 -- gui/LabeledToolButton.cpp | 72 -- gui/LabeledToolButton.h | 22 - gui/LegacyModEditDialog.cpp | 393 --------- gui/LegacyModEditDialog.h | 78 -- gui/LegacyModEditDialog.ui | 321 -------- gui/MCModInfoFrame.cpp | 109 --- gui/MCModInfoFrame.h | 46 -- gui/MCModInfoFrame.ui | 68 -- gui/MainWindow.cpp | 976 +++++++++++++++++++++++ gui/MainWindow.h | 167 ++++ gui/MainWindow.ui | 474 +++++++++++ gui/ModEditDialogCommon.cpp | 41 - gui/ModEditDialogCommon.h | 7 - gui/ModListView.cpp | 36 - gui/ModListView.h | 13 - gui/OneSixModEditDialog.cpp | 317 -------- gui/OneSixModEditDialog.h | 67 -- gui/OneSixModEditDialog.ui | 319 -------- gui/Platform.h | 32 + gui/Platform_Other.cpp | 27 + gui/Platform_X11.cpp | 62 ++ gui/ProgressDialog.cpp | 110 --- gui/ProgressDialog.h | 62 -- gui/ProgressDialog.ui | 53 -- gui/aboutdialog.cpp | 24 - gui/aboutdialog.h | 22 - gui/aboutdialog.ui | 315 -------- gui/consolewindow.cpp | 120 --- gui/consolewindow.h | 63 -- gui/consolewindow.ui | 85 -- gui/dialogs/AboutDialog.cpp | 37 + gui/dialogs/AboutDialog.h | 35 + gui/dialogs/AboutDialog.ui | 316 ++++++++ gui/dialogs/CopyInstanceDialog.cpp | 84 ++ gui/dialogs/CopyInstanceDialog.h | 50 ++ gui/dialogs/CopyInstanceDialog.ui | 134 ++++ gui/dialogs/CustomMessageBox.cpp | 34 + gui/dialogs/CustomMessageBox.h | 26 + gui/dialogs/EditNotesDialog.cpp | 42 + gui/dialogs/EditNotesDialog.h | 38 + gui/dialogs/EditNotesDialog.ui | 77 ++ gui/dialogs/IconPickerDialog.cpp | 156 ++++ gui/dialogs/IconPickerDialog.h | 48 ++ gui/dialogs/IconPickerDialog.ui | 67 ++ gui/dialogs/InstanceSettings.cpp | 180 +++++ gui/dialogs/InstanceSettings.h | 50 ++ gui/dialogs/InstanceSettings.ui | 422 ++++++++++ gui/dialogs/LegacyModEditDialog.cpp | 393 +++++++++ gui/dialogs/LegacyModEditDialog.h | 78 ++ gui/dialogs/LegacyModEditDialog.ui | 321 ++++++++ gui/dialogs/LoginDialog.cpp | 252 ++++++ gui/dialogs/LoginDialog.h | 61 ++ gui/dialogs/LoginDialog.ui | 186 +++++ gui/dialogs/LwjglSelectDialog.cpp | 72 ++ gui/dialogs/LwjglSelectDialog.h | 44 + gui/dialogs/LwjglSelectDialog.ui | 85 ++ gui/dialogs/ModEditDialogCommon.cpp | 57 ++ gui/dialogs/ModEditDialogCommon.h | 22 + gui/dialogs/NewInstanceDialog.cpp | 125 +++ gui/dialogs/NewInstanceDialog.h | 55 ++ gui/dialogs/NewInstanceDialog.ui | 179 +++++ gui/dialogs/OneSixModEditDialog.cpp | 322 ++++++++ gui/dialogs/OneSixModEditDialog.h | 67 ++ gui/dialogs/OneSixModEditDialog.ui | 319 ++++++++ gui/dialogs/ProgressDialog.cpp | 107 +++ gui/dialogs/ProgressDialog.h | 60 ++ gui/dialogs/ProgressDialog.ui | 53 ++ gui/dialogs/SettingsDialog.cpp | 260 ++++++ gui/dialogs/SettingsDialog.h | 63 ++ gui/dialogs/SettingsDialog.ui | 569 +++++++++++++ gui/dialogs/VersionSelectDialog.cpp | 111 +++ gui/dialogs/VersionSelectDialog.h | 61 ++ gui/dialogs/VersionSelectDialog.ui | 103 +++ gui/instancedelegate.cpp | 231 ------ gui/instancedelegate.h | 12 - gui/instancesettings.cpp | 189 ----- gui/instancesettings.h | 35 - gui/instancesettings.ui | 422 ---------- gui/logindialog.cpp | 248 ------ gui/logindialog.h | 57 -- gui/logindialog.ui | 185 ----- gui/lwjglselectdialog.cpp | 72 -- gui/lwjglselectdialog.h | 46 -- gui/lwjglselectdialog.ui | 85 -- gui/mainwindow.cpp | 974 ---------------------- gui/mainwindow.h | 170 ---- gui/mainwindow.ui | 474 ----------- gui/newinstancedialog.cpp | 125 --- gui/newinstancedialog.h | 55 -- gui/newinstancedialog.ui | 179 ----- gui/newmodeditwindow.ui | 159 ---- gui/platform.h | 35 - gui/platform_other.cpp | 27 - gui/platform_x11.cpp | 62 -- gui/settingsdialog.cpp | 256 ------ gui/settingsdialog.h | 64 -- gui/settingsdialog.ui | 569 ------------- gui/versionselectdialog.cpp | 110 --- gui/versionselectdialog.h | 61 -- gui/versionselectdialog.ui | 103 --- gui/widgets/InstanceDelegate.cpp | 246 ++++++ gui/widgets/InstanceDelegate.h | 27 + gui/widgets/LabeledToolButton.cpp | 86 ++ gui/widgets/LabeledToolButton.h | 37 + gui/widgets/MCModInfoFrame.cpp | 111 +++ gui/widgets/MCModInfoFrame.h | 46 ++ gui/widgets/MCModInfoFrame.ui | 68 ++ gui/widgets/ModListView.cpp | 51 ++ gui/widgets/ModListView.h | 27 + logic/BaseInstance.cpp | 140 ++-- logic/BaseInstance_p.h | 17 +- logic/BaseUpdate.cpp | 17 +- logic/BaseUpdate.h | 13 +- logic/BaseVersion.h | 9 +- logic/CMakeLists.txt | 24 - logic/EnabledItemFilter.cpp | 27 +- logic/EnabledItemFilter.h | 18 +- logic/ForgeInstaller.cpp | 15 + logic/ForgeInstaller.h | 19 +- logic/InstanceFactory.cpp | 31 +- logic/InstanceLauncher.cpp | 77 +- logic/InstanceLauncher.h | 26 +- logic/JavaUtils.cpp | 72 +- logic/JavaUtils.h | 8 +- logic/LegacyForge.cpp | 37 +- logic/LegacyForge.h | 32 +- logic/LegacyInstance.cpp | 39 +- logic/LegacyInstance.h | 18 +- logic/LegacyInstance_p.h | 24 +- logic/LegacyUpdate.cpp | 17 +- logic/LegacyUpdate.h | 37 +- logic/MinecraftProcess.h | 43 +- logic/MinecraftVersion.h | 30 +- logic/Mod.cpp | 38 +- logic/Mod.h | 29 +- logic/ModList.cpp | 31 +- logic/ModList.h | 111 +-- logic/NagUtils.cpp | 27 +- logic/NostalgiaInstance.cpp | 26 +- logic/NostalgiaInstance.h | 19 +- logic/OneSixAssets.cpp | 22 +- logic/OneSixAssets.h | 22 +- logic/OneSixInstance.cpp | 19 +- logic/OneSixInstance.h | 19 +- logic/OneSixInstance_p.h | 27 +- logic/OneSixLibrary.cpp | 19 +- logic/OneSixLibrary.h | 36 +- logic/OneSixRule.cpp | 18 +- logic/OneSixRule.h | 59 +- logic/OneSixUpdate.cpp | 1 + logic/OneSixUpdate.h | 21 +- logic/OneSixVersion.cpp | 31 +- logic/OneSixVersion.h | 17 +- logic/OpSys.cpp | 35 +- logic/OpSys.h | 27 +- logic/lists/BaseVersionList.cpp | 36 +- logic/lists/BaseVersionList.h | 46 +- logic/lists/ForgeVersionList.cpp | 2 +- logic/lists/ForgeVersionList.h | 3 +- logic/lists/IconList.cpp | 146 ++-- logic/lists/IconList.h | 48 +- logic/lists/InstanceList.cpp | 4 +- logic/lists/InstanceList.h | 2 +- logic/lists/JavaVersionList.cpp | 7 +- logic/lists/JavaVersionList.h | 6 +- logic/lists/LwjglVersionList.cpp | 2 +- logic/lists/LwjglVersionList.h | 113 ++- logic/lists/MinecraftVersionList.cpp | 4 +- logic/lists/MinecraftVersionList.h | 31 +- logic/net/ByteArrayDownload.cpp | 17 +- logic/net/ByteArrayDownload.h | 15 + logic/net/CacheDownload.cpp | 28 +- logic/net/CacheDownload.h | 15 + logic/net/FileDownload.cpp | 74 +- logic/net/FileDownload.h | 15 + logic/net/ForgeXzDownload.cpp | 44 +- logic/net/ForgeXzDownload.h | 15 + logic/net/HttpMetaCache.cpp | 129 +-- logic/net/HttpMetaCache.h | 15 + logic/net/LoginTask.cpp | 29 +- logic/net/LoginTask.h | 6 +- logic/net/NetAction.h | 21 +- logic/net/NetJob.cpp | 21 +- logic/net/NetJob.h | 20 +- logic/net/S3ListBucket.cpp | 19 +- logic/net/S3ListBucket.h | 15 + logic/tasks/ProgressProvider.h | 25 +- logic/tasks/Task.cpp | 12 +- logic/tasks/Task.h | 22 +- 257 files changed, 12025 insertions(+), 11300 deletions(-) delete mode 100644 depends/util/include/apputils.h delete mode 100644 depends/util/include/siglist.h delete mode 100644 depends/util/include/siglist_impl.h delete mode 100644 depends/util/src/osutils.cpp create mode 100644 gui/ConsoleWindow.cpp create mode 100644 gui/ConsoleWindow.h create mode 100644 gui/ConsoleWindow.ui delete mode 100644 gui/CopyInstanceDialog.cpp delete mode 100644 gui/CopyInstanceDialog.h delete mode 100644 gui/CopyInstanceDialog.ui delete mode 100644 gui/CustomMessageBox.cpp delete mode 100644 gui/CustomMessageBox.h delete mode 100644 gui/EditNotesDialog.cpp delete mode 100644 gui/EditNotesDialog.h delete mode 100644 gui/EditNotesDialog.ui delete mode 100644 gui/IconPickerDialog.cpp delete mode 100644 gui/IconPickerDialog.h delete mode 100644 gui/IconPickerDialog.ui delete mode 100644 gui/LabeledToolButton.cpp delete mode 100644 gui/LabeledToolButton.h delete mode 100644 gui/LegacyModEditDialog.cpp delete mode 100644 gui/LegacyModEditDialog.h delete mode 100644 gui/LegacyModEditDialog.ui delete mode 100644 gui/MCModInfoFrame.cpp delete mode 100644 gui/MCModInfoFrame.h delete mode 100644 gui/MCModInfoFrame.ui create mode 100644 gui/MainWindow.cpp create mode 100644 gui/MainWindow.h create mode 100644 gui/MainWindow.ui delete mode 100644 gui/ModEditDialogCommon.cpp delete mode 100644 gui/ModEditDialogCommon.h delete mode 100644 gui/ModListView.cpp delete mode 100644 gui/ModListView.h delete mode 100644 gui/OneSixModEditDialog.cpp delete mode 100644 gui/OneSixModEditDialog.h delete mode 100644 gui/OneSixModEditDialog.ui create mode 100644 gui/Platform.h create mode 100644 gui/Platform_Other.cpp create mode 100644 gui/Platform_X11.cpp delete mode 100644 gui/ProgressDialog.cpp delete mode 100644 gui/ProgressDialog.h delete mode 100644 gui/ProgressDialog.ui delete mode 100644 gui/aboutdialog.cpp delete mode 100644 gui/aboutdialog.h delete mode 100644 gui/aboutdialog.ui delete mode 100644 gui/consolewindow.cpp delete mode 100644 gui/consolewindow.h delete mode 100644 gui/consolewindow.ui create mode 100644 gui/dialogs/AboutDialog.cpp create mode 100644 gui/dialogs/AboutDialog.h create mode 100644 gui/dialogs/AboutDialog.ui create mode 100644 gui/dialogs/CopyInstanceDialog.cpp create mode 100644 gui/dialogs/CopyInstanceDialog.h create mode 100644 gui/dialogs/CopyInstanceDialog.ui create mode 100644 gui/dialogs/CustomMessageBox.cpp create mode 100644 gui/dialogs/CustomMessageBox.h create mode 100644 gui/dialogs/EditNotesDialog.cpp create mode 100644 gui/dialogs/EditNotesDialog.h create mode 100644 gui/dialogs/EditNotesDialog.ui create mode 100644 gui/dialogs/IconPickerDialog.cpp create mode 100644 gui/dialogs/IconPickerDialog.h create mode 100644 gui/dialogs/IconPickerDialog.ui create mode 100644 gui/dialogs/InstanceSettings.cpp create mode 100644 gui/dialogs/InstanceSettings.h create mode 100644 gui/dialogs/InstanceSettings.ui create mode 100644 gui/dialogs/LegacyModEditDialog.cpp create mode 100644 gui/dialogs/LegacyModEditDialog.h create mode 100644 gui/dialogs/LegacyModEditDialog.ui create mode 100644 gui/dialogs/LoginDialog.cpp create mode 100644 gui/dialogs/LoginDialog.h create mode 100644 gui/dialogs/LoginDialog.ui create mode 100644 gui/dialogs/LwjglSelectDialog.cpp create mode 100644 gui/dialogs/LwjglSelectDialog.h create mode 100644 gui/dialogs/LwjglSelectDialog.ui create mode 100644 gui/dialogs/ModEditDialogCommon.cpp create mode 100644 gui/dialogs/ModEditDialogCommon.h create mode 100644 gui/dialogs/NewInstanceDialog.cpp create mode 100644 gui/dialogs/NewInstanceDialog.h create mode 100644 gui/dialogs/NewInstanceDialog.ui create mode 100644 gui/dialogs/OneSixModEditDialog.cpp create mode 100644 gui/dialogs/OneSixModEditDialog.h create mode 100644 gui/dialogs/OneSixModEditDialog.ui create mode 100644 gui/dialogs/ProgressDialog.cpp create mode 100644 gui/dialogs/ProgressDialog.h create mode 100644 gui/dialogs/ProgressDialog.ui create mode 100644 gui/dialogs/SettingsDialog.cpp create mode 100644 gui/dialogs/SettingsDialog.h create mode 100644 gui/dialogs/SettingsDialog.ui create mode 100644 gui/dialogs/VersionSelectDialog.cpp create mode 100644 gui/dialogs/VersionSelectDialog.h create mode 100644 gui/dialogs/VersionSelectDialog.ui delete mode 100644 gui/instancedelegate.cpp delete mode 100644 gui/instancedelegate.h delete mode 100644 gui/instancesettings.cpp delete mode 100644 gui/instancesettings.h delete mode 100644 gui/instancesettings.ui delete mode 100644 gui/logindialog.cpp delete mode 100644 gui/logindialog.h delete mode 100644 gui/logindialog.ui delete mode 100644 gui/lwjglselectdialog.cpp delete mode 100644 gui/lwjglselectdialog.h delete mode 100644 gui/lwjglselectdialog.ui delete mode 100644 gui/mainwindow.cpp delete mode 100644 gui/mainwindow.h delete mode 100644 gui/mainwindow.ui delete mode 100644 gui/newinstancedialog.cpp delete mode 100644 gui/newinstancedialog.h delete mode 100644 gui/newinstancedialog.ui delete mode 100644 gui/newmodeditwindow.ui delete mode 100644 gui/platform.h delete mode 100644 gui/platform_other.cpp delete mode 100644 gui/platform_x11.cpp delete mode 100644 gui/settingsdialog.cpp delete mode 100644 gui/settingsdialog.h delete mode 100644 gui/settingsdialog.ui delete mode 100644 gui/versionselectdialog.cpp delete mode 100644 gui/versionselectdialog.h delete mode 100644 gui/versionselectdialog.ui create mode 100644 gui/widgets/InstanceDelegate.cpp create mode 100644 gui/widgets/InstanceDelegate.h create mode 100644 gui/widgets/LabeledToolButton.cpp create mode 100644 gui/widgets/LabeledToolButton.h create mode 100644 gui/widgets/MCModInfoFrame.cpp create mode 100644 gui/widgets/MCModInfoFrame.h create mode 100644 gui/widgets/MCModInfoFrame.ui create mode 100644 gui/widgets/ModListView.cpp create mode 100644 gui/widgets/ModListView.h delete mode 100644 logic/CMakeLists.txt diff --git a/CMakeLists.txt b/CMakeLists.txt index cb24499f..e150c459 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -178,49 +178,53 @@ logger/QsLog.h logger/QsLogDest.cpp logger/QsLogDest.h -# GUI -gui/mainwindow.h -gui/mainwindow.cpp -gui/settingsdialog.h -gui/settingsdialog.cpp -gui/CopyInstanceDialog.h -gui/CopyInstanceDialog.cpp -gui/newinstancedialog.h -gui/newinstancedialog.cpp -gui/logindialog.h -gui/logindialog.cpp -gui/ProgressDialog.h -gui/ProgressDialog.cpp -gui/aboutdialog.h -gui/aboutdialog.cpp -gui/consolewindow.h -gui/consolewindow.cpp -gui/instancedelegate.h -gui/instancedelegate.cpp -gui/versionselectdialog.h -gui/versionselectdialog.cpp -gui/lwjglselectdialog.h -gui/lwjglselectdialog.cpp -gui/instancesettings.h -gui/instancesettings.cpp -gui/IconPickerDialog.h -gui/IconPickerDialog.cpp -gui/LegacyModEditDialog.h -gui/LegacyModEditDialog.cpp -gui/OneSixModEditDialog.h -gui/OneSixModEditDialog.cpp -gui/ModEditDialogCommon.h -gui/ModEditDialogCommon.cpp -gui/ModListView.h -gui/ModListView.cpp -gui/LabeledToolButton.h -gui/LabeledToolButton.cpp -gui/EditNotesDialog.h -gui/EditNotesDialog.cpp -gui/MCModInfoFrame.h -gui/MCModInfoFrame.cpp -gui/CustomMessageBox.h -gui/CustomMessageBox.cpp +# GUI - windows +gui/MainWindow.h +gui/MainWindow.cpp +gui/ConsoleWindow.h +gui/ConsoleWindow.cpp + +# GUI - dialogs +gui/dialogs/SettingsDialog.h +gui/dialogs/SettingsDialog.cpp +gui/dialogs/CopyInstanceDialog.h +gui/dialogs/CopyInstanceDialog.cpp +gui/dialogs/dialogs/ +gui/dialogs/NewInstanceDialog.cpp +gui/dialogs/LoginDialog.h +gui/dialogs/LoginDialog.cpp +gui/dialogs/ProgressDialog.h +gui/dialogs/ProgressDialog.cpp +gui/dialogs/AboutDialog.h +gui/dialogs/AboutDialog.cpp +gui/dialogs/VersionSelectDialog.h +gui/dialogs/VersionSelectDialog.cpp +gui/dialogs/LwjglSelectDialog.h +gui/dialogs/LwjglSelectDialog.cpp +gui/dialogs/InstanceSettings.h +gui/dialogs/InstanceSettings.cpp +gui/dialogs/IconPickerDialog.h +gui/dialogs/IconPickerDialog.cpp +gui/dialogs/LegacyModEditDialog.h +gui/dialogs/LegacyModEditDialog.cpp +gui/dialogs/OneSixModEditDialog.h +gui/dialogs/OneSixModEditDialog.cpp +gui/dialogs/ModEditDialogCommon.h +gui/dialogs/ModEditDialogCommon.cpp +gui/dialogs/EditNotesDialog.h +gui/dialogs/EditNotesDialog.cpp +gui/dialogs/CustomMessageBox.h +gui/dialogs/CustomMessageBox.cpp + +# GUI - widgets +gui/widgets/InstanceDelegate.h +gui/widgets/InstanceDelegate.cpp +gui/widgets/ModListView.h +gui/widgets/ModListView.cpp +gui/widgets/LabeledToolButton.h +gui/widgets/LabeledToolButton.cpp +gui/widgets/MCModInfoFrame.h +gui/widgets/MCModInfoFrame.cpp # Base classes and infrastructure logic/BaseVersion.h @@ -332,24 +336,28 @@ logic/NagUtils.cpp ######## UIs ######## SET(MULTIMC_UIS -gui/mainwindow.ui -gui/settingsdialog.ui -gui/CopyInstanceDialog.ui -gui/newinstancedialog.ui -gui/logindialog.ui -gui/aboutdialog.ui -gui/consolewindow.ui -gui/versionselectdialog.ui -gui/lwjglselectdialog.ui -gui/instancesettings.ui - -gui/ProgressDialog.ui -gui/IconPickerDialog.ui -gui/LegacyModEditDialog.ui -gui/OneSixModEditDialog.ui -gui/EditNotesDialog.ui - -gui/MCModInfoFrame.ui + +# Windows +gui/MainWindow.ui +gui/ConsoleWindow.ui + +# Dialogs +gui/dialogs/SettingsDialog.ui +gui/dialogs/CopyInstanceDialog.ui +gui/dialogs/NewInstanceDialog.ui +gui/dialogs/LoginDialog.ui +gui/dialogs/AboutDialog.ui +gui/dialogs/VersionSelectDialog.ui +gui/dialogs/LwjglSelectDialog.ui +gui/dialogs/InstanceSettings.ui +gui/dialogs/ProgressDialog.ui +gui/dialogs/IconPickerDialog.ui +gui/dialogs/LegacyModEditDialog.ui +gui/dialogs/OneSixModEditDialog.ui +gui/dialogs/EditNotesDialog.ui + +# Widgets/other +gui/widgets/MCModInfoFrame.ui ) set (FILES_TO_TRANSLATE ${FILES_TO_TRANSLATE} ${MULTIMC_SOURCES} ${MULTIMC_UIS}) @@ -364,9 +372,9 @@ ENDIF() IF(UNIX AND NOT APPLE) SET(MultiMC_QT_ADDITIONAL_MODULES ${MultiMC_QT_ADDITIONAL_MODULES} X11Extras) SET(MultiMC_LINK_ADDITIONAL_LIBS ${MultiMC_LINK_ADDITIONAL_LIBS} xcb) - LIST(APPEND MULTIMC_SOURCES gui/platform_x11.cpp) + LIST(APPEND MULTIMC_SOURCES gui/Platform_X11.cpp) ELSE() - LIST(APPEND MULTIMC_SOURCES gui/platform_other.cpp) + LIST(APPEND MULTIMC_SOURCES gui/Platform_Other.cpp) ENDIF() diff --git a/MultiMC.cpp b/MultiMC.cpp index e04904b4..1c70fb54 100644 --- a/MultiMC.cpp +++ b/MultiMC.cpp @@ -7,8 +7,8 @@ #include #include -#include "gui/mainwindow.h" -#include "gui/versionselectdialog.h" +#include "gui/MainWindow.h" +#include "gui/dialogs/VersionSelectDialog.h" #include "logic/lists/InstanceList.h" #include "logic/lists/IconList.h" #include "logic/lists/LwjglVersionList.h" @@ -24,7 +24,7 @@ #include "cmdutils.h" #include #include -#include +#include "logger/QsLog.h" #include #include "config.h" diff --git a/depends/classparser/include/classparser_config.h b/depends/classparser/include/classparser_config.h index fe6a2ab9..a043824a 100644 --- a/depends/classparser/include/classparser_config.h +++ b/depends/classparser/include/classparser_config.h @@ -16,8 +16,7 @@ #include #ifdef CLASSPARSER_LIBRARY -# define CLASSPARSER_EXPORT Q_DECL_EXPORT +#define CLASSPARSER_EXPORT Q_DECL_EXPORT #else -# define CLASSPARSER_EXPORT Q_DECL_IMPORT +#define CLASSPARSER_EXPORT Q_DECL_IMPORT #endif - diff --git a/depends/classparser/include/javautils.h b/depends/classparser/include/javautils.h index 63e5ec26..90042261 100644 --- a/depends/classparser/include/javautils.h +++ b/depends/classparser/include/javautils.h @@ -22,8 +22,8 @@ namespace javautils { - /** - * @brief Get the version from a minecraft.jar by parsing its class files. Expensive! - */ - QString GetMinecraftJarVersion(QString jar); +/** + * @brief Get the version from a minecraft.jar by parsing its class files. Expensive! + */ +QString GetMinecraftJarVersion(QString jar); } diff --git a/depends/classparser/src/annotations.cpp b/depends/classparser/src/annotations.cpp index fc0c98fa..d1a7c046 100644 --- a/depends/classparser/src/annotations.cpp +++ b/depends/classparser/src/annotations.cpp @@ -4,80 +4,82 @@ namespace java { - std::string annotation::toString() +std::string annotation::toString() +{ + std::ostringstream ss; + ss << "Annotation type : " << type_index << " - " << pool[type_index].str_data << std::endl; + ss << "Contains " << name_val_pairs.size() << " pairs:" << std::endl; + for (unsigned i = 0; i < name_val_pairs.size(); i++) { - std::ostringstream ss; - ss << "Annotation type : " << type_index << " - " << pool[type_index].str_data << std::endl; - ss << "Contains " << name_val_pairs.size() << " pairs:" << std::endl; - for(unsigned i = 0; i < name_val_pairs.size(); i++) - { - std::pair &val = name_val_pairs[i]; - auto name_idx = val.first; - ss << pool[name_idx].str_data << "(" << name_idx << ")" << " = " << val.second->toString() << std::endl; - } - return ss.str(); + std::pair &val = name_val_pairs[i]; + auto name_idx = val.first; + ss << pool[name_idx].str_data << "(" << name_idx << ")" + << " = " << val.second->toString() << std::endl; } + return ss.str(); +} + +annotation *annotation::read(util::membuffer &input, constant_pool &pool) +{ + uint16_t type_index = 0; + input.read_be(type_index); + annotation *ann = new annotation(type_index, pool); - annotation * annotation::read (util::membuffer& input, constant_pool& pool) + uint16_t num_pairs = 0; + input.read_be(num_pairs); + while (num_pairs) { - uint16_t type_index = 0; - input.read_be(type_index); - annotation * ann = new annotation(type_index,pool); - - uint16_t num_pairs = 0; - input.read_be(num_pairs); - while(num_pairs) - { - uint16_t name_idx = 0; - // read name index - input.read_be(name_idx); - auto elem = element_value::readElementValue(input,pool); - // read value - ann->add_pair(name_idx, elem); - num_pairs --; - } - return ann; + uint16_t name_idx = 0; + // read name index + input.read_be(name_idx); + auto elem = element_value::readElementValue(input, pool); + // read value + ann->add_pair(name_idx, elem); + num_pairs--; } - - element_value* element_value::readElementValue ( util::membuffer& input, java::constant_pool& pool ) + return ann; +} + +element_value *element_value::readElementValue(util::membuffer &input, + java::constant_pool &pool) +{ + element_value_type type = INVALID; + input.read(type); + uint16_t index = 0; + uint16_t index2 = 0; + std::vector vals; + switch (type) { - element_value_type type = INVALID; - input.read(type); - uint16_t index = 0; - uint16_t index2 = 0; - std::vector vals; - switch (type) + case PRIMITIVE_BYTE: + case PRIMITIVE_CHAR: + case PRIMITIVE_DOUBLE: + case PRIMITIVE_FLOAT: + case PRIMITIVE_INT: + case PRIMITIVE_LONG: + case PRIMITIVE_SHORT: + case PRIMITIVE_BOOLEAN: + case STRING: + input.read_be(index); + return new element_value_simple(type, index, pool); + case ENUM_CONSTANT: + input.read_be(index); + input.read_be(index2); + return new element_value_enum(type, index, index2, pool); + case CLASS: // Class + input.read_be(index); + return new element_value_class(type, index, pool); + case ANNOTATION: // Annotation + // FIXME: runtime visibility info needs to be passed from parent + return new element_value_annotation(ANNOTATION, annotation::read(input, pool), pool); + case ARRAY: // Array + input.read_be(index); + for (int i = 0; i < index; i++) { - case PRIMITIVE_BYTE: - case PRIMITIVE_CHAR: - case PRIMITIVE_DOUBLE: - case PRIMITIVE_FLOAT: - case PRIMITIVE_INT: - case PRIMITIVE_LONG: - case PRIMITIVE_SHORT: - case PRIMITIVE_BOOLEAN: - case STRING: - input.read_be(index); - return new element_value_simple(type, index, pool); - case ENUM_CONSTANT: - input.read_be(index); - input.read_be(index2); - return new element_value_enum(type, index, index2, pool); - case CLASS: // Class - input.read_be(index); - return new element_value_class(type, index, pool); - case ANNOTATION: // Annotation - // FIXME: runtime visibility info needs to be passed from parent - return new element_value_annotation(ANNOTATION, annotation::read(input, pool), pool); - case ARRAY: // Array - input.read_be(index); - for (int i = 0; i < index; i++) - { - vals.push_back(element_value::readElementValue(input, pool)); - } - return new element_value_array(ARRAY, vals, pool); - default: - throw new java::classfile_exception(); + vals.push_back(element_value::readElementValue(input, pool)); } + return new element_value_array(ARRAY, vals, pool); + default: + throw new java::classfile_exception(); } +} } \ No newline at end of file diff --git a/depends/classparser/src/annotations.h b/depends/classparser/src/annotations.h index b115dc0b..aa25d241 100644 --- a/depends/classparser/src/annotations.h +++ b/depends/classparser/src/annotations.h @@ -5,248 +5,273 @@ namespace java { - enum element_value_type : uint8_t - { - INVALID = 0, - STRING = 's', - ENUM_CONSTANT = 'e', - CLASS = 'c', - ANNOTATION = '@', - ARRAY = '[', // one array dimension - PRIMITIVE_INT = 'I', // integer - PRIMITIVE_BYTE = 'B', // signed byte - PRIMITIVE_CHAR = 'C', // Unicode character code point in the Basic Multilingual Plane, encoded with UTF-16 - PRIMITIVE_DOUBLE = 'D', // double-precision floating-point value - PRIMITIVE_FLOAT = 'F', // single-precision floating-point value - PRIMITIVE_LONG = 'J', // long integer - PRIMITIVE_SHORT = 'S', // signed short - PRIMITIVE_BOOLEAN = 'Z' // true or false - }; +enum element_value_type : uint8_t +{ + INVALID = 0, + STRING = 's', + ENUM_CONSTANT = 'e', + CLASS = 'c', + ANNOTATION = '@', + ARRAY = '[', // one array dimension + PRIMITIVE_INT = 'I', // integer + PRIMITIVE_BYTE = 'B', // signed byte + PRIMITIVE_CHAR = 'C', // Unicode character code point in the Basic Multilingual Plane, + // encoded with UTF-16 + PRIMITIVE_DOUBLE = 'D', // double-precision floating-point value + PRIMITIVE_FLOAT = 'F', // single-precision floating-point value + PRIMITIVE_LONG = 'J', // long integer + PRIMITIVE_SHORT = 'S', // signed short + PRIMITIVE_BOOLEAN = 'Z' // true or false +}; +/** + * The element_value structure is a discriminated union representing the value of an + *element-value pair. + * It is used to represent element values in all attributes that describe annotations + * - RuntimeVisibleAnnotations + * - RuntimeInvisibleAnnotations + * - RuntimeVisibleParameterAnnotations + * - RuntimeInvisibleParameterAnnotations). + * + * The element_value structure has the following format: + */ +class element_value +{ +protected: + element_value_type type; + constant_pool &pool; + +public: + element_value(element_value_type type, constant_pool &pool) : type(type), pool(pool) {}; + + element_value_type getElementValueType() + { + return type; + } + + virtual std::string toString() = 0; + + static element_value *readElementValue(util::membuffer &input, constant_pool &pool); +}; + +/** + * Each value of the annotations table represents a single runtime-visible annotation on a + * program element. + * The annotation structure has the following format: + */ +class annotation +{ +public: + typedef std::vector> value_list; + +protected: /** - * The element_value structure is a discriminated union representing the value of an element-value pair. - * It is used to represent element values in all attributes that describe annotations - * - RuntimeVisibleAnnotations - * - RuntimeInvisibleAnnotations - * - RuntimeVisibleParameterAnnotations - * - RuntimeInvisibleParameterAnnotations). + * The value of the type_index item must be a valid index into the constant_pool table. + * The constant_pool entry at that index must be a CONSTANT_Utf8_info (§4.4.7) structure + * representing a field descriptor representing the annotation type corresponding + * to the annotation represented by this annotation structure. + */ + uint16_t type_index; + /** + * map between element_name_index and value. * - * The element_value structure has the following format: + * The value of the element_name_index item must be a valid index into the constant_pool + *table. + * The constant_pool entry at that index must be a CONSTANT_Utf8_info (§4.4.7) structure + *representing + * a valid field descriptor (§4.3.2) that denotes the name of the annotation type element + *represented + * by this element_value_pairs entry. */ - class element_value - { - protected: - element_value_type type; - constant_pool & pool; - - public: - element_value(element_value_type type, constant_pool & pool): type(type), pool(pool) {}; + value_list name_val_pairs; + /** + * Reference to the parent constant pool + */ + constant_pool &pool; - element_value_type getElementValueType() +public: + annotation(uint16_t type_index, constant_pool &pool) + : type_index(type_index), pool(pool) {}; + ~annotation() + { + for (unsigned i = 0; i < name_val_pairs.size(); i++) { - return type; + delete name_val_pairs[i].second; } - - virtual std::string toString() = 0; + } + void add_pair(uint16_t key, element_value *value) + { + name_val_pairs.push_back(std::make_pair(key, value)); + } + ; + value_list::const_iterator begin() + { + return name_val_pairs.cbegin(); + } + value_list::const_iterator end() + { + return name_val_pairs.cend(); + } + std::string toString(); + static annotation *read(util::membuffer &input, constant_pool &pool); +}; +typedef std::vector annotation_table; + +/// type for simple value annotation elements +class element_value_simple : public element_value +{ +protected: + /// index of the constant in the constant pool + uint16_t index; - static element_value * readElementValue(util::membuffer & input, constant_pool & pool); - }; - +public: + element_value_simple(element_value_type type, uint16_t index, constant_pool &pool) + : element_value(type, pool), index(index) { + // TODO: verify consistency + }; + uint16_t getIndex() + { + return index; + } + virtual std::string toString() + { + return pool[index].toString(); + } + ; +}; +/// The enum_const_value item is used if the tag item is 'e'. +class element_value_enum : public element_value +{ +protected: /** - * Each value of the annotations table represents a single runtime-visible annotation on a program element. - * The annotation structure has the following format: + * The value of the type_name_index item must be a valid index into the constant_pool table. + * The constant_pool entry at that index must be a CONSTANT_Utf8_info (§4.4.7) structure + * representing a valid field descriptor (§4.3.2) that denotes the internal form of the + * binary + * name (§4.2.1) of the type of the enum constant represented by this element_value + * structure. */ - class annotation - { - public: - typedef std::vector< std::pair > value_list; - protected: - /** - * The value of the type_index item must be a valid index into the constant_pool table. - * The constant_pool entry at that index must be a CONSTANT_Utf8_info (§4.4.7) structure - * representing a field descriptor representing the annotation type corresponding - * to the annotation represented by this annotation structure. - */ - uint16_t type_index; - /** - * map between element_name_index and value. - * - * The value of the element_name_index item must be a valid index into the constant_pool table. - * The constant_pool entry at that index must be a CONSTANT_Utf8_info (§4.4.7) structure representing - * a valid field descriptor (§4.3.2) that denotes the name of the annotation type element represented - * by this element_value_pairs entry. - */ - value_list name_val_pairs; - /** - * Reference to the parent constant pool - */ - constant_pool & pool; - public: - annotation(uint16_t type_index, constant_pool& pool):type_index(type_index), pool(pool) {}; - ~annotation() - { - for(unsigned i = 0 ; i < name_val_pairs.size(); i++) - { - delete name_val_pairs[i].second; - } - } - void add_pair(uint16_t key, element_value * value) - { - name_val_pairs.push_back(std::make_pair(key, value)); - }; - value_list::const_iterator begin() - { - return name_val_pairs.cbegin(); - } - value_list::const_iterator end() - { - return name_val_pairs.cend(); - } - std::string toString(); - static annotation * read(util::membuffer & input, constant_pool & pool); - }; - typedef std::vector annotation_table; - - - /// type for simple value annotation elements - class element_value_simple : public element_value - { - protected: - /// index of the constant in the constant pool - uint16_t index; - public: - element_value_simple(element_value_type type, uint16_t index , constant_pool& pool): - element_value(type, pool), index(index) - { - // TODO: verify consistency - }; - uint16_t getIndex() - { - return index; - } - virtual std::string toString() - { - return pool[index].toString(); - }; - }; - /// The enum_const_value item is used if the tag item is 'e'. - class element_value_enum : public element_value - { - protected: - /** - * The value of the type_name_index item must be a valid index into the constant_pool table. - * The constant_pool entry at that index must be a CONSTANT_Utf8_info (§4.4.7) structure - * representing a valid field descriptor (§4.3.2) that denotes the internal form of the binary - * name (§4.2.1) of the type of the enum constant represented by this element_value structure. - */ - uint16_t typeIndex; - /** - * The value of the const_name_index item must be a valid index into the constant_pool table. - * The constant_pool entry at that index must be a CONSTANT_Utf8_info (§4.4.7) structure - * representing the simple name of the enum constant represented by this element_value structure. - */ - uint16_t valueIndex; - public: - element_value_enum(element_value_type type, uint16_t typeIndex, uint16_t valueIndex, constant_pool& pool): - element_value(type, pool), typeIndex(typeIndex), valueIndex(valueIndex) - { - // TODO: verify consistency - } - uint16_t getValueIndex() - { - return valueIndex; - } - uint16_t getTypeIndex() - { - return typeIndex; - } - virtual std::string toString() - { - return "enum value"; - }; - }; - - class element_value_class : public element_value - { - protected: - /** - * The class_info_index item must be a valid index into the constant_pool table. - * The constant_pool entry at that index must be a CONSTANT_Utf8_info (§4.4.7) structure - * representing the return descriptor (§4.3.3) of the type that is reified by the class - * represented by this element_value structure. - * - * For example, 'V' for Void.class, 'Ljava/lang/Object;' for Object, etc. - * - * Or in plain english, you can store type information in annotations. Yay. - */ - uint16_t classIndex; - public: - element_value_class(element_value_type type, uint16_t classIndex, constant_pool& pool): - element_value(type, pool), classIndex(classIndex) - { - // TODO: verify consistency - } - uint16_t getIndex() - { - return classIndex; - } - virtual std::string toString() - { - return "class"; - }; - }; - - /// nested annotations... yay - class element_value_annotation : public element_value - { - private: - annotation * nestedAnnotation; - public: - element_value_annotation(element_value_type type, annotation * nestedAnnotation, constant_pool& pool): - element_value(type, pool), nestedAnnotation(nestedAnnotation) - {}; - ~element_value_annotation() - { - if(nestedAnnotation) - { - delete nestedAnnotation; - nestedAnnotation = nullptr; - } - } - virtual std::string toString() - { - return "nested annotation"; - }; - }; - - /// and arrays! - class element_value_array : public element_value - { - public: - typedef std::vector elem_vec; - protected: - elem_vec values; - public: - element_value_array ( element_value_type type, std::vector & values, constant_pool& pool ): - element_value(type, pool), values(values) - {}; - ~element_value_array () - { - for(unsigned i = 0; i < values.size();i++) - { - delete values[i]; - } - }; - elem_vec::const_iterator begin() + uint16_t typeIndex; + /** + * The value of the const_name_index item must be a valid index into the constant_pool + * table. + * The constant_pool entry at that index must be a CONSTANT_Utf8_info (§4.4.7) structure + * representing the simple name of the enum constant represented by this element_value + * structure. + */ + uint16_t valueIndex; + +public: + element_value_enum(element_value_type type, uint16_t typeIndex, uint16_t valueIndex, + constant_pool &pool) + : element_value(type, pool), typeIndex(typeIndex), valueIndex(valueIndex) + { + // TODO: verify consistency + } + uint16_t getValueIndex() + { + return valueIndex; + } + uint16_t getTypeIndex() + { + return typeIndex; + } + virtual std::string toString() + { + return "enum value"; + } + ; +}; + +class element_value_class : public element_value +{ +protected: + /** + * The class_info_index item must be a valid index into the constant_pool table. + * The constant_pool entry at that index must be a CONSTANT_Utf8_info (§4.4.7) structure + * representing the return descriptor (§4.3.3) of the type that is reified by the class + * represented by this element_value structure. + * + * For example, 'V' for Void.class, 'Ljava/lang/Object;' for Object, etc. + * + * Or in plain english, you can store type information in annotations. Yay. + */ + uint16_t classIndex; + +public: + element_value_class(element_value_type type, uint16_t classIndex, constant_pool &pool) + : element_value(type, pool), classIndex(classIndex) + { + // TODO: verify consistency + } + uint16_t getIndex() + { + return classIndex; + } + virtual std::string toString() + { + return "class"; + } + ; +}; + +/// nested annotations... yay +class element_value_annotation : public element_value +{ +private: + annotation *nestedAnnotation; + +public: + element_value_annotation(element_value_type type, annotation *nestedAnnotation, + constant_pool &pool) + : element_value(type, pool), nestedAnnotation(nestedAnnotation) {}; + ~element_value_annotation() + { + if (nestedAnnotation) { - return values.cbegin(); + delete nestedAnnotation; + nestedAnnotation = nullptr; } - elem_vec::const_iterator end() + } + virtual std::string toString() + { + return "nested annotation"; + } + ; +}; + +/// and arrays! +class element_value_array : public element_value +{ +public: + typedef std::vector elem_vec; + +protected: + elem_vec values; + +public: + element_value_array(element_value_type type, std::vector &values, + constant_pool &pool) + : element_value(type, pool), values(values) {}; + ~element_value_array() + { + for (unsigned i = 0; i < values.size(); i++) { - return values.cend(); + delete values[i]; } - virtual std::string toString() - { - return "array"; - }; - }; + } + ; + elem_vec::const_iterator begin() + { + return values.cbegin(); + } + elem_vec::const_iterator end() + { + return values.cend(); + } + virtual std::string toString() + { + return "array"; + } + ; +}; } \ No newline at end of file diff --git a/depends/classparser/src/classfile.h b/depends/classparser/src/classfile.h index 33207e99..a5e7ee50 100644 --- a/depends/classparser/src/classfile.h +++ b/depends/classparser/src/classfile.h @@ -5,149 +5,152 @@ #include namespace java { - /** - * Class representing a Java .class file - */ - class classfile : public util::membuffer +/** + * Class representing a Java .class file + */ +class classfile : public util::membuffer +{ +public: + classfile(char *data, std::size_t size) : membuffer(data, size) { - public: - classfile(char * data, std::size_t size) : membuffer(data, size) + valid = false; + is_synthetic = false; + read_be(magic); + if (magic != 0xCAFEBABE) + throw new classfile_exception(); + read_be(minor_version); + read_be(major_version); + constants.load(*this); + read_be(access_flags); + read_be(this_class); + read_be(super_class); + + // Interfaces + uint16_t iface_count = 0; + read_be(iface_count); + while (iface_count) { - valid = false; - is_synthetic = false; - read_be(magic); - if(magic != 0xCAFEBABE) - throw new classfile_exception(); - read_be(minor_version); - read_be(major_version); - constants.load(*this); - read_be(access_flags); - read_be(this_class); - read_be(super_class); - - // Interfaces - uint16_t iface_count = 0; - read_be(iface_count); - while (iface_count) - { - uint16_t iface; - read_be(iface); - interfaces.push_back(iface); - iface_count --; - } - - // Fields - // read fields (and attributes from inside fields) (and possible inner classes. yay for recursion!) - // for now though, we will ignore all attributes - /* - * field_info - * { - * u2 access_flags; - * u2 name_index; - * u2 descriptor_index; - * u2 attributes_count; - * attribute_info attributes[attributes_count]; - * } - */ - uint16_t field_count = 0; - read_be(field_count); - while (field_count) - { - // skip field stuff - skip(6); - // and skip field attributes - uint16_t attr_count = 0; - read_be(attr_count); - while(attr_count) - { - skip(2); - uint32_t attr_length = 0; - read_be(attr_length); - skip(attr_length); - attr_count --; - } - field_count --; - } + uint16_t iface; + read_be(iface); + interfaces.push_back(iface); + iface_count--; + } - // class methods - /* - * method_info - * { - * u2 access_flags; - * u2 name_index; - * u2 descriptor_index; - * u2 attributes_count; - * attribute_info attributes[attributes_count]; - * } - */ - uint16_t method_count = 0; - read_be(method_count); - while( method_count ) + // Fields + // read fields (and attributes from inside fields) (and possible inner classes. yay for + // recursion!) + // for now though, we will ignore all attributes + /* + * field_info + * { + * u2 access_flags; + * u2 name_index; + * u2 descriptor_index; + * u2 attributes_count; + * attribute_info attributes[attributes_count]; + * } + */ + uint16_t field_count = 0; + read_be(field_count); + while (field_count) + { + // skip field stuff + skip(6); + // and skip field attributes + uint16_t attr_count = 0; + read_be(attr_count); + while (attr_count) { - skip(6); - // and skip method attributes - uint16_t attr_count = 0; - read_be(attr_count); - while(attr_count) - { - skip(2); - uint32_t attr_length = 0; - read_be(attr_length); - skip(attr_length); - attr_count --; - } - method_count --; + skip(2); + uint32_t attr_length = 0; + read_be(attr_length); + skip(attr_length); + attr_count--; } + field_count--; + } - // class attributes - // there are many kinds of attributes. this is just the generic wrapper structure. - // type is decided by attribute name. extensions to the standard are *possible* - // class annotations are one kind of a attribute (one per class) - /* - * attribute_info - * { - * u2 attribute_name_index; - * u4 attribute_length; - * u1 info[attribute_length]; - * } - */ - uint16_t class_attr_count = 0; - read_be(class_attr_count); - while(class_attr_count) + // class methods + /* + * method_info + * { + * u2 access_flags; + * u2 name_index; + * u2 descriptor_index; + * u2 attributes_count; + * attribute_info attributes[attributes_count]; + * } + */ + uint16_t method_count = 0; + read_be(method_count); + while (method_count) + { + skip(6); + // and skip method attributes + uint16_t attr_count = 0; + read_be(attr_count); + while (attr_count) { - uint16_t name_idx = 0; - read_be(name_idx); + skip(2); uint32_t attr_length = 0; read_be(attr_length); - - auto name = constants[name_idx]; - if(name.str_data == "RuntimeVisibleAnnotations") + skip(attr_length); + attr_count--; + } + method_count--; + } + + // class attributes + // there are many kinds of attributes. this is just the generic wrapper structure. + // type is decided by attribute name. extensions to the standard are *possible* + // class annotations are one kind of a attribute (one per class) + /* + * attribute_info + * { + * u2 attribute_name_index; + * u4 attribute_length; + * u1 info[attribute_length]; + * } + */ + uint16_t class_attr_count = 0; + read_be(class_attr_count); + while (class_attr_count) + { + uint16_t name_idx = 0; + read_be(name_idx); + uint32_t attr_length = 0; + read_be(attr_length); + + auto name = constants[name_idx]; + if (name.str_data == "RuntimeVisibleAnnotations") + { + uint16_t num_annotations = 0; + read_be(num_annotations); + while (num_annotations) { - uint16_t num_annotations = 0; - read_be(num_annotations); - while (num_annotations) - { - visible_class_annotations.push_back(annotation::read(*this, constants)); - num_annotations --; - } + visible_class_annotations.push_back(annotation::read(*this, constants)); + num_annotations--; } - else skip(attr_length); - class_attr_count --; } - valid = true; - }; - bool valid; - bool is_synthetic; - uint32_t magic; - uint16_t minor_version; - uint16_t major_version; - constant_pool constants; - uint16_t access_flags; - uint16_t this_class; - uint16_t super_class; - // interfaces this class implements ? must be. investigate. - std::vector interfaces; - // FIXME: doesn't free up memory on delete - java::annotation_table visible_class_annotations; - }; + else + skip(attr_length); + class_attr_count--; + } + valid = true; + } + ; + bool valid; + bool is_synthetic; + uint32_t magic; + uint16_t minor_version; + uint16_t major_version; + constant_pool constants; + uint16_t access_flags; + uint16_t this_class; + uint16_t super_class; + // interfaces this class implements ? must be. investigate. + std::vector interfaces; + // FIXME: doesn't free up memory on delete + java::annotation_table visible_class_annotations; +}; } \ No newline at end of file diff --git a/depends/classparser/src/constants.h b/depends/classparser/src/constants.h index 61aa5687..242b943e 100644 --- a/depends/classparser/src/constants.h +++ b/depends/classparser/src/constants.h @@ -4,209 +4,217 @@ namespace java { - class constant +class constant +{ +public: + enum type_t : uint8_t { - public: - enum type_t : uint8_t - { - j_hole = 0, // HACK: this is a hole in the array, because java is crazy - j_string_data = 1, - j_int = 3, - j_float = 4, - j_long = 5, - j_double = 6, - j_class = 7, - j_string = 8, - j_fieldref = 9, - j_methodref = 10, - j_interface_methodref = 11, - j_nameandtype = 12 - } type; + j_hole = 0, // HACK: this is a hole in the array, because java is crazy + j_string_data = 1, + j_int = 3, + j_float = 4, + j_long = 5, + j_double = 6, + j_class = 7, + j_string = 8, + j_fieldref = 9, + j_methodref = 10, + j_interface_methodref = 11, + j_nameandtype = 12 + } type; - constant(util::membuffer & buf ) - { - buf.read(type); - // invalid constant type! - if(type > j_nameandtype || type == (type_t)0 || type == (type_t)2) - throw new classfile_exception(); - - // load data depending on type - switch(type) - { - case j_float: - case j_int: - buf.read_be(int_data); // same as float data really - break; - case j_double: - case j_long: - buf.read_be(long_data); // same as double - break; - case j_class: - buf.read_be(ref_type.class_idx); - break; - case j_fieldref: - case j_methodref: - case j_interface_methodref: - buf.read_be(ref_type.class_idx); - buf.read_be(ref_type.name_and_type_idx); - break; - case j_string: - buf.read_be(index); - break; - case j_string_data: - // HACK HACK: for now, we call these UTF-8 and do no further processing. - // Later, we should do some decoding. It's really modified UTF-8 - // * U+0000 is represented as 0xC0,0x80 invalid character - // * any single zero byte ends the string - // * characters above U+10000 are encoded like in CESU-8 - buf.read_jstr(str_data); - break; - case j_nameandtype: - buf.read_be(name_and_type.name_index); - buf.read_be(name_and_type.descriptor_index); - break; - } - } + constant(util::membuffer &buf) + { + buf.read(type); + // invalid constant type! + if (type > j_nameandtype || type == (type_t)0 || type == (type_t)2) + throw new classfile_exception(); - constant(int fake) + // load data depending on type + switch (type) { - type = j_hole; + case j_float: + case j_int: + buf.read_be(int_data); // same as float data really + break; + case j_double: + case j_long: + buf.read_be(long_data); // same as double + break; + case j_class: + buf.read_be(ref_type.class_idx); + break; + case j_fieldref: + case j_methodref: + case j_interface_methodref: + buf.read_be(ref_type.class_idx); + buf.read_be(ref_type.name_and_type_idx); + break; + case j_string: + buf.read_be(index); + break; + case j_string_data: + // HACK HACK: for now, we call these UTF-8 and do no further processing. + // Later, we should do some decoding. It's really modified UTF-8 + // * U+0000 is represented as 0xC0,0x80 invalid character + // * any single zero byte ends the string + // * characters above U+10000 are encoded like in CESU-8 + buf.read_jstr(str_data); + break; + case j_nameandtype: + buf.read_be(name_and_type.name_index); + buf.read_be(name_and_type.descriptor_index); + break; } + } + + constant(int fake) + { + type = j_hole; + } - std::string toString() + std::string toString() + { + std::ostringstream ss; + switch (type) { - std::ostringstream ss; - switch(type) - { - case j_hole: - ss << "Fake legacy entry"; - break; - case j_float: - ss << "Float: " << float_data; - break; - case j_double: - ss << "Double: " << double_data; - break; - case j_int: - ss << "Int: " << int_data; - break; - case j_long: - ss << "Long: " << long_data; - break; - case j_string_data: - ss << "StrData: " << str_data; - break; - case j_string: - ss << "Str: " << index; - break; - case j_fieldref: - ss << "FieldRef: " << ref_type.class_idx << " " << ref_type.name_and_type_idx; - break; - case j_methodref: - ss << "MethodRef: " << ref_type.class_idx << " " << ref_type.name_and_type_idx; - break; - case j_interface_methodref: - ss << "IfMethodRef: " << ref_type.class_idx << " " << ref_type.name_and_type_idx; - break; - case j_class: - ss << "Class: " << ref_type.class_idx; - break; - case j_nameandtype: - ss << "NameAndType: " << name_and_type.name_index << " " << name_and_type.descriptor_index; - break; - } - return ss.str(); + case j_hole: + ss << "Fake legacy entry"; + break; + case j_float: + ss << "Float: " << float_data; + break; + case j_double: + ss << "Double: " << double_data; + break; + case j_int: + ss << "Int: " << int_data; + break; + case j_long: + ss << "Long: " << long_data; + break; + case j_string_data: + ss << "StrData: " << str_data; + break; + case j_string: + ss << "Str: " << index; + break; + case j_fieldref: + ss << "FieldRef: " << ref_type.class_idx << " " << ref_type.name_and_type_idx; + break; + case j_methodref: + ss << "MethodRef: " << ref_type.class_idx << " " << ref_type.name_and_type_idx; + break; + case j_interface_methodref: + ss << "IfMethodRef: " << ref_type.class_idx << " " << ref_type.name_and_type_idx; + break; + case j_class: + ss << "Class: " << ref_type.class_idx; + break; + case j_nameandtype: + ss << "NameAndType: " << name_and_type.name_index << " " + << name_and_type.descriptor_index; + break; } + return ss.str(); + } - std::string str_data; /** String data in 'modified utf-8'.*/ - // store everything here. - union + std::string str_data; /** String data in 'modified utf-8'.*/ + // store everything here. + union + { + int32_t int_data; + int64_t long_data; + float float_data; + double double_data; + uint16_t index; + struct { - int32_t int_data; - int64_t long_data; - float float_data; - double double_data; - uint16_t index; - struct - { - /** - * Class reference: - * an index within the constant pool to a UTF-8 string containing - * the fully qualified class name (in internal format) - * Used for j_class, j_fieldref, j_methodref and j_interface_methodref - */ - uint16_t class_idx; - // used for j_fieldref, j_methodref and j_interface_methodref - uint16_t name_and_type_idx; - } ref_type; - struct - { - uint16_t name_index; - uint16_t descriptor_index; - } name_and_type; - }; + /** + * Class reference: + * an index within the constant pool to a UTF-8 string containing + * the fully qualified class name (in internal format) + * Used for j_class, j_fieldref, j_methodref and j_interface_methodref + */ + uint16_t class_idx; + // used for j_fieldref, j_methodref and j_interface_methodref + uint16_t name_and_type_idx; + } ref_type; + struct + { + uint16_t name_index; + uint16_t descriptor_index; + } name_and_type; }; +}; +/** + * A helper class that represents the custom container used in Java class file for storage of + * constants + */ +class constant_pool +{ +public: + /** + * Create a pool of constants + */ + constant_pool() + { + } /** - * A helper class that represents the custom container used in Java class file for storage of constants + * Load a java constant pool */ - class constant_pool + void load(util::membuffer &buf) { - public: - /** - * Create a pool of constants - */ - constant_pool(){} - /** - * Load a java constant pool - */ - void load(util::membuffer & buf) + uint16_t length = 0; + buf.read_be(length); + length--; + uint16_t index = 1; + const constant *last_constant = nullptr; + while (length) { - uint16_t length = 0; - buf.read_be(length); - length --; - uint16_t index = 1; - const constant * last_constant = nullptr; - while(length) + const constant &cnst = constant(buf); + constants.push_back(cnst); + last_constant = &constants[constants.size() - 1]; + if (last_constant->type == constant::j_double || + last_constant->type == constant::j_long) { - const constant & cnst = constant(buf); - constants.push_back(cnst); - last_constant = &constants[constants.size() - 1]; - if(last_constant->type == constant::j_double || last_constant->type == constant::j_long) - { - // push in a fake constant to preserve indexing - constants.push_back(constant(0)); - length-=2; - index+=2; - } - else - { - length--; - index++; - } + // push in a fake constant to preserve indexing + constants.push_back(constant(0)); + length -= 2; + index += 2; } - } - typedef std::vector container_type; - /** - * Access constants based on jar file index numbers (index of the first element is 1) - */ - java::constant & operator[](std::size_t constant_index) - { - if(constant_index == 0 || constant_index > constants.size()) + else { - throw new classfile_exception(); + length--; + index++; } - return constants[constant_index - 1]; - }; - container_type::const_iterator begin() const - { - return constants.begin(); - }; - container_type::const_iterator end() const + } + } + typedef std::vector container_type; + /** + * Access constants based on jar file index numbers (index of the first element is 1) + */ + java::constant &operator[](std::size_t constant_index) + { + if (constant_index == 0 || constant_index > constants.size()) { - return constants.end(); + throw new classfile_exception(); } - private: - container_type constants; - }; + return constants[constant_index - 1]; + } + ; + container_type::const_iterator begin() const + { + return constants.begin(); + } + ; + container_type::const_iterator end() const + { + return constants.end(); + } + +private: + container_type constants; +}; } diff --git a/depends/classparser/src/errors.h b/depends/classparser/src/errors.h index c02b07c8..ddbbd828 100644 --- a/depends/classparser/src/errors.h +++ b/depends/classparser/src/errors.h @@ -2,5 +2,7 @@ #include namespace java { - class classfile_exception : public std::exception {}; +class classfile_exception : public std::exception +{ +}; } diff --git a/depends/classparser/src/javaendian.h b/depends/classparser/src/javaendian.h index fa6207fe..d488b382 100644 --- a/depends/classparser/src/javaendian.h +++ b/depends/classparser/src/javaendian.h @@ -10,53 +10,67 @@ namespace util inline uint64_t bigswap(uint64_t x) { return x; -}; +} +; inline uint32_t bigswap(uint32_t x) { return x; -}; +} +; inline uint16_t bigswap(uint16_t x) { return x; -}; +} +; inline int64_t bigswap(int64_t x) { return x; -}; +} +; inline int32_t bigswap(int32_t x) { return x; -}; +} +; inline int16_t bigswap(int16_t x) { return x; -}; +} +; #else inline uint64_t bigswap(uint64_t x) { - return (x>>56) | ((x<<40) & 0x00FF000000000000) | ((x<<24) & 0x0000FF0000000000) | ((x<<8) & 0x000000FF00000000) | - ((x>>8) & 0x00000000FF000000) | ((x>>24) & 0x0000000000FF0000) | ((x>>40) & 0x000000000000FF00) | (x<<56); -}; + return (x >> 56) | ((x << 40) & 0x00FF000000000000) | ((x << 24) & 0x0000FF0000000000) | + ((x << 8) & 0x000000FF00000000) | ((x >> 8) & 0x00000000FF000000) | + ((x >> 24) & 0x0000000000FF0000) | ((x >> 40) & 0x000000000000FF00) | (x << 56); +} +; inline uint32_t bigswap(uint32_t x) { - return (x>>24) | ((x<<8) & 0x00FF0000) | ((x>>8) & 0x0000FF00) | (x<<24); -}; + return (x >> 24) | ((x << 8) & 0x00FF0000) | ((x >> 8) & 0x0000FF00) | (x << 24); +} +; inline uint16_t bigswap(uint16_t x) { - return (x>>8) | (x<<8); -}; + return (x >> 8) | (x << 8); +} +; inline int64_t bigswap(int64_t x) { - return (x>>56) | ((x<<40) & 0x00FF000000000000) | ((x<<24) & 0x0000FF0000000000) | ((x<<8) & 0x000000FF00000000) | - ((x>>8) & 0x00000000FF000000) | ((x>>24) & 0x0000000000FF0000) | ((x>>40) & 0x000000000000FF00) | (x<<56); -}; + return (x >> 56) | ((x << 40) & 0x00FF000000000000) | ((x << 24) & 0x0000FF0000000000) | + ((x << 8) & 0x000000FF00000000) | ((x >> 8) & 0x00000000FF000000) | + ((x >> 24) & 0x0000000000FF0000) | ((x >> 40) & 0x000000000000FF00) | (x << 56); +} +; inline int32_t bigswap(int32_t x) { - return (x>>24) | ((x<<8) & 0x00FF0000) | ((x>>8) & 0x0000FF00) | (x<<24); -}; + return (x >> 24) | ((x << 8) & 0x00FF0000) | ((x >> 8) & 0x0000FF00) | (x << 24); +} +; inline int16_t bigswap(int16_t x) { - return (x>>8) | (x<<8); -}; + return (x >> 8) | (x << 8); +} +; #endif } diff --git a/depends/classparser/src/javautils.cpp b/depends/classparser/src/javautils.cpp index 3a5c6934..9f9ac263 100644 --- a/depends/classparser/src/javautils.cpp +++ b/depends/classparser/src/javautils.cpp @@ -49,24 +49,28 @@ QString GetMinecraftJarVersion(QString jarName) Minecraft.read(classfile, size); // parse Minecraft.class - try { + try + { char *temp = classfile; java::classfile MinecraftClass(temp, size); java::constant_pool constants = MinecraftClass.constants; - for(java::constant_pool::container_type::const_iterator iter=constants.begin(); - iter != constants.end(); iter++) + for (java::constant_pool::container_type::const_iterator iter = constants.begin(); + iter != constants.end(); iter++) { - const java::constant & constant = *iter; + const java::constant &constant = *iter; if (constant.type != java::constant::j_string_data) continue; - const std::string & str = constant.str_data; + const std::string &str = constant.str_data; if (str.compare(0, 20, "Minecraft Minecraft ") == 0) { version = str.substr(20).data(); break; } } - } catch(java::classfile_exception &) {} + } + catch (java::classfile_exception &) + { + } // clean up delete[] classfile; @@ -76,5 +80,4 @@ QString GetMinecraftJarVersion(QString jarName) return version; } - } diff --git a/depends/classparser/src/membuffer.h b/depends/classparser/src/membuffer.h index 2ea3a69b..ab83412a 100644 --- a/depends/classparser/src/membuffer.h +++ b/depends/classparser/src/membuffer.h @@ -7,58 +7,57 @@ namespace util { - class membuffer +class membuffer +{ +public: + membuffer(char *buffer, std::size_t size) + { + current = start = buffer; + end = start + size; + } + ~membuffer() + { + // maybe? possibly? left out to avoid confusion. for now. + // delete start; + } + /** + * Read some value. That's all ;) + */ + template void read(T &val) + { + val = *(T *)current; + current += sizeof(T); + } + /** + * Read a big-endian number + * valid for 2-byte, 4-byte and 8-byte variables + */ + template void read_be(T &val) { - public: - membuffer(char * buffer, std::size_t size) - { - current = start = buffer; - end = start + size; - } - ~membuffer() - { - // maybe? possibly? left out to avoid confusion. for now. - //delete start; - } - /** - * Read some value. That's all ;) - */ - template - void read(T& val) - { - val = *(T *)current; - current += sizeof(T); - } - /** - * Read a big-endian number - * valid for 2-byte, 4-byte and 8-byte variables - */ - template - void read_be(T& val) - { - val = util::bigswap(*(T *)current); - current += sizeof(T); - } - /** - * Read a string in the format: - * 2B length (big endian, unsigned) - * length bytes data - */ - void read_jstr(std::string & str) - { - uint16_t length = 0; - read_be(length); - str.append(current,length); - current += length; - } - /** - * Skip N bytes - */ - void skip (std::size_t N) - { - current += N; - } - private: - char * start, *end, *current; - }; + val = util::bigswap(*(T *)current); + current += sizeof(T); + } + /** + * Read a string in the format: + * 2B length (big endian, unsigned) + * length bytes data + */ + void read_jstr(std::string &str) + { + uint16_t length = 0; + read_be(length); + str.append(current, length); + current += length; + } + /** + * Skip N bytes + */ + void skip(std::size_t N) + { + current += N; + } + +private: + char *start, *end, *current; +}; } diff --git a/depends/launcher/MCFrame.java b/depends/launcher/MCFrame.java index d6ebb240..ce4564c9 100644 --- a/depends/launcher/MCFrame.java +++ b/depends/launcher/MCFrame.java @@ -1,12 +1,12 @@ -// +// // Copyright 2012 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. @@ -30,94 +30,85 @@ import java.awt.image.BufferedImage; public class MCFrame extends Frame implements WindowListener { - private Launcher appletWrap = null; - public MCFrame(String title) - { - super(title); - BufferedImage image = null; - try - { - image = ImageIO.read(new File("icon.png")); - setIconImage(image); - } - catch (IOException e) - { - e.printStackTrace(); - } - this.addWindowListener(this); - } + private Launcher appletWrap = null; + public MCFrame ( String title ) + { + super ( title ); + BufferedImage image = null; + try { + image = ImageIO.read ( new File ( "icon.png" ) ); + setIconImage ( image ); + } catch ( IOException e ) { + e.printStackTrace(); + } + this.addWindowListener ( this ); + } + + public void start ( Applet mcApplet, String user, String session, Dimension winSize, boolean maximize ) + { + try { + appletWrap = new Launcher ( mcApplet, new URL ( "http://www.minecraft.net/game" ) ); + } catch ( MalformedURLException ignored ) {} + + appletWrap.setParameter ( "username", user ); + appletWrap.setParameter ( "sessionid", session ); + appletWrap.setParameter ( "stand-alone", "true" ); // Show the quit button. + mcApplet.setStub ( appletWrap ); + + this.add ( appletWrap ); + appletWrap.setPreferredSize ( winSize ); + this.pack(); + this.setLocationRelativeTo ( null ); + this.setResizable ( true ); + if ( maximize ) { + this.setExtendedState ( MAXIMIZED_BOTH ); + } - public void start(Applet mcApplet, String user, String session, Dimension winSize, boolean maximize) - { - try - { - appletWrap = new Launcher(mcApplet, new URL("http://www.minecraft.net/game")); - } - catch (MalformedURLException ignored){} - - appletWrap.setParameter("username", user); - appletWrap.setParameter("sessionid", session); - appletWrap.setParameter("stand-alone", "true"); // Show the quit button. - mcApplet.setStub(appletWrap); - - this.add(appletWrap); - appletWrap.setPreferredSize(winSize); - this.pack(); - this.setLocationRelativeTo(null); - this.setResizable(true); - if (maximize) - this.setExtendedState(MAXIMIZED_BOTH); - - validate(); - appletWrap.init(); - appletWrap.start(); - setVisible(true); - } + validate(); + appletWrap.init(); + appletWrap.start(); + setVisible ( true ); + } - @Override - public void windowActivated(WindowEvent e) {} + @Override + public void windowActivated ( WindowEvent e ) {} - @Override - public void windowClosed(WindowEvent e) {} + @Override + public void windowClosed ( WindowEvent e ) {} - @Override - public void windowClosing(WindowEvent e) - { - new Thread() - { - public void run() - { - try - { - Thread.sleep(30000L); - } catch (InterruptedException localInterruptedException) - { - localInterruptedException.printStackTrace(); - } - System.out.println("FORCING EXIT!"); - System.exit(0); - } - } - .start(); + @Override + public void windowClosing ( WindowEvent e ) + { + new Thread() { + public void run() { + try { + Thread.sleep ( 30000L ); + } catch ( InterruptedException localInterruptedException ) { + localInterruptedException.printStackTrace(); + } + System.out.println ( "FORCING EXIT!" ); + System.exit ( 0 ); + } + } + .start(); - if (appletWrap != null) - { - appletWrap.stop(); - appletWrap.destroy(); - } - // old minecraft versions can hang without this >_< - System.exit(0); - } + if ( appletWrap != null ) { + appletWrap.stop(); + appletWrap.destroy(); + } + // old minecraft versions can hang without this >_< + System.exit ( 0 ); + } - @Override - public void windowDeactivated(WindowEvent e) {} + @Override + public void windowDeactivated ( WindowEvent e ) {} - @Override - public void windowDeiconified(WindowEvent e) {} + @Override + public void windowDeiconified ( WindowEvent e ) {} - @Override - public void windowIconified(WindowEvent e) {} + @Override + public void windowIconified ( WindowEvent e ) {} - @Override - public void windowOpened(WindowEvent e) {} -} \ No newline at end of file + @Override + public void windowOpened ( WindowEvent e ) {} +} diff --git a/depends/pack200/src/unpack.cpp b/depends/pack200/src/unpack.cpp index d7de1b22..b286269d 100644 --- a/depends/pack200/src/unpack.cpp +++ b/depends/pack200/src/unpack.cpp @@ -1523,8 +1523,8 @@ band **unpacker::attr_definitions::buildBands(unpacker::layout_definition *lo) call.le_body[0] = &cble; // Distinguish backward calls and callables: assert(cble.le_kind == EK_CBLE); - //FIXME: hit this one - //assert(cble.le_len == call_num); + // FIXME: hit this one + // assert(cble.le_len == call_num); cble.le_back |= call.le_back; } calls_to_link.popTo(0); @@ -2778,8 +2778,8 @@ void unpacker::putlayout(band **body) { band &cble = *b.le_body[0]; assert(cble.le_kind == EK_CBLE); - //FIXME: hit this one - //assert(cble.le_len == b.le_len); + // FIXME: hit this one + // assert(cble.le_len == b.le_len); putlayout(cble.le_body); } break; diff --git a/depends/settings/include/basicsettingsobject.h b/depends/settings/include/basicsettingsobject.h index b7e5851d..387a3646 100644 --- a/depends/settings/include/basicsettingsobject.h +++ b/depends/settings/include/basicsettingsobject.h @@ -3,7 +3,7 @@ * 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 @@ -13,8 +13,7 @@ * limitations under the License. */ -#ifndef BASICSETTINGSOBJECT_H -#define BASICSETTINGSOBJECT_H +#pragma once #include #include @@ -31,14 +30,13 @@ class LIBSETTINGS_EXPORT BasicSettingsObject : public SettingsObject Q_OBJECT public: explicit BasicSettingsObject(QObject *parent = 0); - -protected slots: + +protected +slots: virtual void changeSetting(const Setting &setting, QVariant value); - + protected: virtual QVariant retrieveValue(const Setting &setting); - + QSettings config; }; - -#endif // BASICSETTINGSOBJECT_H diff --git a/depends/settings/include/inifile.h b/depends/settings/include/inifile.h index 8d30a258..27da7bf0 100644 --- a/depends/settings/include/inifile.h +++ b/depends/settings/include/inifile.h @@ -3,7 +3,7 @@ * 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 @@ -14,6 +14,7 @@ */ #pragma once + #include #include #include @@ -25,11 +26,11 @@ class LIBSETTINGS_EXPORT INIFile : public QMap { public: explicit INIFile(); - + bool loadFile(QByteArray file); bool loadFile(QString fileName); bool saveFile(QString fileName); - + QVariant get(QString key, QVariant def) const; void set(QString key, QVariant val); QString unescape(QString orig); diff --git a/depends/settings/include/inisettingsobject.h b/depends/settings/include/inisettingsobject.h index 03d6fe05..8badc0c6 100644 --- a/depends/settings/include/inisettingsobject.h +++ b/depends/settings/include/inisettingsobject.h @@ -3,7 +3,7 @@ * 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 @@ -13,8 +13,7 @@ * limitations under the License. */ -#ifndef INISETTINGSOBJECT_H -#define INISETTINGSOBJECT_H +#pragma once #include @@ -22,7 +21,7 @@ #include "settingsobject.h" -#include "libutil_config.h" +#include "libsettings_config.h" /*! * \brief A settings object that stores its settings in an INIFile. @@ -32,29 +31,31 @@ class LIBSETTINGS_EXPORT INISettingsObject : public SettingsObject Q_OBJECT public: explicit INISettingsObject(const QString &path, QObject *parent = 0); - + /*! * \brief Gets the path to the INI file. * \return The path to the INI file. */ - virtual QString filePath() const { return m_filePath; } - + virtual QString filePath() const + { + return m_filePath; + } + /*! * \brief Sets the path to the INI file and reloads it. * \param filePath The INI file's new path. */ virtual void setFilePath(const QString &filePath); - -protected slots: + +protected +slots: virtual void changeSetting(const Setting &setting, QVariant value); - virtual void resetSetting ( const Setting& setting ); - + virtual void resetSetting(const Setting &setting); + protected: virtual QVariant retrieveValue(const Setting &setting); - + INIFile m_ini; - + QString m_filePath; }; - -#endif // INISETTINGSOBJECT_H diff --git a/depends/settings/include/keyring.h b/depends/settings/include/keyring.h index 299b14b0..747211de 100644 --- a/depends/settings/include/keyring.h +++ b/depends/settings/include/keyring.h @@ -15,8 +15,7 @@ * limitations under the License. */ -#ifndef KEYRING_H -#define KEYRING_H +#pragma once #include @@ -79,14 +78,15 @@ public: * @return */ virtual void removeStoredAccount(QString service, QString username) = 0; - + protected: /// fall back to StubKeyring if false - virtual bool isValid() { return false; } + virtual bool isValid() + { + return false; + } private: static Keyring *m_instance; static void destroy(); }; - -#endif // KEYRING_H diff --git a/depends/settings/include/libsettings_config.h b/depends/settings/include/libsettings_config.h index 2ecfe1c1..ba77f640 100644 --- a/depends/settings/include/libsettings_config.h +++ b/depends/settings/include/libsettings_config.h @@ -3,7 +3,7 @@ * 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 @@ -18,11 +18,11 @@ #include #ifdef LIBSETTINGS_STATIC - #define LIBSETTINGS_EXPORT +#define LIBSETTINGS_EXPORT +#else +#ifdef LIBSETTINGS_LIBRARY +#define LIBSETTINGS_EXPORT Q_DECL_EXPORT #else - #ifdef LIBSETTINGS_LIBRARY - #define LIBSETTINGS_EXPORT Q_DECL_EXPORT - #else - #define LIBSETTINGS_EXPORT Q_DECL_IMPORT - #endif +#define LIBSETTINGS_EXPORT Q_DECL_IMPORT +#endif #endif diff --git a/depends/settings/include/overridesetting.h b/depends/settings/include/overridesetting.h index 58bb6d40..3e60dc7c 100644 --- a/depends/settings/include/overridesetting.h +++ b/depends/settings/include/overridesetting.h @@ -3,7 +3,7 @@ * 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 @@ -13,8 +13,7 @@ * limitations under the License. */ -#ifndef OVERRIDESETTING_H -#define OVERRIDESETTING_H +#pragma once #include @@ -25,7 +24,7 @@ /*! * \brief A setting that 'overrides another.' * This means that the setting's default value will be the value of another setting. - * The other setting can be (and usually is) a part of a different SettingsObject + * The other setting can be (and usually is) a part of a different SettingsObject * than this one. */ class LIBSETTINGS_EXPORT OverrideSetting : public Setting @@ -33,11 +32,9 @@ class LIBSETTINGS_EXPORT OverrideSetting : public Setting Q_OBJECT public: explicit OverrideSetting(const QString &name, Setting *other, QObject *parent = 0); - + virtual QVariant defValue() const; - + protected: Setting *m_other; }; - -#endif // OVERRIDESETTING_H diff --git a/depends/settings/include/setting.h b/depends/settings/include/setting.h index a161ab50..39490207 100644 --- a/depends/settings/include/setting.h +++ b/depends/settings/include/setting.h @@ -3,7 +3,7 @@ * 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 @@ -13,8 +13,7 @@ * limitations under the License. */ -#ifndef SETTING_H -#define SETTING_H +#pragma once #include #include @@ -24,7 +23,7 @@ class SettingsObject; /*! - * + * */ class LIBSETTINGS_EXPORT Setting : public QObject { @@ -35,23 +34,30 @@ public: * \param parent The Setting's parent object. */ explicit Setting(QString id, QVariant defVal = QVariant(), QObject *parent = 0); - + /*! * \brief Gets this setting's ID. * This is used to refer to the setting within the application. - * \warning Changing the ID while the setting is registered with a SettingsObject results in undefined behavior. + * \warning Changing the ID while the setting is registered with a SettingsObject results in + * undefined behavior. * \return The ID of the setting. */ - virtual QString id() const { return m_id; } - + virtual QString id() const + { + return m_id; + } + /*! * \brief Gets this setting's config file key. * This is used to store the setting's value in the config file. It is usually * the same as the setting's ID, but it can be different. * \return The setting's config file key. */ - virtual QString configKey() const { return id(); } - + virtual QString configKey() const + { + return id(); + } + /*! * \brief Gets this setting's value as a QVariant. * This is done by calling the SettingsObject's retrieveValue() function. @@ -60,22 +66,23 @@ public: * \sa value() */ virtual QVariant get() const; - + /*! * \brief Gets this setting's actual value (I.E. not as a QVariant). * This function is just shorthand for get().value() * \return The setting's actual value. */ - template - inline T value() const { return get().value(); } - - + template inline T value() const + { + return get().value(); + } + /*! * \brief Gets this setting's default value. * \return The default value of this setting. */ virtual QVariant defValue() const; - + signals: /*! * \brief Signal emitted when this Setting object's value changes. @@ -83,14 +90,15 @@ signals: * \param value This Setting object's new value. */ void settingChanged(const Setting &setting, QVariant value); - + /*! * \brief Signal emitted when this Setting object's value resets to default. * \param setting A reference to the Setting that changed. */ void settingReset(const Setting &setting); - -public slots: + +public +slots: /*! * \brief Changes the setting's value. * This is done by emitting the settingChanged() signal which will then be @@ -98,7 +106,7 @@ public slots: * \param value The new value. */ virtual void set(QVariant value); - + /*! * \brief Reset the setting to default * This is done by emitting the settingReset() signal which will then be @@ -106,9 +114,8 @@ public slots: * \param value The new value. */ virtual void reset(); + protected: QString m_id; QVariant m_defVal; }; - -#endif // SETTING_H diff --git a/depends/settings/include/settingsobject.h b/depends/settings/include/settingsobject.h index e8bf5c83..7a6b3cb6 100644 --- a/depends/settings/include/settingsobject.h +++ b/depends/settings/include/settingsobject.h @@ -3,7 +3,7 @@ * 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 @@ -23,9 +23,10 @@ class Setting; /*! - * \brief The SettingsObject handles communicating settings between the application and a settings file. + * \brief The SettingsObject handles communicating settings between the application and a + *settings file. * The class keeps a list of Setting objects. Each Setting object represents one - * of the application's settings. These Setting objects are registered with + * of the application's settings. These Setting objects are registered with * a SettingsObject and can be managed similarly to the way a list works. * * \author Andrew Okin @@ -38,9 +39,10 @@ class LIBSETTINGS_EXPORT SettingsObject : public QObject Q_OBJECT public: explicit SettingsObject(QObject *parent = 0); - + /*! - * \brief Registers the given setting with this SettingsObject and connects the necessary signals. + * \brief Registers the given setting with this SettingsObject and connects the necessary + * signals. * This will fail if there is already a setting with the same ID as * the one that is being registered. * \note Registering a setting object causes the SettingsObject to take ownership @@ -52,36 +54,38 @@ public: * \return True if successful. False if registry failed. */ virtual bool registerSetting(Setting *setting); - + /*! - * \brief Unregisters the given setting from this SettingsObject and disconnects its signals. - * \note This does not delete the setting. Furthermore, when the setting is + * \brief Unregisters the given setting from this SettingsObject and disconnects its + * signals. + * \note This does not delete the setting. Furthermore, when the setting is * unregistered, the SettingsObject drops ownership of the setting. This means * that if you unregister a setting, its parent is set to null and you become * responsible for freeing its memory. * \param setting The setting to unregister. */ virtual void unregisterSetting(Setting *setting); - - + /*! * \brief Gets the setting with the given ID. * \param id The ID of the setting to get. - * \return A pointer to the setting with the given ID. + * \return A pointer to the setting with the given ID. * Returns null if there is no setting with the given ID. * \sa operator []() */ virtual Setting *getSetting(const QString &id) const; - + /*! * \brief Same as getSetting() * \param id The ID of the setting to get. - * \return A pointer to the setting with the given ID. + * \return A pointer to the setting with the given ID. * \sa getSetting() */ - inline Setting *operator [](const QString &id) { return getSetting(id); } - - + inline Setting *operator[](const QString &id) + { + return getSetting(id); + } + /*! * \brief Gets the value of the setting with the given ID. * \param id The ID of the setting to get. @@ -89,7 +93,7 @@ public: * If no setting with the given ID exists, returns an invalid QVariant. */ virtual QVariant get(const QString &id) const; - + /*! * \brief Sets the value of the setting with the given ID. * If no setting with the given ID exists, returns false and logs to qDebug @@ -98,87 +102,88 @@ public: * \return True if successful, false if it failed. */ virtual bool set(const QString &id, QVariant value); - + /*! * \brief Reverts the setting with the given ID to default. * \param id The ID of the setting to reset. */ virtual void reset(const QString &id) const; - + /*! * \brief Gets a QList with pointers to all of the registered settings. * The order of the entries in the list is undefined. * \return A QList with pointers to all registered settings. */ virtual QList getSettings(); - + /*! * \brief Checks if this SettingsObject contains a setting with the given ID. * \param id The ID to check for. * \return True if the SettingsObject has a setting with the given ID. */ virtual bool contains(const QString &id); - + signals: /*! * \brief Signal emitted when one of this SettingsObject object's settings changes. - * This is usually just connected directly to each Setting object's + * This is usually just connected directly to each Setting object's * settingChanged() signals. * \param setting A reference to the Setting object that changed. * \param value The Setting object's new value. */ void settingChanged(const Setting &setting, QVariant value); - + /*! * \brief Signal emitted when one of this SettingsObject object's settings resets. - * This is usually just connected directly to each Setting object's + * This is usually just connected directly to each Setting object's * settingReset() signals. * \param setting A reference to the Setting object that changed. */ void settingReset(const Setting &setting); - -protected slots: + +protected +slots: /*! * \brief Changes a setting. - * This slot is usually connected to each Setting object's + * This slot is usually connected to each Setting object's * settingChanged() signal. The signal is emitted, causing this slot * to update the setting's value in the config file. * \param setting A reference to the Setting object that changed. * \param value The setting's new value. */ virtual void changeSetting(const Setting &setting, QVariant value) = 0; - + /*! * \brief Resets a setting. - * This slot is usually connected to each Setting object's + * This slot is usually connected to each Setting object's * settingReset() signal. The signal is emitted, causing this slot * to update the setting's value in the config file. * \param setting A reference to the Setting object that changed. */ virtual void resetSetting(const Setting &setting) = 0; - + protected: /*! * \brief Connects the necessary signals to the given Setting. * \param setting The setting to connect. */ virtual void connectSignals(const Setting &setting); - + /*! * \brief Disconnects signals from the given Setting. * \param setting The setting to disconnect. */ virtual void disconnectSignals(const Setting &setting); - + /*! * \brief Function used by Setting objects to get their values from the SettingsObject. - * \param setting The - * \return + * \param setting The + * \return */ virtual QVariant retrieveValue(const Setting &setting) = 0; - + friend class Setting; - + private: QMap m_settings; }; diff --git a/depends/settings/src/basicsettingsobject.cpp b/depends/settings/src/basicsettingsobject.cpp index 484928c8..96b38851 100644 --- a/depends/settings/src/basicsettingsobject.cpp +++ b/depends/settings/src/basicsettingsobject.cpp @@ -3,7 +3,7 @@ * 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 @@ -16,17 +16,15 @@ #include "include/basicsettingsobject.h" #include "include/setting.h" -BasicSettingsObject::BasicSettingsObject(QObject *parent) : - SettingsObject(parent) +BasicSettingsObject::BasicSettingsObject(QObject *parent) : SettingsObject(parent) { - } void BasicSettingsObject::changeSetting(const Setting &setting, QVariant value) { if (contains(setting.id())) { - if(value.isValid()) + if (value.isValid()) config.setValue(setting.configKey(), value); else config.remove(setting.configKey()); diff --git a/depends/settings/src/inifile.cpp b/depends/settings/src/inifile.cpp index 1eae5609..83aec15e 100644 --- a/depends/settings/src/inifile.cpp +++ b/depends/settings/src/inifile.cpp @@ -3,7 +3,7 @@ * 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 @@ -19,10 +19,8 @@ #include #include - INIFile::INIFile() { - } QString INIFile::unescape(QString orig) @@ -47,50 +45,50 @@ bool INIFile::saveFile(QString fileName) file.open(QIODevice::WriteOnly); QTextStream out(&file); out.setCodec("UTF-8"); - + for (Iterator iter = begin(); iter != end(); iter++) { QString value = iter.value().toString(); value = escape(value); out << iter.key() << "=" << value << "\n"; } - + return true; } bool INIFile::loadFile(QString fileName) { QFile file(fileName); - if(!file.open(QIODevice::ReadOnly)) + if (!file.open(QIODevice::ReadOnly)) return false; bool success = loadFile(file.readAll()); file.close(); return success; } -bool INIFile::loadFile( QByteArray file ) +bool INIFile::loadFile(QByteArray file) { QTextStream in(file); in.setCodec("UTF-8"); - + QStringList lines = in.readAll().split('\n'); for (int i = 0; i < lines.count(); i++) { - QString & lineRaw = lines[i]; + QString &lineRaw = lines[i]; // Ignore comments. QString line = lineRaw.left(lineRaw.indexOf('#')).trimmed(); - + int eqPos = line.indexOf('='); - if(eqPos == -1) + if (eqPos == -1) continue; QString key = line.left(eqPos).trimmed(); QString valueStr = line.right(line.length() - eqPos - 1).trimmed(); - + valueStr = unescape(valueStr); - + QVariant value(valueStr); - this->operator [](key) = value; + this->operator[](key) = value; } - + return true; } @@ -99,10 +97,10 @@ QVariant INIFile::get(QString key, QVariant def) const if (!this->contains(key)) return def; else - return this->operator [](key); + return this->operator[](key); } void INIFile::set(QString key, QVariant val) { - this->operator [](key) = val; + this->operator[](key) = val; } diff --git a/depends/settings/src/inisettingsobject.cpp b/depends/settings/src/inisettingsobject.cpp index 854421b6..4a7a7428 100644 --- a/depends/settings/src/inisettingsobject.cpp +++ b/depends/settings/src/inisettingsobject.cpp @@ -3,7 +3,7 @@ * 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 @@ -16,8 +16,8 @@ #include "include/inisettingsobject.h" #include "include/setting.h" -INISettingsObject::INISettingsObject(const QString &path, QObject *parent) : - SettingsObject(parent) +INISettingsObject::INISettingsObject(const QString &path, QObject *parent) + : SettingsObject(parent) { m_filePath = path; m_ini.loadFile(path); @@ -32,7 +32,7 @@ void INISettingsObject::changeSetting(const Setting &setting, QVariant value) { if (contains(setting.id())) { - if(value.isValid()) + if (value.isValid()) m_ini.set(setting.configKey(), value); else m_ini.remove(setting.configKey()); @@ -40,7 +40,7 @@ void INISettingsObject::changeSetting(const Setting &setting, QVariant value) } } -void INISettingsObject::resetSetting ( const Setting& setting ) +void INISettingsObject::resetSetting(const Setting &setting) { if (contains(setting.id())) { diff --git a/depends/settings/src/overridesetting.cpp b/depends/settings/src/overridesetting.cpp index eafb298f..5b10920d 100644 --- a/depends/settings/src/overridesetting.cpp +++ b/depends/settings/src/overridesetting.cpp @@ -3,7 +3,7 @@ * 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 @@ -15,8 +15,8 @@ #include "include/overridesetting.h" -OverrideSetting::OverrideSetting(const QString &name, Setting *other, QObject *parent) : - Setting(name, QVariant(), parent) +OverrideSetting::OverrideSetting(const QString &name, Setting *other, QObject *parent) + : Setting(name, QVariant(), parent) { m_other = other; } diff --git a/depends/settings/src/setting.cpp b/depends/settings/src/setting.cpp index 8e60af06..899463dc 100644 --- a/depends/settings/src/setting.cpp +++ b/depends/settings/src/setting.cpp @@ -3,7 +3,7 @@ * 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 @@ -16,10 +16,9 @@ #include "include/setting.h" #include "include/settingsobject.h" -Setting::Setting(QString id, QVariant defVal, QObject *parent) : - QObject(parent), m_id(id), m_defVal(defVal) +Setting::Setting(QString id, QVariant defVal, QObject *parent) + : QObject(parent), m_id(id), m_defVal(defVal) { - } QVariant Setting::get() const @@ -32,7 +31,7 @@ QVariant Setting::get() const else { QVariant test = sbase->retrieveValue(*this); - if(!test.isValid()) + if (!test.isValid()) return defValue(); return test; } diff --git a/depends/settings/src/settingsobject.cpp b/depends/settings/src/settingsobject.cpp index 2ca544ad..32a63b8d 100644 --- a/depends/settings/src/settingsobject.cpp +++ b/depends/settings/src/settingsobject.cpp @@ -3,7 +3,7 @@ * 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 @@ -18,10 +18,8 @@ #include -SettingsObject::SettingsObject(QObject *parent) : - QObject(parent) +SettingsObject::SettingsObject(QObject *parent) : QObject(parent) { - } bool SettingsObject::registerSetting(Setting *setting) @@ -29,24 +27,26 @@ bool SettingsObject::registerSetting(Setting *setting) // Check if setting is null or we already have a setting with the same ID. if (!setting) { - qDebug(QString("Failed to register setting. Setting is null."). - arg(setting->id()).toUtf8()); + qDebug(QString("Failed to register setting. Setting is null.") + .arg(setting->id()) + .toUtf8()); return false; // Fail } - + if (contains(setting->id())) { - qDebug(QString("Failed to register setting %1. ID already exists."). - arg(setting->id()).toUtf8()); + qDebug(QString("Failed to register setting %1. ID already exists.") + .arg(setting->id()) + .toUtf8()); return false; // Fail } - + m_settings.insert(setting->id(), setting); setting->setParent(this); // Take ownership. - + // Connect signals. connectSignals(*setting); - + // qDebug(QString("Registered setting %1.").arg(setting->id()).toUtf8()); return true; } @@ -55,22 +55,21 @@ void SettingsObject::unregisterSetting(Setting *setting) { if (!setting || !m_settings.contains(setting->id())) return; // We can't unregister something that's not registered. - + m_settings.remove(setting->id()); - + // Disconnect signals. disconnectSignals(*setting); - + setting->setParent(NULL); // Drop ownership. } - Setting *SettingsObject::getSetting(const QString &id) const { // Make sure there is a setting with the given ID. if (!m_settings.contains(id)) return NULL; - + return m_settings[id]; } @@ -85,8 +84,7 @@ bool SettingsObject::set(const QString &id, QVariant value) Setting *setting = getSetting(id); if (!setting) { - qDebug(QString("Error changing setting %1. Setting doesn't exist."). - arg(id).toUtf8()); + qDebug(QString("Error changing setting %1. Setting doesn't exist.").arg(id).toUtf8()); return false; } else @@ -99,11 +97,10 @@ bool SettingsObject::set(const QString &id, QVariant value) void SettingsObject::reset(const QString &id) const { Setting *setting = getSetting(id); - if(setting) + if (setting) setting->reset(); } - QList SettingsObject::getSettings() { return m_settings.values(); @@ -114,29 +111,26 @@ bool SettingsObject::contains(const QString &id) return m_settings.contains(id); } - void SettingsObject::connectSignals(const Setting &setting) { connect(&setting, SIGNAL(settingChanged(const Setting &, QVariant)), SLOT(changeSetting(const Setting &, QVariant))); connect(&setting, SIGNAL(settingChanged(const Setting &, QVariant)), SIGNAL(settingChanged(const Setting &, QVariant))); - - connect(&setting, SIGNAL(settingReset(Setting)), - SLOT(resetSetting(const Setting &))); - connect(&setting, SIGNAL(settingReset(Setting)), - SIGNAL(settingReset(const Setting &))); + + connect(&setting, SIGNAL(settingReset(Setting)), SLOT(resetSetting(const Setting &))); + connect(&setting, SIGNAL(settingReset(Setting)), SIGNAL(settingReset(const Setting &))); } void SettingsObject::disconnectSignals(const Setting &setting) { - setting.disconnect(SIGNAL(settingChanged(const Setting &, QVariant)), - this, SLOT(changeSetting(const Setting &, QVariant))); - setting.disconnect(SIGNAL(settingChanged(const Setting &, QVariant)), - this, SIGNAL(settingChanged(const Setting &, QVariant))); - - setting.disconnect(SIGNAL(settingReset(const Setting &, QVariant)), - this, SLOT(resetSetting(const Setting &, QVariant))); - setting.disconnect(SIGNAL(settingReset(const Setting &, QVariant)), - this, SIGNAL(settingReset(const Setting &, QVariant))); + setting.disconnect(SIGNAL(settingChanged(const Setting &, QVariant)), this, + SLOT(changeSetting(const Setting &, QVariant))); + setting.disconnect(SIGNAL(settingChanged(const Setting &, QVariant)), this, + SIGNAL(settingChanged(const Setting &, QVariant))); + + setting.disconnect(SIGNAL(settingReset(const Setting &, QVariant)), this, + SLOT(resetSetting(const Setting &, QVariant))); + setting.disconnect(SIGNAL(settingReset(const Setting &, QVariant)), this, + SIGNAL(settingReset(const Setting &, QVariant))); } diff --git a/depends/settings/src/stubkeyring.cpp b/depends/settings/src/stubkeyring.cpp index cf814d2f..53fca025 100644 --- a/depends/settings/src/stubkeyring.cpp +++ b/depends/settings/src/stubkeyring.cpp @@ -27,7 +27,7 @@ QString scramble(QString in_) { QByteArray in = in_.toUtf8(); QByteArray out; - for (int i = 0; i #include @@ -33,8 +32,10 @@ * @brief commandline parsing and processing utilities */ -namespace Util { -namespace Commandline { +namespace Util +{ +namespace Commandline +{ /** * @brief split a string into argv items like a shell would do @@ -52,13 +53,13 @@ namespace FlagStyle { enum Enum { - GNU, /**< --option and -o (GNU Style) */ - Unix, /**< -option and -o (Unix Style) */ + 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 + Default = GNU #endif }; } @@ -66,17 +67,17 @@ enum Enum /** * @brief The ArgumentStyle enum */ -namespace ArgumentStyle +namespace ArgumentStyle { enum Enum { - Space, /**< --option=value */ - Equals, /**< --option value */ + Space, /**< --option=value */ + Equals, /**< --option value */ SpaceAndEquals, /**< --option[= ]value */ #ifdef Q_OS_WIN32 Default = Equals #else - Default = SpaceAndEquals + Default = SpaceAndEquals #endif }; } @@ -101,47 +102,47 @@ public: * @param flagStyle the FlagStyle to use in this Parser * @param argStyle the ArgumentStyle to use in this Parser */ - Parser(FlagStyle::Enum flagStyle = FlagStyle::Default, + 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 @@ -149,7 +150,7 @@ public: * @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 @@ -158,7 +159,7 @@ public: * 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 @@ -168,7 +169,7 @@ public: * 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 @@ -177,7 +178,7 @@ public: * @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 @@ -185,21 +186,21 @@ public: * @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 parse(QStringList argv); - + /** * @brief clear all definitions */ void clear(); - + ~Parser(); - + private: FlagStyle::Enum m_flagStyle; ArgumentStyle::Enum m_argStyle; @@ -209,16 +210,18 @@ private: otSwitch, otOption }; - + // Important: the common part MUST BE COMMON ON ALL THREE structs - struct CommonDef { + struct CommonDef + { QString name; QString doc; QString metavar; QVariant def; }; - - struct OptionDef { + + struct OptionDef + { // common QString name; QString doc; @@ -228,8 +231,9 @@ private: OptionType type; QChar flag; }; - - struct PositionalDef { + + struct PositionalDef + { // common QString name; QString doc; @@ -238,17 +242,14 @@ private: // positional bool required; }; - + QHash m_options; QHash m_flags; QHash m_params; QList m_positionals; QList m_optionList; - + void getPrefix(QString &opt, QString &flag); }; - } } - -#endif // CMDUTILS_H diff --git a/depends/util/include/libutil_config.h b/depends/util/include/libutil_config.h index 914337ed..56b33b74 100644 --- a/depends/util/include/libutil_config.h +++ b/depends/util/include/libutil_config.h @@ -3,7 +3,7 @@ * 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 @@ -18,12 +18,11 @@ #include #ifdef LIBUTIL_STATIC - #define LIBUTIL_EXPORT +#define LIBUTIL_EXPORT +#else +#ifdef LIBUTIL_LIBRARY +#define LIBUTIL_EXPORT Q_DECL_EXPORT #else - #ifdef LIBUTIL_LIBRARY - #define LIBUTIL_EXPORT Q_DECL_EXPORT - #else - #define LIBUTIL_EXPORT Q_DECL_IMPORT - #endif +#define LIBUTIL_EXPORT Q_DECL_IMPORT +#endif #endif - diff --git a/depends/util/include/osutils.h b/depends/util/include/osutils.h index c5d4bb61..d615d31f 100644 --- a/depends/util/include/osutils.h +++ b/depends/util/include/osutils.h @@ -3,7 +3,7 @@ * 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 @@ -13,17 +13,14 @@ * limitations under the License. */ -#ifndef OSUTILS_H -#define OSUTILS_H +#pragma once #include #if defined _WIN32 | defined _WIN64 -#define WINDOWS 1 -#elif __APPLE__ & __MACH__ +#define WINDOWS 1 +#elif __APPLE__ &__MACH__ #define OSX 1 #elif __linux__ #define LINUX 1 #endif - -#endif // OSUTILS_H diff --git a/depends/util/include/pathutils.h b/depends/util/include/pathutils.h index c892c115..45c2a6de 100644 --- a/depends/util/include/pathutils.h +++ b/depends/util/include/pathutils.h @@ -3,7 +3,7 @@ * 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 @@ -13,8 +13,7 @@ * limitations under the License. */ -#ifndef PATHUTILS_H -#define PATHUTILS_H +#pragma once #include @@ -27,10 +26,10 @@ LIBUTIL_EXPORT QString AbsolutePath(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) */ QString NormalizePath(QString path); @@ -54,9 +53,7 @@ LIBUTIL_EXPORT bool ensureFolderPathExists(QString filenamepath); LIBUTIL_EXPORT bool copyPath(QString src, QString dst); /// Opens the given file in the default application. -LIBUTIL_EXPORT void openFileInDefaultProgram ( QString filename ); +LIBUTIL_EXPORT void openFileInDefaultProgram(QString filename); /// Opens the given directory in the default application. -LIBUTIL_EXPORT void openDirInDefaultProgram ( QString dirpath, bool ensureExists = false ); - -#endif // PATHUTILS_H +LIBUTIL_EXPORT void openDirInDefaultProgram(QString dirpath, bool ensureExists = false); diff --git a/depends/util/include/siglist.h b/depends/util/include/siglist.h deleted file mode 100644 index 24b1a889..00000000 --- a/depends/util/include/siglist.h +++ /dev/null @@ -1,129 +0,0 @@ -/* Copyright 2013 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. - */ - -#ifndef SIGLIST_H -#define SIGLIST_H - -#include -#include - -// A QList that allows emitting signals when the list changes. -// Since QObject doesn't support templates, to use this class with a -// certain type, you should create a class deriving from SigList and then -// call the DEFINE_SIGLIST_SIGNALS(T) and SETUP_SIGLIST_SIGNALS(T) macros. -template -class SigList : public QList -{ -public: - explicit SigList() : QList() {} - - virtual void append(const T &value); - virtual void append(const QList &other); - - virtual void clear(); - - virtual void erase(typename QList::iterator pos); - virtual void erase(typename QList::iterator first, typename QList::iterator last); - - virtual void insert(int i, const T &t); - virtual void insert(typename QList::iterator before, const T &t); - - virtual void move(int from, int to); - - virtual void pop_back() { takeLast(); } - virtual void pop_front() { takeFirst(); } - - virtual void push_back(const T &t) { append(t); } - virtual void push_front(const T &t) { prepend(t); } - - virtual void prepend(const T &t); - - virtual int removeAll(const T &t); - virtual bool removeOne(const T &t); - - virtual void removeAt(int i) { takeAt(i); } - virtual void removeFirst() { takeFirst(); } - virtual void removeLast() { takeLast(); } - - virtual void swap(QList &other); - virtual void swap(int i, int j); - - virtual T takeAt(int i); - virtual T takeFirst(); - virtual T takeLast(); - - virtual QList &operator +=(const QList &other) { append(other); return *this; } - virtual QList &operator +=(const T &value) { append(value); return *this; } - virtual QList &operator <<(const QList &other) { append(other); return *this; } - virtual QList &operator <<(const T &value) { append(value); return *this; } - - virtual QList &operator =(const QList &other); - -protected: - // Signal emitted after an item is added to the list. - // Contains a reference to item and the item's new index. - virtual void onItemAdded(const T &item, int index) = 0; - - // Signal emitted after multiple items are added to the list at once. - // The items parameter is a const reference to a QList of the items that - // were added. - // The firstIndex parameter is the new index of the first item added. - virtual void onItemsAdded(const QList &items, int firstIndex) = 0; - - // Signal emitted after an item is removed to the list. - // Contains a reference to the item and the item's old index. - virtual void onItemRemoved(const T &item, int index) = 0; - - // Signal emitted after multiple items are removed from the list at once. - // The items parameter is a const reference to a QList of the items that - // were added. - // The firstIndex parameter is the new index of the first item added. - virtual void onItemsRemoved(const QList &items, int firstIndex) = 0; - - // Signal emitted after an item is moved to another index. - // Contains the item, the old index, and the new index. - virtual void onItemMoved(const T &item, int oldIndex, int newIndex) = 0; - - // Signal emitted after an operation that changes the whole list occurs. - // This signal should be treated as if all data in the entire list was cleared - // and new data added in its place. - virtual void onInvalidated() = 0; -}; - -// Defines the signals for a SigList -#define DEFINE_SIGLIST_SIGNALS(TYPE) \ - Q_SIGNAL void itemAdded(TYPE const &item, int index);\ - Q_SIGNAL void itemsAdded(const QList &items, int firstIndex);\ - Q_SIGNAL void itemRemoved(TYPE const &item, int index);\ - Q_SIGNAL void itemsRemoved(const QList &items, int firstIndex);\ - Q_SIGNAL void itemMoved(TYPE const &item, int oldIndex, int newIndex);\ - Q_SIGNAL void invalidated(); - -// Overrides the onItem* functions and causes them to emit their corresponding -// signals. -#define SETUP_SIGLIST_SIGNALS(TYPE) \ - virtual void onItemAdded(TYPE const &item, int index)\ - { emit itemAdded(item, index); }\ - virtual void onItemsAdded(const QList &items, int firstIndex)\ - { emit itemsAdded(items, firstIndex); }\ - virtual void onItemRemoved(TYPE const &item, int index)\ - { emit itemRemoved(item, index); }\ - virtual void onItemsRemoved(const QList &items, int firstIndex)\ - { emit itemsRemoved(items, firstIndex); }\ - virtual void onItemMoved(TYPE const &item, int oldIndex, int newIndex)\ - { emit itemMoved(item, oldIndex, newIndex); }\ - virtual void onInvalidated() { emit invalidated(); } - -#endif // SIGLIST_H diff --git a/depends/util/include/siglist_impl.h b/depends/util/include/siglist_impl.h deleted file mode 100644 index 5cdc632a..00000000 --- a/depends/util/include/siglist_impl.h +++ /dev/null @@ -1,156 +0,0 @@ -/* Copyright 2013 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 "siglist.h" - -template -void SigList::append(const T &value) -{ - QList::append(value); - onItemAdded(value, QList::length() - 1); -} - -template -void SigList::prepend(const T &value) -{ - QList::prepend(value); - onItemAdded(value, 0); -} - -template -void SigList::append(const QList &other) -{ - int index = QList::length(); - QList::append(other); - onItemsAdded(other, index); -} - -template -void SigList::clear() -{ - QList::clear(); - onInvalidated(); -} - -template -void SigList::erase(typename QList::iterator pos) -{ - T value = *pos; - int index = QList::indexOf(*pos); - QList::erase(pos); - onItemRemoved(value, index); -} - -template -void SigList::erase(typename QList::iterator first, typename QList::iterator last) -{ - QList removedValues; - int firstIndex = QList::indexOf(*first); - - for (auto iter = first; iter < last; iter++) - { - removedValues << *iter; - QList::erase(iter); - } - - onItemsRemoved(removedValues, firstIndex); -} - -template -void SigList::insert(int i, const T &t) -{ - QList::insert(i, t); - onItemAdded(t, i); -} - -template -void SigList::insert(typename QList::iterator before, const T &t) -{ - QList::insert(before, t); - onItemAdded(t, QList::indexOf(t)); -} - -template -void SigList::move(int from, int to) -{ - const T &item = QList::at(from); - QList::move(from, to); - onItemMoved(item, from, to); -} - -template -int SigList::removeAll(const T &t) -{ - int retVal = QList::removeAll(t); - onInvalidated(); - return retVal; -} - -template -bool SigList::removeOne(const T &t) -{ - int index = QList::indexOf(t); - if (QList::removeOne(t)) - { - onItemRemoved(t, index); - return true; - } - return false; -} - -template -void SigList::swap(QList &other) -{ - QList::swap(other); - onInvalidated(); -} - -template -void SigList::swap(int i, int j) -{ - const T &item1 = QList::at(i); - const T &item2 = QList::at(j); - QList::swap(i, j); - onItemMoved(item1, i, j); - onItemMoved(item2, j, i); -} - -template -T SigList::takeAt(int i) -{ - T val = QList::takeAt(i); - onItemRemoved(val, i); - return val; -} - -template -T SigList::takeFirst() -{ - return takeAt(0); -} - -template -T SigList::takeLast() -{ - return takeAt(QList::length() - 1); -} - -template -QList &SigList::operator =(const QList &other) -{ - QList::operator =(other); - onInvalidated(); - return *this; -} diff --git a/depends/util/include/userutils.h b/depends/util/include/userutils.h index 4f2760b1..6ce08bce 100644 --- a/depends/util/include/userutils.h +++ b/depends/util/include/userutils.h @@ -1,5 +1,4 @@ -#ifndef USERUTILS_H -#define USERUTILS_H +#pragma once #include @@ -13,7 +12,6 @@ LIBUTIL_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 -LIBUTIL_EXPORT bool createShortCut(QString location, QString dest, QStringList args, QString name, QString iconLocation); +LIBUTIL_EXPORT bool createShortCut(QString location, QString dest, QStringList args, + QString name, QString iconLocation); } - -#endif // USERUTILS_H diff --git a/depends/util/src/cmdutils.cpp b/depends/util/src/cmdutils.cpp index b9cab717..43a0bcde 100644 --- a/depends/util/src/cmdutils.cpp +++ b/depends/util/src/cmdutils.cpp @@ -21,8 +21,10 @@ * @file libutil/src/cmdutils.cpp */ -namespace Util { -namespace Commandline { +namespace Util +{ +namespace Commandline +{ // commandline splitter QStringList splitArgs(QString args) @@ -31,10 +33,10 @@ QStringList splitArgs(QString args) QString current; bool escape = false; QChar inquotes; - for (int i=0; itype = 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); @@ -120,13 +121,13 @@ 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); @@ -136,13 +137,13 @@ 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; } @@ -151,7 +152,7 @@ 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()) @@ -164,7 +165,7 @@ void Parser::addShortOpt(QString name, QChar flag) 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; @@ -175,14 +176,14 @@ 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 it2(m_positionals); - while(it2.hasNext()) + while (it2.hasNext()) { PositionalDef *param = it2.next(); help << " " << param->metavar; @@ -190,17 +191,17 @@ QString Parser::compileHelp(QString progName, int helpIndent, bool useFlags) 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 it(m_optionList); - while(it.hasNext()) + while (it.hasNext()) { OptionDef *option = it.next(); help << " "; @@ -213,7 +214,8 @@ QString Parser::compileHelp(QString progName, int helpIndent, bool useFlags) help << optPrefix << option->name; if (option->type == otOption) { - QString arg = QString("%1%2").arg(((m_argStyle == ArgumentStyle::Equals) ? "=" : " "), option->metavar); + QString arg = QString("%1%2").arg( + ((m_argStyle == ArgumentStyle::Equals) ? "=" : " "), option->metavar); nameLength += arg.length(); help << arg; } @@ -221,7 +223,7 @@ QString Parser::compileHelp(QString progName, int helpIndent, bool useFlags) help << option->doc << "\r\n"; } } - + return help.join(""); } @@ -229,13 +231,13 @@ QString Parser::compileUsage(QString progName, bool useFlags) { QStringList usage; usage << "Usage: " << progName; - + QString optPrefix, flagPrefix; getPrefix(optPrefix, flagPrefix); - + // options QListIterator it(m_optionList); - while(it.hasNext()) + while (it.hasNext()) { OptionDef *option = it.next(); usage << " ["; @@ -244,20 +246,20 @@ QString Parser::compileUsage(QString progName, bool useFlags) else usage << optPrefix << option->name; if (option->type == otOption) - usage << ((m_argStyle == ArgumentStyle::Equals) ? "=" : " ") << option->metavar; + usage << ((m_argStyle == ArgumentStyle::Equals) ? "=" : " ") << option->metavar; usage << "]"; } - + // arguments QListIterator it2(m_positionals); - while(it2.hasNext()) + while (it2.hasNext()) { PositionalDef *param = it2.next(); usage << " " << (param->required ? "<" : "["); usage << param->metavar; usage << (param->required ? ">" : "]"); } - + return usage.join(""); } @@ -265,59 +267,63 @@ QString Parser::compileUsage(QString progName, bool useFlags) QHash Parser::parse(QStringList argv) { QHash map; - + QStringListIterator it(argv); QString programName = it.next(); - + QString optionPrefix; QString flagPrefix; QListIterator positionals(m_positionals); QStringList expecting; - + getPrefix(optionPrefix, flagPrefix); - + while (it.hasNext()) { QString arg = it.next(); - + if (!expecting.isEmpty()) - // we were expecting an argument + // 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)); - + 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 + // we have an option { - //qDebug("Found option %s", qPrintable(arg)); - + // 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("=")) + + if ((m_argStyle == ArgumentStyle::Equals || + m_argStyle == ArgumentStyle::SpaceAndEquals) && + name.contains("=")) { int i = name.indexOf("="); - equals = name.mid(i+1); + 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)); - + 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) + else // if (option->type == otOption) { if (m_argStyle == ArgumentStyle::Space) expecting.append(name); @@ -326,85 +332,94 @@ QHash Parser::parse(QStringList argv) else if (m_argStyle == ArgumentStyle::SpaceAndEquals) expecting.append(name); else - throw ParsingError(QString("Option %2%1 reqires an argument.").arg(name, optionPrefix)); + 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) + // we have (a) flag(s) { - //qDebug("Found flags %s", qPrintable(arg)); - + // 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("=")) + + if ((m_argStyle == ArgumentStyle::Equals || + m_argStyle == ArgumentStyle::SpaceAndEquals) && + flags.contains("=")) { int i = flags.indexOf("="); - equals = flags.mid(i+1); + 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)); - + 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) + else // if (option->type == otOption) { if (m_argStyle == ArgumentStyle::Space) expecting.append(option->name); else if (!equals.isNull()) - if (i == flags.length()-1) + 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)); + 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)); + 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)); - + 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)); + throw ParsingError( + QString("Missing required positional argument '%1'").arg(param->name)); else map[param->name] = param->def; } - + // fill out gaps QListIterator iter(m_optionList); while (iter.hasNext()) @@ -413,27 +428,27 @@ QHash Parser::parse(QStringList argv) if (!map.contains(option->name)) map[option->name] = option->def; } - + return map; } -//clear defs +// clear defs void Parser::clear() { m_flags.clear(); m_params.clear(); m_options.clear(); - + QMutableListIterator it(m_optionList); - while(it.hasNext()) + while (it.hasNext()) { OptionDef *option = it.next(); it.remove(); delete option; } - + QMutableListIterator it2(m_positionals); - while(it2.hasNext()) + while (it2.hasNext()) { PositionalDef *arg = it2.next(); it2.remove(); @@ -441,31 +456,30 @@ void Parser::clear() } } -//Destructor +// Destructor Parser::~Parser() { clear(); } -//getPrefix +// 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 { + // else if (m_flagStyle == FlagStyle::GNU) + else + { opt = "--"; flag = "-"; } } // ParsingError -ParsingError::ParsingError(const QString &what) -:std::runtime_error(what.toStdString()) +ParsingError::ParsingError(const QString &what) : std::runtime_error(what.toStdString()) { } - } } diff --git a/depends/util/src/osutils.cpp b/depends/util/src/osutils.cpp deleted file mode 100644 index 9a85d1e5..00000000 --- a/depends/util/src/osutils.cpp +++ /dev/null @@ -1,19 +0,0 @@ -/* Copyright 2013 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 "include/osutils.h" - -#include -#include diff --git a/depends/util/src/pathutils.cpp b/depends/util/src/pathutils.cpp index ad8d7566..485d03e8 100644 --- a/depends/util/src/pathutils.cpp +++ b/depends/util/src/pathutils.cpp @@ -3,7 +3,7 @@ * 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 @@ -41,7 +41,7 @@ QString AbsolutePath(QString path) /** * Normalize path - * + * * Any paths inside the current directory will be normalized to relative paths (to current) * Other paths will be made absolute */ @@ -85,7 +85,7 @@ QString DirNameFromString(QString string, QString inDir) { num++; dirName = RemoveInvalidFilenameChars(dirName, '-') + QString::number(num); - + // If it's over 9000 if (num > 9000) return ""; @@ -95,59 +95,56 @@ QString DirNameFromString(QString string, QString inDir) bool ensureFilePathExists(QString filenamepath) { - QFileInfo a ( filenamepath ); + QFileInfo a(filenamepath); QDir dir; QString ensuredPath = a.path(); - bool success = dir.mkpath ( ensuredPath ); + bool success = dir.mkpath(ensuredPath); return success; } bool ensureFolderPathExists(QString foldernamepath) { - QFileInfo a ( foldernamepath ); + QFileInfo a(foldernamepath); QDir dir; QString ensuredPath = a.filePath(); - bool success = dir.mkpath ( ensuredPath ); + bool success = dir.mkpath(ensuredPath); return success; } - bool copyPath(QString src, QString dst) { QDir dir(src); if (!dir.exists()) return false; - if(!ensureFolderPathExists(dst)) + if (!ensureFolderPathExists(dst)) return false; - foreach (QString d, dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot)) + foreach(QString d, dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot)) { QString inner_src = src + QDir::separator() + d; QString inner_dst = dst + QDir::separator() + d; copyPath(inner_src, inner_dst); } - foreach (QString f, dir.entryList(QDir::Files)) + foreach(QString f, dir.entryList(QDir::Files)) { QFile::copy(src + QDir::separator() + f, dst + QDir::separator() + f); } return true; } -void openDirInDefaultProgram ( QString path, bool ensureExists ) +void openDirInDefaultProgram(QString path, bool ensureExists) { QDir parentPath; - QDir dir( path ); - if(!dir.exists()) + QDir dir(path); + if (!dir.exists()) { parentPath.mkpath(dir.absolutePath()); } - QDesktopServices::openUrl ( "file:///" + dir.absolutePath() ); + QDesktopServices::openUrl("file:///" + dir.absolutePath()); } -void openFileInDefaultProgram ( QString filename ) +void openFileInDefaultProgram(QString filename) { - QDesktopServices::openUrl ( "file:///" + QFileInfo ( filename ).absolutePath() ); + QDesktopServices::openUrl("file:///" + QFileInfo(filename).absolutePath()); } - - diff --git a/depends/util/src/userutils.cpp b/depends/util/src/userutils.cpp index b70841ed..060a58e9 100644 --- a/depends/util/src/userutils.cpp +++ b/depends/util/src/userutils.cpp @@ -23,37 +23,37 @@ 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%08X", hres); return hres; } } - - - IShellLink* link; - hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (LPVOID*)&link); - + + IShellLink *link; + hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, + (LPVOID *)&link); + if (SUCCEEDED(hres)) { - IPersistFile* persistFile; - + IPersistFile *persistFile; + link->SetPath(targetPath); link->SetArguments(args); - - hres = link->QueryInterface(IID_IPersistFile, (LPVOID*)&persistFile); + + 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(); } @@ -70,51 +70,55 @@ QString Util::getDesktopDir() } // Cross-platform Shortcut creation -bool Util::createShortCut(QString location, QString dest, QStringList args, QString name, QString icon) +bool Util::createShortCut(QString location, QString dest, QStringList args, QString name, + QString icon) { #if LINUX location = PathCombine(location, name + ".desktop"); qDebug("location: %s", qPrintable(location)); - + 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 << "[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); - + + f.setPermissions(f.permissions() | QFileDevice::ExeOwner | QFileDevice::ExeGroup | + QFileDevice::ExeOther); + return true; #elif WINDOWS // 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)); + // 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!"); diff --git a/depends/xz-embedded/include/xz.h b/depends/xz-embedded/include/xz.h index 49a96f7b..eef8ef69 100644 --- a/depends/xz-embedded/include/xz.h +++ b/depends/xz-embedded/include/xz.h @@ -12,11 +12,11 @@ #define XZ_H #ifdef __KERNEL__ -# include -# include +#include +#include #else -# include -# include +#include +#include #endif #ifdef __cplusplus @@ -37,10 +37,9 @@ extern "C" { #define XZ_DEC_SPARC */ - /* In Linux, this is used to make extern functions static when needed. */ #ifndef XZ_EXTERN -# define XZ_EXTERN extern +#define XZ_EXTERN extern #endif /** @@ -68,7 +67,8 @@ extern "C" { * with support for all operation modes, but the preboot code may * be built with fewer features to minimize code size. */ -enum xz_mode { +enum xz_mode +{ XZ_SINGLE, XZ_PREALLOC, XZ_DYNALLOC @@ -124,7 +124,8 @@ enum xz_mode { * (relatively) clear that the compressed input is truncated, XZ_DATA_ERROR * is used instead of XZ_BUF_ERROR. */ -enum xz_ret { +enum xz_ret +{ XZ_OK, XZ_STREAM_END, XZ_UNSUPPORTED_CHECK, @@ -152,7 +153,8 @@ enum xz_ret { * Only the contents of the output buffer from out[out_pos] onward, and * the variables in_pos and out_pos are modified by the XZ code. */ -struct xz_buf { +struct xz_buf +{ const uint8_t *in; size_t in_pos; size_t in_size; @@ -259,11 +261,11 @@ XZ_EXTERN void xz_dec_end(struct xz_dec *s); * care about the functions below. */ #ifndef XZ_INTERNAL_CRC32 -# ifdef __KERNEL__ -# define XZ_INTERNAL_CRC32 0 -# else -# define XZ_INTERNAL_CRC32 1 -# endif +#ifdef __KERNEL__ +#define XZ_INTERNAL_CRC32 0 +#else +#define XZ_INTERNAL_CRC32 1 +#endif #endif /* @@ -271,15 +273,15 @@ XZ_EXTERN void xz_dec_end(struct xz_dec *s); * implementation is needed too. */ #ifndef XZ_USE_CRC64 -# undef XZ_INTERNAL_CRC64 -# define XZ_INTERNAL_CRC64 0 +#undef XZ_INTERNAL_CRC64 +#define XZ_INTERNAL_CRC64 0 #endif #ifndef XZ_INTERNAL_CRC64 -# ifdef __KERNEL__ -# error Using CRC64 in the kernel has not been implemented. -# else -# define XZ_INTERNAL_CRC64 1 -# endif +#ifdef __KERNEL__ +#error Using CRC64 in the kernel has not been implemented. +#else +#define XZ_INTERNAL_CRC64 1 +#endif #endif #if XZ_INTERNAL_CRC32 diff --git a/depends/xz-embedded/src/xz_config.h b/depends/xz-embedded/src/xz_config.h index eb9dac1a..40805b75 100644 --- a/depends/xz-embedded/src/xz_config.h +++ b/depends/xz-embedded/src/xz_config.h @@ -27,11 +27,11 @@ */ #ifdef _MSC_VER typedef unsigned char bool; -# define true 1 -# define false 0 -# define inline __inline +#define true 1 +#define false 0 +#define inline __inline #else -# include +#include #endif #include @@ -48,7 +48,7 @@ typedef unsigned char bool; #define memzero(buf, size) memset(buf, 0, size) #ifndef min -# define min(x, y) ((x) < (y) ? (x) : (y)) +#define min(x, y) ((x) < (y) ? (x) : (y)) #endif #define min_t(type, x, y) min(x, y) @@ -63,32 +63,27 @@ typedef unsigned char bool; * so if you want to change it, you need to #undef it first. */ #ifndef __always_inline -# ifdef __GNUC__ -# define __always_inline \ - inline __attribute__((__always_inline__)) -# else -# define __always_inline inline -# endif +#ifdef __GNUC__ +#define __always_inline inline __attribute__((__always_inline__)) +#else +#define __always_inline inline +#endif #endif /* Inline functions to access unaligned unsigned 32-bit integers */ #ifndef get_unaligned_le32 static inline uint32_t get_unaligned_le32(const uint8_t *buf) { - return (uint32_t)buf[0] - | ((uint32_t)buf[1] << 8) - | ((uint32_t)buf[2] << 16) - | ((uint32_t)buf[3] << 24); + return (uint32_t)buf[0] | ((uint32_t)buf[1] << 8) | ((uint32_t)buf[2] << 16) | + ((uint32_t)buf[3] << 24); } #endif #ifndef get_unaligned_be32 static inline uint32_t get_unaligned_be32(const uint8_t *buf) { - return (uint32_t)(buf[0] << 24) - | ((uint32_t)buf[1] << 16) - | ((uint32_t)buf[2] << 8) - | (uint32_t)buf[3]; + return (uint32_t)(buf[0] << 24) | ((uint32_t)buf[1] << 16) | ((uint32_t)buf[2] << 8) | + (uint32_t)buf[3]; } #endif @@ -118,7 +113,7 @@ static inline void put_unaligned_be32(uint32_t val, uint8_t *buf) * could save a few bytes in code size. */ #ifndef get_le32 -# define get_le32 get_unaligned_le32 +#define get_le32 get_unaligned_le32 #endif #endif diff --git a/depends/xz-embedded/src/xz_crc32.c b/depends/xz-embedded/src/xz_crc32.c index 34532d14..c412662b 100644 --- a/depends/xz-embedded/src/xz_crc32.c +++ b/depends/xz-embedded/src/xz_crc32.c @@ -22,7 +22,7 @@ * See for details. */ #ifndef STATIC_RW_DATA -# define STATIC_RW_DATA static +#define STATIC_RW_DATA static #endif STATIC_RW_DATA uint32_t xz_crc32_table[256]; @@ -35,7 +35,8 @@ XZ_EXTERN void xz_crc32_init(void) uint32_t j; uint32_t r; - for (i = 0; i < 256; ++i) { + for (i = 0; i < 256; ++i) + { r = i; for (j = 0; j < 8; ++j) r = (r >> 1) ^ (poly & ~((r & 1) - 1)); @@ -50,7 +51,8 @@ XZ_EXTERN uint32_t xz_crc32(const uint8_t *buf, size_t size, uint32_t crc) { crc = ~crc; - while (size != 0) { + while (size != 0) + { crc = xz_crc32_table[*buf++ ^ (crc & 0xFF)] ^ (crc >> 8); --size; } diff --git a/depends/xz-embedded/src/xz_crc64.c b/depends/xz-embedded/src/xz_crc64.c index ca1caee8..4794b9d3 100644 --- a/depends/xz-embedded/src/xz_crc64.c +++ b/depends/xz-embedded/src/xz_crc64.c @@ -13,7 +13,7 @@ #include "xz_private.h" #ifndef STATIC_RW_DATA -# define STATIC_RW_DATA static +#define STATIC_RW_DATA static #endif STATIC_RW_DATA uint64_t xz_crc64_table[256]; @@ -26,7 +26,8 @@ XZ_EXTERN void xz_crc64_init(void) uint32_t j; uint64_t r; - for (i = 0; i < 256; ++i) { + for (i = 0; i < 256; ++i) + { r = i; for (j = 0; j < 8; ++j) r = (r >> 1) ^ (poly & ~((r & 1) - 1)); @@ -41,7 +42,8 @@ XZ_EXTERN uint64_t xz_crc64(const uint8_t *buf, size_t size, uint64_t crc) { crc = ~crc; - while (size != 0) { + while (size != 0) + { crc = xz_crc64_table[*buf++ ^ (crc & 0xFF)] ^ (crc >> 8); --size; } diff --git a/depends/xz-embedded/src/xz_dec_bcj.c b/depends/xz-embedded/src/xz_dec_bcj.c index a768e6d2..9ffda3bd 100644 --- a/depends/xz-embedded/src/xz_dec_bcj.c +++ b/depends/xz-embedded/src/xz_dec_bcj.c @@ -16,15 +16,17 @@ */ #ifdef XZ_DEC_BCJ -struct xz_dec_bcj { +struct xz_dec_bcj +{ /* Type of the BCJ filter being used */ - enum { - BCJ_X86 = 4, /* x86 or x86-64 */ - BCJ_POWERPC = 5, /* Big endian only */ - BCJ_IA64 = 6, /* Big or little endian */ - BCJ_ARM = 7, /* Little endian only */ - BCJ_ARMTHUMB = 8, /* Little endian only */ - BCJ_SPARC = 9 /* Big or little endian */ + enum + { + BCJ_X86 = 4, /* x86 or x86-64 */ + BCJ_POWERPC = 5, /* Big endian only */ + BCJ_IA64 = 6, /* Big or little endian */ + BCJ_ARM = 7, /* Little endian only */ + BCJ_ARMTHUMB = 8, /* Little endian only */ + BCJ_SPARC = 9 /* Big or little endian */ } type; /* @@ -52,7 +54,8 @@ struct xz_dec_bcj { size_t out_pos; size_t out_size; - struct { + struct + { /* Amount of already filtered data in the beginning of buf */ size_t filtered; @@ -87,13 +90,13 @@ static inline int bcj_x86_test_msbyte(uint8_t b) static size_t bcj_x86(struct xz_dec_bcj *s, uint8_t *buf, size_t size) { - static const bool mask_to_allowed_status[8] - = { true, true, true, false, true, false, false, false }; + static const bool mask_to_allowed_status[8] = {true, true, true, false, + true, false, false, false}; - static const uint8_t mask_to_bit_num[8] = { 0, 1, 2, 2, 3, 3, 3, 3 }; + static const uint8_t mask_to_bit_num[8] = {0, 1, 2, 2, 3, 3, 3, 3}; size_t i; - size_t prev_pos = (size_t)-1; + size_t prev_pos = (size_t) - 1; uint32_t prev_mask = s->x86_prev_mask; uint32_t src; uint32_t dest; @@ -104,19 +107,24 @@ static size_t bcj_x86(struct xz_dec_bcj *s, uint8_t *buf, size_t size) return 0; size -= 4; - for (i = 0; i < size; ++i) { + for (i = 0; i < size; ++i) + { if ((buf[i] & 0xFE) != 0xE8) continue; prev_pos = i - prev_pos; - if (prev_pos > 3) { + if (prev_pos > 3) + { prev_mask = 0; - } else { + } + else + { prev_mask = (prev_mask << (prev_pos - 1)) & 7; - if (prev_mask != 0) { + if (prev_mask != 0) + { b = buf[i + 4 - mask_to_bit_num[prev_mask]]; - if (!mask_to_allowed_status[prev_mask] - || bcj_x86_test_msbyte(b)) { + if (!mask_to_allowed_status[prev_mask] || bcj_x86_test_msbyte(b)) + { prev_pos = i; prev_mask = (prev_mask << 1) | 1; continue; @@ -126,9 +134,11 @@ static size_t bcj_x86(struct xz_dec_bcj *s, uint8_t *buf, size_t size) prev_pos = i; - if (bcj_x86_test_msbyte(buf[i + 4])) { + if (bcj_x86_test_msbyte(buf[i + 4])) + { src = get_unaligned_le32(buf + i + 1); - while (true) { + while (true) + { dest = src - (s->pos + (uint32_t)i + 5); if (prev_mask == 0) break; @@ -145,7 +155,9 @@ static size_t bcj_x86(struct xz_dec_bcj *s, uint8_t *buf, size_t size) dest |= (uint32_t)0 - (dest & 0x01000000); put_unaligned_le32(dest, buf + i + 1); i += 4; - } else { + } + else + { prev_mask = (prev_mask << 1) | 1; } } @@ -162,9 +174,11 @@ static size_t bcj_powerpc(struct xz_dec_bcj *s, uint8_t *buf, size_t size) size_t i; uint32_t instr; - for (i = 0; i + 4 <= size; i += 4) { + for (i = 0; i + 4 <= size; i += 4) + { instr = get_unaligned_be32(buf + i); - if ((instr & 0xFC000003) == 0x48000001) { + if ((instr & 0xFC000003) == 0x48000001) + { instr &= 0x03FFFFFC; instr -= s->pos + (uint32_t)i; instr &= 0x03FFFFFC; @@ -180,12 +194,8 @@ static size_t bcj_powerpc(struct xz_dec_bcj *s, uint8_t *buf, size_t size) #ifdef XZ_DEC_IA64 static size_t bcj_ia64(struct xz_dec_bcj *s, uint8_t *buf, size_t size) { - static const uint8_t branch_table[32] = { - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 4, 4, 6, 6, 0, 0, 7, 7, - 4, 4, 0, 0, 4, 4, 0, 0 - }; + static const uint8_t branch_table[32] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 4, 4, 6, 6, 0, 0, 7, 7, 4, 4, 0, 0, 4, 4, 0, 0}; /* * The local variables take a little bit stack space, but it's less @@ -219,9 +229,11 @@ static size_t bcj_ia64(struct xz_dec_bcj *s, uint8_t *buf, size_t size) /* Instruction normalized with bit_res for easier manipulation */ uint64_t norm; - for (i = 0; i + 16 <= size; i += 16) { + for (i = 0; i + 16 <= size; i += 16) + { mask = branch_table[buf[i] & 0x1F]; - for (slot = 0, bit_pos = 5; slot < 3; ++slot, bit_pos += 41) { + for (slot = 0, bit_pos = 5; slot < 3; ++slot, bit_pos += 41) + { if (((mask >> slot) & 1) == 0) continue; @@ -229,13 +241,12 @@ static size_t bcj_ia64(struct xz_dec_bcj *s, uint8_t *buf, size_t size) bit_res = bit_pos & 7; instr = 0; for (j = 0; j < 6; ++j) - instr |= (uint64_t)(buf[i + j + byte_pos]) - << (8 * j); + instr |= (uint64_t)(buf[i + j + byte_pos]) << (8 * j); norm = instr >> bit_res; - if (((norm >> 37) & 0x0F) == 0x05 - && ((norm >> 9) & 0x07) == 0) { + if (((norm >> 37) & 0x0F) == 0x05 && ((norm >> 9) & 0x07) == 0) + { addr = (norm >> 13) & 0x0FFFFF; addr |= ((uint32_t)(norm >> 36) & 1) << 20; addr <<= 4; @@ -244,15 +255,13 @@ static size_t bcj_ia64(struct xz_dec_bcj *s, uint8_t *buf, size_t size) norm &= ~((uint64_t)0x8FFFFF << 13); norm |= (uint64_t)(addr & 0x0FFFFF) << 13; - norm |= (uint64_t)(addr & 0x100000) - << (36 - 20); + norm |= (uint64_t)(addr & 0x100000) << (36 - 20); instr &= (1 << bit_res) - 1; instr |= norm << bit_res; for (j = 0; j < 6; j++) - buf[i + j + byte_pos] - = (uint8_t)(instr >> (8 * j)); + buf[i + j + byte_pos] = (uint8_t)(instr >> (8 * j)); } } } @@ -267,10 +276,12 @@ static size_t bcj_arm(struct xz_dec_bcj *s, uint8_t *buf, size_t size) size_t i; uint32_t addr; - for (i = 0; i + 4 <= size; i += 4) { - if (buf[i + 3] == 0xEB) { - addr = (uint32_t)buf[i] | ((uint32_t)buf[i + 1] << 8) - | ((uint32_t)buf[i + 2] << 16); + for (i = 0; i + 4 <= size; i += 4) + { + if (buf[i + 3] == 0xEB) + { + addr = + (uint32_t)buf[i] | ((uint32_t)buf[i + 1] << 8) | ((uint32_t)buf[i + 2] << 16); addr <<= 2; addr -= s->pos + (uint32_t)i + 8; addr >>= 2; @@ -290,13 +301,12 @@ static size_t bcj_armthumb(struct xz_dec_bcj *s, uint8_t *buf, size_t size) size_t i; uint32_t addr; - for (i = 0; i + 4 <= size; i += 2) { - if ((buf[i + 1] & 0xF8) == 0xF0 - && (buf[i + 3] & 0xF8) == 0xF8) { - addr = (((uint32_t)buf[i + 1] & 0x07) << 19) - | ((uint32_t)buf[i] << 11) - | (((uint32_t)buf[i + 3] & 0x07) << 8) - | (uint32_t)buf[i + 2]; + for (i = 0; i + 4 <= size; i += 2) + { + if ((buf[i + 1] & 0xF8) == 0xF0 && (buf[i + 3] & 0xF8) == 0xF8) + { + addr = (((uint32_t)buf[i + 1] & 0x07) << 19) | ((uint32_t)buf[i] << 11) | + (((uint32_t)buf[i + 3] & 0x07) << 8) | (uint32_t)buf[i + 2]; addr <<= 1; addr -= s->pos + (uint32_t)i + 4; addr >>= 1; @@ -318,14 +328,16 @@ static size_t bcj_sparc(struct xz_dec_bcj *s, uint8_t *buf, size_t size) size_t i; uint32_t instr; - for (i = 0; i + 4 <= size; i += 4) { + for (i = 0; i + 4 <= size; i += 4) + { instr = get_unaligned_be32(buf + i); - if ((instr >> 22) == 0x100 || (instr >> 22) == 0x1FF) { + if ((instr >> 22) == 0x100 || (instr >> 22) == 0x1FF) + { instr <<= 2; instr -= s->pos + (uint32_t)i; instr >>= 2; - instr = ((uint32_t)0x40000000 - (instr & 0x400000)) - | 0x40000000 | (instr & 0x3FFFFF); + instr = + ((uint32_t)0x40000000 - (instr & 0x400000)) | 0x40000000 | (instr & 0x3FFFFF); put_unaligned_be32(instr, buf + i); } } @@ -342,15 +354,15 @@ static size_t bcj_sparc(struct xz_dec_bcj *s, uint8_t *buf, size_t size) * pointers, which could be problematic in the kernel boot code, which must * avoid pointers to static data (at least on x86). */ -static void bcj_apply(struct xz_dec_bcj *s, - uint8_t *buf, size_t *pos, size_t size) +static void bcj_apply(struct xz_dec_bcj *s, uint8_t *buf, size_t *pos, size_t size) { size_t filtered; buf += *pos; size -= *pos; - switch (s->type) { + switch (s->type) + { #ifdef XZ_DEC_X86 case BCJ_X86: filtered = bcj_x86(s, buf, size); @@ -414,9 +426,8 @@ static void bcj_flush(struct xz_dec_bcj *s, struct xz_buf *b) * data in chunks of 1-16 bytes. To hide this issue, this function does * some buffering. */ -XZ_EXTERN enum xz_ret xz_dec_bcj_run(struct xz_dec_bcj *s, - struct xz_dec_lzma2 *lzma2, - struct xz_buf *b) +XZ_EXTERN enum xz_ret xz_dec_bcj_run(struct xz_dec_bcj *s, struct xz_dec_lzma2 *lzma2, + struct xz_buf *b) { size_t out_start; @@ -425,7 +436,8 @@ XZ_EXTERN enum xz_ret xz_dec_bcj_run(struct xz_dec_bcj *s, * immediatelly if we couldn't flush everything, or if the next * filter in the chain had already returned XZ_STREAM_END. */ - if (s->temp.filtered > 0) { + if (s->temp.filtered > 0) + { bcj_flush(s, b); if (s->temp.filtered > 0) return XZ_OK; @@ -446,14 +458,14 @@ XZ_EXTERN enum xz_ret xz_dec_bcj_run(struct xz_dec_bcj *s, * case where the output buffer is full and the next filter has no * more output coming but hasn't returned XZ_STREAM_END yet. */ - if (s->temp.size < b->out_size - b->out_pos || s->temp.size == 0) { + if (s->temp.size < b->out_size - b->out_pos || s->temp.size == 0) + { out_start = b->out_pos; memcpy(b->out + b->out_pos, s->temp.buf, s->temp.size); b->out_pos += s->temp.size; s->ret = xz_dec_lzma2_run(lzma2, b); - if (s->ret != XZ_STREAM_END - && (s->ret != XZ_OK || s->single_call)) + if (s->ret != XZ_STREAM_END && (s->ret != XZ_OK || s->single_call)) return s->ret; bcj_apply(s, b->out, &out_start, b->out_pos); @@ -487,7 +499,8 @@ XZ_EXTERN enum xz_ret xz_dec_bcj_run(struct xz_dec_bcj *s, * A mix of filtered and unfiltered data may be left in temp; it will * be taken care on the next call to this function. */ - if (b->out_pos < b->out_size) { + if (b->out_pos < b->out_size) + { /* Make b->out{,_pos,_size} temporarily point to s->temp. */ s->out = b->out; s->out_pos = b->out_pos; @@ -535,7 +548,8 @@ XZ_EXTERN struct xz_dec_bcj *xz_dec_bcj_create(bool single_call) XZ_EXTERN enum xz_ret xz_dec_bcj_reset(struct xz_dec_bcj *s, uint8_t id) { - switch (id) { + switch (id) + { #ifdef XZ_DEC_X86 case BCJ_X86: #endif diff --git a/depends/xz-embedded/src/xz_dec_lzma2.c b/depends/xz-embedded/src/xz_dec_lzma2.c index a6cdc969..3d7b9a2e 100644 --- a/depends/xz-embedded/src/xz_dec_lzma2.c +++ b/depends/xz-embedded/src/xz_dec_lzma2.c @@ -41,7 +41,8 @@ * in which the dictionary variables address the actual output * buffer directly. */ -struct dictionary { +struct dictionary +{ /* Beginning of the history buffer */ uint8_t *buf; @@ -92,7 +93,8 @@ struct dictionary { }; /* Range decoder */ -struct rc_dec { +struct rc_dec +{ uint32_t range; uint32_t code; @@ -112,7 +114,8 @@ struct rc_dec { }; /* Probabilities for a length decoder. */ -struct lzma_len_dec { +struct lzma_len_dec +{ /* Probability of match length being at least 10 */ uint16_t choice; @@ -129,7 +132,8 @@ struct lzma_len_dec { uint16_t high[LEN_HIGH_SYMBOLS]; }; -struct lzma_dec { +struct lzma_dec +{ /* Distances of latest four matches */ uint32_t rep0; uint32_t rep1; @@ -153,7 +157,7 @@ struct lzma_dec { */ uint32_t lc; uint32_t literal_pos_mask; /* (1 << lp) - 1 */ - uint32_t pos_mask; /* (1 << pb) - 1 */ + uint32_t pos_mask; /* (1 << pb) - 1 */ /* If 1, it's a match. Otherwise it's a single 8-bit literal. */ uint16_t is_match[STATES][POS_STATES_MAX]; @@ -211,9 +215,11 @@ struct lzma_dec { uint16_t literal[LITERAL_CODERS_MAX][LITERAL_CODER_SIZE]; }; -struct lzma2_dec { +struct lzma2_dec +{ /* Position in xz_dec_lzma2_run(). */ - enum lzma2_seq { + enum lzma2_seq + { SEQ_CONTROL, SEQ_UNCOMPRESSED_1, SEQ_UNCOMPRESSED_2, @@ -250,7 +256,8 @@ struct lzma2_dec { bool need_props; }; -struct xz_dec_lzma2 { +struct xz_dec_lzma2 +{ /* * The order below is important on x86 to reduce code size and * it shouldn't hurt on other platforms. Everything up to and @@ -269,7 +276,8 @@ struct xz_dec_lzma2 { * Temporary buffer which holds small number of input bytes between * decoder calls. See lzma2_lzma() for details. */ - struct { + struct + { uint32_t size; uint8_t buf[3 * LZMA_IN_REQUIRED]; } temp; @@ -285,7 +293,8 @@ struct xz_dec_lzma2 { */ static void dict_reset(struct dictionary *dict, struct xz_buf *b) { - if (DEC_IS_SINGLE(dict->mode)) { + if (DEC_IS_SINGLE(dict->mode)) + { dict->buf = b->out + b->out_pos; dict->end = b->out_size - b->out_pos; } @@ -358,7 +367,8 @@ static bool dict_repeat(struct dictionary *dict, uint32_t *len, uint32_t dist) if (dist >= dict->pos) back += dict->end; - do { + do + { dict->buf[dict->pos++] = dict->buf[back++]; if (back == dict->end) back = 0; @@ -371,15 +381,13 @@ static bool dict_repeat(struct dictionary *dict, uint32_t *len, uint32_t dist) } /* Copy uncompressed data as is from input to dictionary and output buffers. */ -static void dict_uncompressed(struct dictionary *dict, struct xz_buf *b, - uint32_t *left) +static void dict_uncompressed(struct dictionary *dict, struct xz_buf *b, uint32_t *left) { size_t copy_size; - while (*left > 0 && b->in_pos < b->in_size - && b->out_pos < b->out_size) { - copy_size = min(b->in_size - b->in_pos, - b->out_size - b->out_pos); + while (*left > 0 && b->in_pos < b->in_size && b->out_pos < b->out_size) + { + copy_size = min(b->in_size - b->in_pos, b->out_size - b->out_pos); if (copy_size > dict->end - dict->pos) copy_size = dict->end - dict->pos; if (copy_size > *left) @@ -393,12 +401,12 @@ static void dict_uncompressed(struct dictionary *dict, struct xz_buf *b, if (dict->full < dict->pos) dict->full = dict->pos; - if (DEC_IS_MULTI(dict->mode)) { + if (DEC_IS_MULTI(dict->mode)) + { if (dict->pos == dict->end) dict->pos = 0; - memcpy(b->out + b->out_pos, b->in + b->in_pos, - copy_size); + memcpy(b->out + b->out_pos, b->in + b->in_pos, copy_size); } dict->start = dict->pos; @@ -417,12 +425,12 @@ static uint32_t dict_flush(struct dictionary *dict, struct xz_buf *b) { size_t copy_size = dict->pos - dict->start; - if (DEC_IS_MULTI(dict->mode)) { + if (DEC_IS_MULTI(dict->mode)) + { if (dict->pos == dict->end) dict->pos = 0; - memcpy(b->out + b->out_pos, dict->buf + dict->start, - copy_size); + memcpy(b->out + b->out_pos, dict->buf + dict->start, copy_size); } dict->start = dict->pos; @@ -437,7 +445,7 @@ static uint32_t dict_flush(struct dictionary *dict, struct xz_buf *b) /* Reset the range decoder. */ static void rc_reset(struct rc_dec *rc) { - rc->range = (uint32_t)-1; + rc->range = (uint32_t) - 1; rc->code = 0; rc->init_bytes_left = RC_INIT_BYTES; } @@ -448,7 +456,8 @@ static void rc_reset(struct rc_dec *rc) */ static bool rc_read_init(struct rc_dec *rc, struct xz_buf *b) { - while (rc->init_bytes_left > 0) { + while (rc->init_bytes_left > 0) + { if (b->in_pos == b->in_size) return false; @@ -477,7 +486,8 @@ static inline bool rc_is_finished(const struct rc_dec *rc) /* Read the next input byte if needed. */ static __always_inline void rc_normalize(struct rc_dec *rc) { - if (rc->range < RC_TOP_VALUE) { + if (rc->range < RC_TOP_VALUE) + { rc->range <<= RC_SHIFT_BITS; rc->code = (rc->code << RC_SHIFT_BITS) + rc->in[rc->in_pos++]; } @@ -501,11 +511,14 @@ static __always_inline int rc_bit(struct rc_dec *rc, uint16_t *prob) rc_normalize(rc); bound = (rc->range >> RC_BIT_MODEL_TOTAL_BITS) * *prob; - if (rc->code < bound) { + if (rc->code < bound) + { rc->range = bound; *prob += (RC_BIT_MODEL_TOTAL - *prob) >> RC_MOVE_BITS; bit = 0; - } else { + } + else + { rc->range -= bound; rc->code -= bound; *prob -= *prob >> RC_MOVE_BITS; @@ -516,12 +529,12 @@ static __always_inline int rc_bit(struct rc_dec *rc, uint16_t *prob) } /* Decode a bittree starting from the most significant bit. */ -static __always_inline uint32_t rc_bittree(struct rc_dec *rc, - uint16_t *probs, uint32_t limit) +static __always_inline uint32_t rc_bittree(struct rc_dec *rc, uint16_t *probs, uint32_t limit) { uint32_t symbol = 1; - do { + do + { if (rc_bit(rc, &probs[symbol])) symbol = (symbol << 1) + 1; else @@ -532,18 +545,21 @@ static __always_inline uint32_t rc_bittree(struct rc_dec *rc, } /* Decode a bittree starting from the least significant bit. */ -static __always_inline void rc_bittree_reverse(struct rc_dec *rc, - uint16_t *probs, - uint32_t *dest, uint32_t limit) +static __always_inline void rc_bittree_reverse(struct rc_dec *rc, uint16_t *probs, + uint32_t *dest, uint32_t limit) { uint32_t symbol = 1; uint32_t i = 0; - do { - if (rc_bit(rc, &probs[symbol])) { + do + { + if (rc_bit(rc, &probs[symbol])) + { symbol = (symbol << 1) + 1; *dest += 1 << i; - } else { + } + else + { symbol <<= 1; } } while (++i < limit); @@ -554,7 +570,8 @@ static inline void rc_direct(struct rc_dec *rc, uint32_t *dest, uint32_t limit) { uint32_t mask; - do { + do + { rc_normalize(rc); rc->range >>= 1; rc->code -= rc->range; @@ -589,22 +606,29 @@ static void lzma_literal(struct xz_dec_lzma2 *s) probs = lzma_literal_probs(s); - if (lzma_state_is_literal(s->lzma.state)) { + if (lzma_state_is_literal(s->lzma.state)) + { symbol = rc_bittree(&s->rc, probs, 0x100); - } else { + } + else + { symbol = 1; match_byte = dict_get(&s->dict, s->lzma.rep0) << 1; offset = 0x100; - do { + do + { match_bit = match_byte & offset; match_byte <<= 1; i = offset + match_bit + symbol; - if (rc_bit(&s->rc, &probs[i])) { + if (rc_bit(&s->rc, &probs[i])) + { symbol = (symbol << 1) + 1; offset &= match_bit; - } else { + } + else + { symbol <<= 1; offset &= ~match_bit; } @@ -616,26 +640,30 @@ static void lzma_literal(struct xz_dec_lzma2 *s) } /* Decode the length of the match into s->lzma.len. */ -static void lzma_len(struct xz_dec_lzma2 *s, struct lzma_len_dec *l, - uint32_t pos_state) +static void lzma_len(struct xz_dec_lzma2 *s, struct lzma_len_dec *l, uint32_t pos_state) { uint16_t *probs; uint32_t limit; - if (!rc_bit(&s->rc, &l->choice)) { + if (!rc_bit(&s->rc, &l->choice)) + { probs = l->low[pos_state]; limit = LEN_LOW_SYMBOLS; s->lzma.len = MATCH_LEN_MIN; - } else { - if (!rc_bit(&s->rc, &l->choice2)) { + } + else + { + if (!rc_bit(&s->rc, &l->choice2)) + { probs = l->mid[pos_state]; limit = LEN_MID_SYMBOLS; s->lzma.len = MATCH_LEN_MIN + LEN_LOW_SYMBOLS; - } else { + } + else + { probs = l->high; limit = LEN_HIGH_SYMBOLS; - s->lzma.len = MATCH_LEN_MIN + LEN_LOW_SYMBOLS - + LEN_MID_SYMBOLS; + s->lzma.len = MATCH_LEN_MIN + LEN_LOW_SYMBOLS + LEN_MID_SYMBOLS; } } @@ -660,23 +688,26 @@ static void lzma_match(struct xz_dec_lzma2 *s, uint32_t pos_state) probs = s->lzma.dist_slot[lzma_get_dist_state(s->lzma.len)]; dist_slot = rc_bittree(&s->rc, probs, DIST_SLOTS) - DIST_SLOTS; - if (dist_slot < DIST_MODEL_START) { + if (dist_slot < DIST_MODEL_START) + { s->lzma.rep0 = dist_slot; - } else { + } + else + { limit = (dist_slot >> 1) - 1; s->lzma.rep0 = 2 + (dist_slot & 1); - if (dist_slot < DIST_MODEL_END) { + if (dist_slot < DIST_MODEL_END) + { s->lzma.rep0 <<= limit; - probs = s->lzma.dist_special + s->lzma.rep0 - - dist_slot - 1; - rc_bittree_reverse(&s->rc, probs, - &s->lzma.rep0, limit); - } else { + probs = s->lzma.dist_special + s->lzma.rep0 - dist_slot - 1; + rc_bittree_reverse(&s->rc, probs, &s->lzma.rep0, limit); + } + else + { rc_direct(&s->rc, &s->lzma.rep0, limit - ALIGN_BITS); s->lzma.rep0 <<= ALIGN_BITS; - rc_bittree_reverse(&s->rc, s->lzma.dist_align, - &s->lzma.rep0, ALIGN_BITS); + rc_bittree_reverse(&s->rc, s->lzma.dist_align, &s->lzma.rep0, ALIGN_BITS); } } } @@ -689,20 +720,29 @@ static void lzma_rep_match(struct xz_dec_lzma2 *s, uint32_t pos_state) { uint32_t tmp; - if (!rc_bit(&s->rc, &s->lzma.is_rep0[s->lzma.state])) { - if (!rc_bit(&s->rc, &s->lzma.is_rep0_long[ - s->lzma.state][pos_state])) { + if (!rc_bit(&s->rc, &s->lzma.is_rep0[s->lzma.state])) + { + if (!rc_bit(&s->rc, &s->lzma.is_rep0_long[s->lzma.state][pos_state])) + { lzma_state_short_rep(&s->lzma.state); s->lzma.len = 1; return; } - } else { - if (!rc_bit(&s->rc, &s->lzma.is_rep1[s->lzma.state])) { + } + else + { + if (!rc_bit(&s->rc, &s->lzma.is_rep1[s->lzma.state])) + { tmp = s->lzma.rep1; - } else { - if (!rc_bit(&s->rc, &s->lzma.is_rep2[s->lzma.state])) { + } + else + { + if (!rc_bit(&s->rc, &s->lzma.is_rep2[s->lzma.state])) + { tmp = s->lzma.rep2; - } else { + } + else + { tmp = s->lzma.rep3; s->lzma.rep3 = s->lzma.rep2; } @@ -734,13 +774,16 @@ static bool lzma_main(struct xz_dec_lzma2 *s) * Decode more LZMA symbols. One iteration may consume up to * LZMA_IN_REQUIRED - 1 bytes. */ - while (dict_has_space(&s->dict) && !rc_limit_exceeded(&s->rc)) { + while (dict_has_space(&s->dict) && !rc_limit_exceeded(&s->rc)) + { pos_state = s->dict.pos & s->lzma.pos_mask; - if (!rc_bit(&s->rc, &s->lzma.is_match[ - s->lzma.state][pos_state])) { + if (!rc_bit(&s->rc, &s->lzma.is_match[s->lzma.state][pos_state])) + { lzma_literal(s); - } else { + } + else + { if (rc_bit(&s->rc, &s->lzma.is_rep[s->lzma.state])) lzma_rep_match(s, pos_state); else @@ -802,7 +845,8 @@ static bool lzma_props(struct xz_dec_lzma2 *s, uint8_t props) return false; s->lzma.pos_mask = 0; - while (props >= 9 * 5) { + while (props >= 9 * 5) + { props -= 9 * 5; ++s->lzma.pos_mask; } @@ -810,7 +854,8 @@ static bool lzma_props(struct xz_dec_lzma2 *s, uint8_t props) s->lzma.pos_mask = (1 << s->lzma.pos_mask) - 1; s->lzma.literal_pos_mask = 0; - while (props >= 9) { + while (props >= 9) + { props -= 9; ++s->lzma.literal_pos_mask; } @@ -849,7 +894,8 @@ static bool lzma2_lzma(struct xz_dec_lzma2 *s, struct xz_buf *b) uint32_t tmp; in_avail = b->in_size - b->in_pos; - if (s->temp.size > 0 || s->lzma2.compressed == 0) { + if (s->temp.size > 0 || s->lzma2.compressed == 0) + { tmp = 2 * LZMA_IN_REQUIRED - s->temp.size; if (tmp > s->lzma2.compressed - s->temp.size) tmp = s->lzma2.compressed - s->temp.size; @@ -858,16 +904,19 @@ static bool lzma2_lzma(struct xz_dec_lzma2 *s, struct xz_buf *b) memcpy(s->temp.buf + s->temp.size, b->in + b->in_pos, tmp); - if (s->temp.size + tmp == s->lzma2.compressed) { - memzero(s->temp.buf + s->temp.size + tmp, - sizeof(s->temp.buf) - - s->temp.size - tmp); + if (s->temp.size + tmp == s->lzma2.compressed) + { + memzero(s->temp.buf + s->temp.size + tmp, sizeof(s->temp.buf) - s->temp.size - tmp); s->rc.in_limit = s->temp.size + tmp; - } else if (s->temp.size + tmp < LZMA_IN_REQUIRED) { + } + else if (s->temp.size + tmp < LZMA_IN_REQUIRED) + { s->temp.size += tmp; b->in_pos += tmp; return true; - } else { + } + else + { s->rc.in_limit = s->temp.size + tmp - LZMA_IN_REQUIRED; } @@ -879,10 +928,10 @@ static bool lzma2_lzma(struct xz_dec_lzma2 *s, struct xz_buf *b) s->lzma2.compressed -= s->rc.in_pos; - if (s->rc.in_pos < s->temp.size) { + if (s->rc.in_pos < s->temp.size) + { s->temp.size -= s->rc.in_pos; - memmove(s->temp.buf, s->temp.buf + s->rc.in_pos, - s->temp.size); + memmove(s->temp.buf, s->temp.buf + s->rc.in_pos, s->temp.size); return true; } @@ -891,7 +940,8 @@ static bool lzma2_lzma(struct xz_dec_lzma2 *s, struct xz_buf *b) } in_avail = b->in_size - b->in_pos; - if (in_avail >= LZMA_IN_REQUIRED) { + if (in_avail >= LZMA_IN_REQUIRED) + { s->rc.in = b->in; s->rc.in_pos = b->in_pos; @@ -912,7 +962,8 @@ static bool lzma2_lzma(struct xz_dec_lzma2 *s, struct xz_buf *b) } in_avail = b->in_size - b->in_pos; - if (in_avail < LZMA_IN_REQUIRED) { + if (in_avail < LZMA_IN_REQUIRED) + { if (in_avail > s->lzma2.compressed) in_avail = s->lzma2.compressed; @@ -928,13 +979,14 @@ static bool lzma2_lzma(struct xz_dec_lzma2 *s, struct xz_buf *b) * Take care of the LZMA2 control layer, and forward the job of actual LZMA * decoding or copying of uncompressed chunks to other functions. */ -XZ_EXTERN enum xz_ret xz_dec_lzma2_run(struct xz_dec_lzma2 *s, - struct xz_buf *b) +XZ_EXTERN enum xz_ret xz_dec_lzma2_run(struct xz_dec_lzma2 *s, struct xz_buf *b) { uint32_t tmp; - while (b->in_pos < b->in_size || s->lzma2.sequence == SEQ_LZMA_RUN) { - switch (s->lzma2.sequence) { + while (b->in_pos < b->in_size || s->lzma2.sequence == SEQ_LZMA_RUN) + { + switch (s->lzma2.sequence) + { case SEQ_CONTROL: /* * LZMA2 control byte @@ -972,38 +1024,45 @@ XZ_EXTERN enum xz_ret xz_dec_lzma2_run(struct xz_dec_lzma2 *s, if (tmp == 0x00) return XZ_STREAM_END; - if (tmp >= 0xE0 || tmp == 0x01) { + if (tmp >= 0xE0 || tmp == 0x01) + { s->lzma2.need_props = true; s->lzma2.need_dict_reset = false; dict_reset(&s->dict, b); - } else if (s->lzma2.need_dict_reset) { + } + else if (s->lzma2.need_dict_reset) + { return XZ_DATA_ERROR; } - if (tmp >= 0x80) { + if (tmp >= 0x80) + { s->lzma2.uncompressed = (tmp & 0x1F) << 16; s->lzma2.sequence = SEQ_UNCOMPRESSED_1; - if (tmp >= 0xC0) { + if (tmp >= 0xC0) + { /* * When there are new properties, * state reset is done at * SEQ_PROPERTIES. */ s->lzma2.need_props = false; - s->lzma2.next_sequence - = SEQ_PROPERTIES; - - } else if (s->lzma2.need_props) { + s->lzma2.next_sequence = SEQ_PROPERTIES; + } + else if (s->lzma2.need_props) + { return XZ_DATA_ERROR; - - } else { - s->lzma2.next_sequence - = SEQ_LZMA_PREPARE; + } + else + { + s->lzma2.next_sequence = SEQ_LZMA_PREPARE; if (tmp >= 0xA0) lzma_reset(s); } - } else { + } + else + { if (tmp > 0x02) return XZ_DATA_ERROR; @@ -1014,26 +1073,22 @@ XZ_EXTERN enum xz_ret xz_dec_lzma2_run(struct xz_dec_lzma2 *s, break; case SEQ_UNCOMPRESSED_1: - s->lzma2.uncompressed - += (uint32_t)b->in[b->in_pos++] << 8; + s->lzma2.uncompressed += (uint32_t)b->in[b->in_pos++] << 8; s->lzma2.sequence = SEQ_UNCOMPRESSED_2; break; case SEQ_UNCOMPRESSED_2: - s->lzma2.uncompressed - += (uint32_t)b->in[b->in_pos++] + 1; + s->lzma2.uncompressed += (uint32_t)b->in[b->in_pos++] + 1; s->lzma2.sequence = SEQ_COMPRESSED_0; break; case SEQ_COMPRESSED_0: - s->lzma2.compressed - = (uint32_t)b->in[b->in_pos++] << 8; + s->lzma2.compressed = (uint32_t)b->in[b->in_pos++] << 8; s->lzma2.sequence = SEQ_COMPRESSED_1; break; case SEQ_COMPRESSED_1: - s->lzma2.compressed - += (uint32_t)b->in[b->in_pos++] + 1; + s->lzma2.compressed += (uint32_t)b->in[b->in_pos++] + 1; s->lzma2.sequence = s->lzma2.next_sequence; break; @@ -1063,26 +1118,24 @@ XZ_EXTERN enum xz_ret xz_dec_lzma2_run(struct xz_dec_lzma2 *s, * the output buffer yet, we may run this loop * multiple times without changing s->lzma2.sequence. */ - dict_limit(&s->dict, min_t(size_t, - b->out_size - b->out_pos, - s->lzma2.uncompressed)); + dict_limit(&s->dict, + min_t(size_t, b->out_size - b->out_pos, s->lzma2.uncompressed)); if (!lzma2_lzma(s, b)) return XZ_DATA_ERROR; s->lzma2.uncompressed -= dict_flush(&s->dict, b); - if (s->lzma2.uncompressed == 0) { - if (s->lzma2.compressed > 0 || s->lzma.len > 0 - || !rc_is_finished(&s->rc)) + if (s->lzma2.uncompressed == 0) + { + if (s->lzma2.compressed > 0 || s->lzma.len > 0 || !rc_is_finished(&s->rc)) return XZ_DATA_ERROR; rc_reset(&s->rc); s->lzma2.sequence = SEQ_CONTROL; - - } else if (b->out_pos == b->out_size - || (b->in_pos == b->in_size - && s->temp.size - < s->lzma2.compressed)) { + } + else if (b->out_pos == b->out_size || + (b->in_pos == b->in_size && s->temp.size < s->lzma2.compressed)) + { return XZ_OK; } @@ -1101,8 +1154,7 @@ XZ_EXTERN enum xz_ret xz_dec_lzma2_run(struct xz_dec_lzma2 *s, return XZ_OK; } -XZ_EXTERN struct xz_dec_lzma2 *xz_dec_lzma2_create(enum xz_mode mode, - uint32_t dict_max) +XZ_EXTERN struct xz_dec_lzma2 *xz_dec_lzma2_create(enum xz_mode mode, uint32_t dict_max) { struct xz_dec_lzma2 *s = kmalloc(sizeof(*s), GFP_KERNEL); if (s == NULL) @@ -1111,13 +1163,17 @@ XZ_EXTERN struct xz_dec_lzma2 *xz_dec_lzma2_create(enum xz_mode mode, s->dict.mode = mode; s->dict.size_max = dict_max; - if (DEC_IS_PREALLOC(mode)) { + if (DEC_IS_PREALLOC(mode)) + { s->dict.buf = vmalloc(dict_max); - if (s->dict.buf == NULL) { + if (s->dict.buf == NULL) + { kfree(s); return NULL; } - } else if (DEC_IS_DYNALLOC(mode)) { + } + else if (DEC_IS_DYNALLOC(mode)) + { s->dict.buf = NULL; s->dict.allocated = 0; } @@ -1134,17 +1190,21 @@ XZ_EXTERN enum xz_ret xz_dec_lzma2_reset(struct xz_dec_lzma2 *s, uint8_t props) s->dict.size = 2 + (props & 1); s->dict.size <<= (props >> 1) + 11; - if (DEC_IS_MULTI(s->dict.mode)) { + if (DEC_IS_MULTI(s->dict.mode)) + { if (s->dict.size > s->dict.size_max) return XZ_MEMLIMIT_ERROR; s->dict.end = s->dict.size; - if (DEC_IS_DYNALLOC(s->dict.mode)) { - if (s->dict.allocated < s->dict.size) { + if (DEC_IS_DYNALLOC(s->dict.mode)) + { + if (s->dict.allocated < s->dict.size) + { vfree(s->dict.buf); s->dict.buf = vmalloc(s->dict.size); - if (s->dict.buf == NULL) { + if (s->dict.buf == NULL) + { s->dict.allocated = 0; return XZ_MEM_ERROR; } diff --git a/depends/xz-embedded/src/xz_dec_stream.c b/depends/xz-embedded/src/xz_dec_stream.c index d6525506..6e935ded 100644 --- a/depends/xz-embedded/src/xz_dec_stream.c +++ b/depends/xz-embedded/src/xz_dec_stream.c @@ -11,21 +11,24 @@ #include "xz_stream.h" #ifdef XZ_USE_CRC64 -# define IS_CRC64(check_type) ((check_type) == XZ_CHECK_CRC64) +#define IS_CRC64(check_type) ((check_type) == XZ_CHECK_CRC64) #else -# define IS_CRC64(check_type) false +#define IS_CRC64(check_type) false #endif /* Hash used to validate the Index field */ -struct xz_dec_hash { +struct xz_dec_hash +{ vli_type unpadded; vli_type uncompressed; uint32_t crc32; }; -struct xz_dec { +struct xz_dec +{ /* Position in dec_main() */ - enum { + enum + { SEQ_STREAM_HEADER, SEQ_BLOCK_START, SEQ_BLOCK_HEADER, @@ -69,7 +72,8 @@ struct xz_dec { bool allow_buf_error; /* Information stored in Block Header */ - struct { + struct + { /* * Value stored in the Compressed Size field, or * VLI_UNKNOWN if Compressed Size is not present. @@ -87,7 +91,8 @@ struct xz_dec { } block_header; /* Information collected when decoding Blocks */ - struct { + struct + { /* Observed compressed size of the current Block */ vli_type compressed; @@ -105,9 +110,11 @@ struct xz_dec { } block; /* Variables needed when verifying the Index field */ - struct { + struct + { /* Position in dec_index() */ - enum { + enum + { SEQ_INDEX_COUNT, SEQ_INDEX_UNPADDED, SEQ_INDEX_UNCOMPRESSED @@ -133,7 +140,8 @@ struct xz_dec { * to a multiple of four bytes; the size_t variables before it * should guarantee this. */ - struct { + struct + { size_t pos; size_t size; uint8_t buf[1024]; @@ -149,14 +157,8 @@ struct xz_dec { #ifdef XZ_DEC_ANY_CHECK /* Sizes of the Check field with different Check IDs */ -static const uint8_t check_sizes[16] = { - 0, - 4, 4, 4, - 8, 8, 8, - 16, 16, 16, - 32, 32, 32, - 64, 64, 64 -}; +static const uint8_t check_sizes[16] = {0, 4, 4, 4, 8, 8, 8, 16, + 16, 16, 32, 32, 32, 64, 64, 64}; #endif /* @@ -167,14 +169,14 @@ static const uint8_t check_sizes[16] = { */ static bool fill_temp(struct xz_dec *s, struct xz_buf *b) { - size_t copy_size = min_t(size_t, - b->in_size - b->in_pos, s->temp.size - s->temp.pos); + size_t copy_size = min_t(size_t, b->in_size - b->in_pos, s->temp.size - s->temp.pos); memcpy(s->temp.buf + s->temp.pos, b->in + b->in_pos, copy_size); b->in_pos += copy_size; s->temp.pos += copy_size; - if (s->temp.pos == s->temp.size) { + if (s->temp.pos == s->temp.size) + { s->temp.pos = 0; return true; } @@ -183,21 +185,22 @@ static bool fill_temp(struct xz_dec *s, struct xz_buf *b) } /* Decode a variable-length integer (little-endian base-128 encoding) */ -static enum xz_ret dec_vli(struct xz_dec *s, const uint8_t *in, - size_t *in_pos, size_t in_size) +static enum xz_ret dec_vli(struct xz_dec *s, const uint8_t *in, size_t *in_pos, size_t in_size) { uint8_t byte; if (s->pos == 0) s->vli = 0; - while (*in_pos < in_size) { + while (*in_pos < in_size) + { byte = in[*in_pos]; ++*in_pos; s->vli |= (vli_type)(byte & 0x7F) << s->pos; - if ((byte & 0x80) == 0) { + if ((byte & 0x80) == 0) + { /* Don't allow non-minimal encodings. */ if (byte == 0 && s->pos != 0) return XZ_DATA_ERROR; @@ -247,33 +250,28 @@ static enum xz_ret dec_block(struct xz_dec *s, struct xz_buf *b) * There is no need to separately check for VLI_UNKNOWN, since * the observed sizes are always smaller than VLI_UNKNOWN. */ - if (s->block.compressed > s->block_header.compressed - || s->block.uncompressed - > s->block_header.uncompressed) + if (s->block.compressed > s->block_header.compressed || + s->block.uncompressed > s->block_header.uncompressed) return XZ_DATA_ERROR; if (s->check_type == XZ_CHECK_CRC32) - s->crc = xz_crc32(b->out + s->out_start, - b->out_pos - s->out_start, s->crc); + s->crc = xz_crc32(b->out + s->out_start, b->out_pos - s->out_start, s->crc); #ifdef XZ_USE_CRC64 else if (s->check_type == XZ_CHECK_CRC64) - s->crc = xz_crc64(b->out + s->out_start, - b->out_pos - s->out_start, s->crc); + s->crc = xz_crc64(b->out + s->out_start, b->out_pos - s->out_start, s->crc); #endif - if (ret == XZ_STREAM_END) { - if (s->block_header.compressed != VLI_UNKNOWN - && s->block_header.compressed - != s->block.compressed) + if (ret == XZ_STREAM_END) + { + if (s->block_header.compressed != VLI_UNKNOWN && + s->block_header.compressed != s->block.compressed) return XZ_DATA_ERROR; - if (s->block_header.uncompressed != VLI_UNKNOWN - && s->block_header.uncompressed - != s->block.uncompressed) + if (s->block_header.uncompressed != VLI_UNKNOWN && + s->block_header.uncompressed != s->block.uncompressed) return XZ_DATA_ERROR; - s->block.hash.unpadded += s->block_header.size - + s->block.compressed; + s->block.hash.unpadded += s->block_header.size + s->block.compressed; #ifdef XZ_DEC_ANY_CHECK s->block.hash.unpadded += check_sizes[s->check_type]; @@ -285,9 +283,8 @@ static enum xz_ret dec_block(struct xz_dec *s, struct xz_buf *b) #endif s->block.hash.uncompressed += s->block.uncompressed; - s->block.hash.crc32 = xz_crc32( - (const uint8_t *)&s->block.hash, - sizeof(s->block.hash), s->block.hash.crc32); + s->block.hash.crc32 = xz_crc32((const uint8_t *)&s->block.hash, sizeof(s->block.hash), + s->block.hash.crc32); ++s->block.count; } @@ -315,14 +312,17 @@ static enum xz_ret dec_index(struct xz_dec *s, struct xz_buf *b) { enum xz_ret ret; - do { + do + { ret = dec_vli(s, b->in, &b->in_pos, b->in_size); - if (ret != XZ_STREAM_END) { + if (ret != XZ_STREAM_END) + { index_update(s, b); return ret; } - switch (s->index.sequence) { + switch (s->index.sequence) + { case SEQ_INDEX_COUNT: s->index.count = s->vli; @@ -344,10 +344,8 @@ static enum xz_ret dec_index(struct xz_dec *s, struct xz_buf *b) case SEQ_INDEX_UNCOMPRESSED: s->index.hash.uncompressed += s->vli; - s->index.hash.crc32 = xz_crc32( - (const uint8_t *)&s->index.hash, - sizeof(s->index.hash), - s->index.hash.crc32); + s->index.hash.crc32 = xz_crc32((const uint8_t *)&s->index.hash, + sizeof(s->index.hash), s->index.hash.crc32); --s->index.count; s->index.sequence = SEQ_INDEX_UNPADDED; break; @@ -362,10 +360,10 @@ static enum xz_ret dec_index(struct xz_dec *s, struct xz_buf *b) * of s->crc. s->pos must be zero when starting to validate the first byte. * The "bits" argument allows using the same code for both CRC32 and CRC64. */ -static enum xz_ret crc_validate(struct xz_dec *s, struct xz_buf *b, - uint32_t bits) +static enum xz_ret crc_validate(struct xz_dec *s, struct xz_buf *b, uint32_t bits) { - do { + do + { if (b->in_pos == b->in_size) return XZ_OK; @@ -389,7 +387,8 @@ static enum xz_ret crc_validate(struct xz_dec *s, struct xz_buf *b, */ static bool check_skip(struct xz_dec *s, struct xz_buf *b) { - while (s->pos < check_sizes[s->check_type]) { + while (s->pos < check_sizes[s->check_type]) + { if (b->in_pos == b->in_size) return false; @@ -409,8 +408,8 @@ static enum xz_ret dec_stream_header(struct xz_dec *s) if (!memeq(s->temp.buf, HEADER_MAGIC, HEADER_MAGIC_SIZE)) return XZ_FORMAT_ERROR; - if (xz_crc32(s->temp.buf + HEADER_MAGIC_SIZE, 2, 0) - != get_le32(s->temp.buf + HEADER_MAGIC_SIZE + 2)) + if (xz_crc32(s->temp.buf + HEADER_MAGIC_SIZE, 2, 0) != + get_le32(s->temp.buf + HEADER_MAGIC_SIZE + 2)) return XZ_DATA_ERROR; if (s->temp.buf[HEADER_MAGIC_SIZE] != 0) @@ -476,49 +475,53 @@ static enum xz_ret dec_block_header(struct xz_dec *s) * eight bytes so this is safe. */ s->temp.size -= 4; - if (xz_crc32(s->temp.buf, s->temp.size, 0) - != get_le32(s->temp.buf + s->temp.size)) + if (xz_crc32(s->temp.buf, s->temp.size, 0) != get_le32(s->temp.buf + s->temp.size)) return XZ_DATA_ERROR; s->temp.pos = 2; - /* - * Catch unsupported Block Flags. We support only one or two filters - * in the chain, so we catch that with the same test. - */ +/* + * Catch unsupported Block Flags. We support only one or two filters + * in the chain, so we catch that with the same test. + */ #ifdef XZ_DEC_BCJ if (s->temp.buf[1] & 0x3E) #else - if (s->temp.buf[1] & 0x3F) + if (s->temp.buf[1] & 0x3F) #endif - return XZ_OPTIONS_ERROR; + return XZ_OPTIONS_ERROR; /* Compressed Size */ - if (s->temp.buf[1] & 0x40) { - if (dec_vli(s, s->temp.buf, &s->temp.pos, s->temp.size) - != XZ_STREAM_END) + if (s->temp.buf[1] & 0x40) + { + if (dec_vli(s, s->temp.buf, &s->temp.pos, s->temp.size) != XZ_STREAM_END) return XZ_DATA_ERROR; s->block_header.compressed = s->vli; - } else { + } + else + { s->block_header.compressed = VLI_UNKNOWN; } /* Uncompressed Size */ - if (s->temp.buf[1] & 0x80) { - if (dec_vli(s, s->temp.buf, &s->temp.pos, s->temp.size) - != XZ_STREAM_END) + if (s->temp.buf[1] & 0x80) + { + if (dec_vli(s, s->temp.buf, &s->temp.pos, s->temp.size) != XZ_STREAM_END) return XZ_DATA_ERROR; s->block_header.uncompressed = s->vli; - } else { + } + else + { s->block_header.uncompressed = VLI_UNKNOWN; } #ifdef XZ_DEC_BCJ /* If there are two filters, the first one must be a BCJ filter. */ s->bcj_active = s->temp.buf[1] & 0x01; - if (s->bcj_active) { + if (s->bcj_active) + { if (s->temp.size - s->temp.pos < 2) return XZ_OPTIONS_ERROR; @@ -577,8 +580,10 @@ static enum xz_ret dec_main(struct xz_dec *s, struct xz_buf *b) */ s->in_start = b->in_pos; - while (true) { - switch (s->sequence) { + while (true) + { + switch (s->sequence) + { case SEQ_STREAM_HEADER: /* * Stream Header is copied to s->temp, and then @@ -610,7 +615,8 @@ static enum xz_ret dec_main(struct xz_dec *s, struct xz_buf *b) return XZ_OK; /* See if this is the beginning of the Index field. */ - if (b->in[b->in_pos] == 0) { + if (b->in[b->in_pos] == 0) + { s->in_start = b->in_pos++; s->sequence = SEQ_INDEX; break; @@ -620,8 +626,7 @@ static enum xz_ret dec_main(struct xz_dec *s, struct xz_buf *b) * Calculate the size of the Block Header and * prepare to decode it. */ - s->block_header.size - = ((uint32_t)b->in[b->in_pos] + 1) * 4; + s->block_header.size = ((uint32_t)b->in[b->in_pos] + 1) * 4; s->temp.size = s->block_header.size; s->temp.pos = 0; @@ -652,7 +657,8 @@ static enum xz_ret dec_main(struct xz_dec *s, struct xz_buf *b) * anymore, so we use it here to test the size * of the Block Padding field. */ - while (s->block.compressed & 3) { + while (s->block.compressed & 3) + { if (b->in_pos == b->in_size) return XZ_OK; @@ -665,18 +671,21 @@ static enum xz_ret dec_main(struct xz_dec *s, struct xz_buf *b) s->sequence = SEQ_BLOCK_CHECK; case SEQ_BLOCK_CHECK: - if (s->check_type == XZ_CHECK_CRC32) { + if (s->check_type == XZ_CHECK_CRC32) + { ret = crc_validate(s, b, 32); if (ret != XZ_STREAM_END) return ret; } - else if (IS_CRC64(s->check_type)) { + else if (IS_CRC64(s->check_type)) + { ret = crc_validate(s, b, 64); if (ret != XZ_STREAM_END) return ret; } #ifdef XZ_DEC_ANY_CHECK - else if (!check_skip(s, b)) { + else if (!check_skip(s, b)) + { return XZ_OK; } #endif @@ -692,9 +701,10 @@ static enum xz_ret dec_main(struct xz_dec *s, struct xz_buf *b) s->sequence = SEQ_INDEX_PADDING; case SEQ_INDEX_PADDING: - while ((s->index.size + (b->in_pos - s->in_start)) - & 3) { - if (b->in_pos == b->in_size) { + while ((s->index.size + (b->in_pos - s->in_start)) & 3) + { + if (b->in_pos == b->in_size) + { index_update(s, b); return XZ_OK; } @@ -707,8 +717,7 @@ static enum xz_ret dec_main(struct xz_dec *s, struct xz_buf *b) index_update(s, b); /* Compare the hashes to validate the Index field. */ - if (!memeq(&s->block.hash, &s->index.hash, - sizeof(s->block.hash))) + if (!memeq(&s->block.hash, &s->index.hash, sizeof(s->block.hash))) return XZ_DATA_ERROR; s->sequence = SEQ_INDEX_CRC32; @@ -770,23 +779,26 @@ XZ_EXTERN enum xz_ret xz_dec_run(struct xz_dec *s, struct xz_buf *b) out_start = b->out_pos; ret = dec_main(s, b); - if (DEC_IS_SINGLE(s->mode)) { + if (DEC_IS_SINGLE(s->mode)) + { if (ret == XZ_OK) - ret = b->in_pos == b->in_size - ? XZ_DATA_ERROR : XZ_BUF_ERROR; + ret = b->in_pos == b->in_size ? XZ_DATA_ERROR : XZ_BUF_ERROR; - if (ret != XZ_STREAM_END) { + if (ret != XZ_STREAM_END) + { b->in_pos = in_start; b->out_pos = out_start; } - - } else if (ret == XZ_OK && in_start == b->in_pos - && out_start == b->out_pos) { + } + else if (ret == XZ_OK && in_start == b->in_pos && out_start == b->out_pos) + { if (s->allow_buf_error) ret = XZ_BUF_ERROR; s->allow_buf_error = true; - } else { + } + else + { s->allow_buf_error = false; } @@ -837,7 +849,8 @@ XZ_EXTERN void xz_dec_reset(struct xz_dec *s) XZ_EXTERN void xz_dec_end(struct xz_dec *s) { - if (s != NULL) { + if (s != NULL) + { xz_dec_lzma2_end(s->lzma2); #ifdef XZ_DEC_BCJ xz_dec_bcj_end(s->bcj); diff --git a/depends/xz-embedded/src/xz_lzma2.h b/depends/xz-embedded/src/xz_lzma2.h index 071d67be..3976033a 100644 --- a/depends/xz-embedded/src/xz_lzma2.h +++ b/depends/xz-embedded/src/xz_lzma2.h @@ -39,7 +39,8 @@ * The symbol names are in from STATE_oldest_older_previous. REP means * either short or long repeated match, and NONLIT means any non-literal. */ -enum lzma_state { +enum lzma_state +{ STATE_LIT_LIT, STATE_MATCH_LIT_LIT, STATE_REP_LIT_LIT, @@ -146,8 +147,7 @@ static inline bool lzma_state_is_literal(enum lzma_state state) */ static inline uint32_t lzma_get_dist_state(uint32_t len) { - return len < DIST_STATES + MATCH_LEN_MIN - ? len - MATCH_LEN_MIN : DIST_STATES - 1; + return len < DIST_STATES + MATCH_LEN_MIN ? len - MATCH_LEN_MIN : DIST_STATES - 1; } /* @@ -192,7 +192,7 @@ static inline uint32_t lzma_get_dist_state(uint32_t len) #define ALIGN_MASK (ALIGN_SIZE - 1) /* Total number of all probability variables */ -#define PROBS_TOTAL (1846 + LITERAL_CODERS_MAX * LITERAL_CODER_SIZE) +#define PROBS_TOTAL (1846 + LITERAL_CODERS_MAX *LITERAL_CODER_SIZE) /* * LZMA remembers the four most recent match distances. Reusing these diff --git a/depends/xz-embedded/src/xz_private.h b/depends/xz-embedded/src/xz_private.h index 482b90f3..55a3af1c 100644 --- a/depends/xz-embedded/src/xz_private.h +++ b/depends/xz-embedded/src/xz_private.h @@ -11,51 +11,50 @@ #define XZ_PRIVATE_H #ifdef __KERNEL__ -# include -# include -# include - /* XZ_PREBOOT may be defined only via decompress_unxz.c. */ -# ifndef XZ_PREBOOT -# include -# include -# include -# ifdef CONFIG_XZ_DEC_X86 -# define XZ_DEC_X86 -# endif -# ifdef CONFIG_XZ_DEC_POWERPC -# define XZ_DEC_POWERPC -# endif -# ifdef CONFIG_XZ_DEC_IA64 -# define XZ_DEC_IA64 -# endif -# ifdef CONFIG_XZ_DEC_ARM -# define XZ_DEC_ARM -# endif -# ifdef CONFIG_XZ_DEC_ARMTHUMB -# define XZ_DEC_ARMTHUMB -# endif -# ifdef CONFIG_XZ_DEC_SPARC -# define XZ_DEC_SPARC -# endif -# define memeq(a, b, size) (memcmp(a, b, size) == 0) -# define memzero(buf, size) memset(buf, 0, size) -# endif -# define get_le32(p) le32_to_cpup((const uint32_t *)(p)) +#include +#include +#include +/* XZ_PREBOOT may be defined only via decompress_unxz.c. */ +#ifndef XZ_PREBOOT +#include +#include +#include +#ifdef CONFIG_XZ_DEC_X86 +#define XZ_DEC_X86 +#endif +#ifdef CONFIG_XZ_DEC_POWERPC +#define XZ_DEC_POWERPC +#endif +#ifdef CONFIG_XZ_DEC_IA64 +#define XZ_DEC_IA64 +#endif +#ifdef CONFIG_XZ_DEC_ARM +#define XZ_DEC_ARM +#endif +#ifdef CONFIG_XZ_DEC_ARMTHUMB +#define XZ_DEC_ARMTHUMB +#endif +#ifdef CONFIG_XZ_DEC_SPARC +#define XZ_DEC_SPARC +#endif +#define memeq(a, b, size) (memcmp(a, b, size) == 0) +#define memzero(buf, size) memset(buf, 0, size) +#endif +#define get_le32(p) le32_to_cpup((const uint32_t *)(p)) #else - /* - * For userspace builds, use a separate header to define the required - * macros and functions. This makes it easier to adapt the code into - * different environments and avoids clutter in the Linux kernel tree. - */ -# include "xz_config.h" +/* + * For userspace builds, use a separate header to define the required + * macros and functions. This makes it easier to adapt the code into + * different environments and avoids clutter in the Linux kernel tree. + */ +#include "xz_config.h" #endif /* If no specific decoding mode is requested, enable support for all modes. */ -#if !defined(XZ_DEC_SINGLE) && !defined(XZ_DEC_PREALLOC) \ - && !defined(XZ_DEC_DYNALLOC) -# define XZ_DEC_SINGLE -# define XZ_DEC_PREALLOC -# define XZ_DEC_DYNALLOC +#if !defined(XZ_DEC_SINGLE) && !defined(XZ_DEC_PREALLOC) && !defined(XZ_DEC_DYNALLOC) +#define XZ_DEC_SINGLE +#define XZ_DEC_PREALLOC +#define XZ_DEC_DYNALLOC #endif /* @@ -64,29 +63,29 @@ * false at compile time and thus allow the compiler to omit unneeded code. */ #ifdef XZ_DEC_SINGLE -# define DEC_IS_SINGLE(mode) ((mode) == XZ_SINGLE) +#define DEC_IS_SINGLE(mode) ((mode) == XZ_SINGLE) #else -# define DEC_IS_SINGLE(mode) (false) +#define DEC_IS_SINGLE(mode) (false) #endif #ifdef XZ_DEC_PREALLOC -# define DEC_IS_PREALLOC(mode) ((mode) == XZ_PREALLOC) +#define DEC_IS_PREALLOC(mode) ((mode) == XZ_PREALLOC) #else -# define DEC_IS_PREALLOC(mode) (false) +#define DEC_IS_PREALLOC(mode) (false) #endif #ifdef XZ_DEC_DYNALLOC -# define DEC_IS_DYNALLOC(mode) ((mode) == XZ_DYNALLOC) +#define DEC_IS_DYNALLOC(mode) ((mode) == XZ_DYNALLOC) #else -# define DEC_IS_DYNALLOC(mode) (false) +#define DEC_IS_DYNALLOC(mode) (false) #endif #if !defined(XZ_DEC_SINGLE) -# define DEC_IS_MULTI(mode) (true) +#define DEC_IS_MULTI(mode) (true) #elif defined(XZ_DEC_PREALLOC) || defined(XZ_DEC_DYNALLOC) -# define DEC_IS_MULTI(mode) ((mode) != XZ_SINGLE) +#define DEC_IS_MULTI(mode) ((mode) != XZ_SINGLE) #else -# define DEC_IS_MULTI(mode) (false) +#define DEC_IS_MULTI(mode) (false) #endif /* @@ -94,20 +93,18 @@ * XZ_DEC_BCJ is used to enable generic support for BCJ decoders. */ #ifndef XZ_DEC_BCJ -# if defined(XZ_DEC_X86) || defined(XZ_DEC_POWERPC) \ - || defined(XZ_DEC_IA64) || defined(XZ_DEC_ARM) \ - || defined(XZ_DEC_ARM) || defined(XZ_DEC_ARMTHUMB) \ - || defined(XZ_DEC_SPARC) -# define XZ_DEC_BCJ -# endif +#if defined(XZ_DEC_X86) || defined(XZ_DEC_POWERPC) || defined(XZ_DEC_IA64) || \ + defined(XZ_DEC_ARM) || defined(XZ_DEC_ARM) || defined(XZ_DEC_ARMTHUMB) || \ + defined(XZ_DEC_SPARC) +#define XZ_DEC_BCJ +#endif #endif /* * Allocate memory for LZMA2 decoder. xz_dec_lzma2_reset() must be used * before calling xz_dec_lzma2_run(). */ -XZ_EXTERN struct xz_dec_lzma2 *xz_dec_lzma2_create(enum xz_mode mode, - uint32_t dict_max); +XZ_EXTERN struct xz_dec_lzma2 *xz_dec_lzma2_create(enum xz_mode mode, uint32_t dict_max); /* * Decode the LZMA2 properties (one byte) and reset the decoder. Return @@ -115,12 +112,10 @@ XZ_EXTERN struct xz_dec_lzma2 *xz_dec_lzma2_create(enum xz_mode mode, * big enough, and XZ_OPTIONS_ERROR if props indicates something that this * decoder doesn't support. */ -XZ_EXTERN enum xz_ret xz_dec_lzma2_reset(struct xz_dec_lzma2 *s, - uint8_t props); +XZ_EXTERN enum xz_ret xz_dec_lzma2_reset(struct xz_dec_lzma2 *s, uint8_t props); /* Decode raw LZMA2 stream from b->in to b->out. */ -XZ_EXTERN enum xz_ret xz_dec_lzma2_run(struct xz_dec_lzma2 *s, - struct xz_buf *b); +XZ_EXTERN enum xz_ret xz_dec_lzma2_run(struct xz_dec_lzma2 *s, struct xz_buf *b); /* Free the memory allocated for the LZMA2 decoder. */ XZ_EXTERN void xz_dec_lzma2_end(struct xz_dec_lzma2 *s); @@ -145,9 +140,8 @@ XZ_EXTERN enum xz_ret xz_dec_bcj_reset(struct xz_dec_bcj *s, uint8_t id); * a BCJ filter in the chain. If the chain has only LZMA2, xz_dec_lzma2_run() * must be called directly. */ -XZ_EXTERN enum xz_ret xz_dec_bcj_run(struct xz_dec_bcj *s, - struct xz_dec_lzma2 *lzma2, - struct xz_buf *b); +XZ_EXTERN enum xz_ret xz_dec_bcj_run(struct xz_dec_bcj *s, struct xz_dec_lzma2 *lzma2, + struct xz_buf *b); /* Free the memory allocated for the BCJ filters. */ #define xz_dec_bcj_end(s) kfree(s) diff --git a/depends/xz-embedded/src/xz_stream.h b/depends/xz-embedded/src/xz_stream.h index 66cb5a70..c0e191e6 100644 --- a/depends/xz-embedded/src/xz_stream.h +++ b/depends/xz-embedded/src/xz_stream.h @@ -11,10 +11,9 @@ #define XZ_STREAM_H #if defined(__KERNEL__) && !XZ_INTERNAL_CRC32 -# include -# undef crc32 -# define xz_crc32(buf, size, crc) \ - (~crc32_le(~(uint32_t)(crc), buf, size)) +#include +#undef crc32 +#define xz_crc32(buf, size, crc) (~crc32_le(~(uint32_t)(crc), buf, size)) #endif /* @@ -42,14 +41,15 @@ */ typedef uint64_t vli_type; -#define VLI_MAX ((vli_type)-1 / 2) -#define VLI_UNKNOWN ((vli_type)-1) +#define VLI_MAX ((vli_type) - 1 / 2) +#define VLI_UNKNOWN ((vli_type) - 1) /* Maximum encoded size of a VLI */ #define VLI_BYTES_MAX (sizeof(vli_type) * 8 / 7) /* Integrity Check types */ -enum xz_check { +enum xz_check +{ XZ_CHECK_NONE = 0, XZ_CHECK_CRC32 = 1, XZ_CHECK_CRC64 = 4, diff --git a/depends/xz-embedded/xzminidec.c b/depends/xz-embedded/xzminidec.c index ba074131..bb62c3ac 100644 --- a/depends/xz-embedded/xzminidec.c +++ b/depends/xz-embedded/xzminidec.c @@ -29,10 +29,11 @@ int main(int argc, char **argv) enum xz_ret ret; const char *msg; - if (argc >= 2 && strcmp(argv[1], "--help") == 0) { + if (argc >= 2 && strcmp(argv[1], "--help") == 0) + { fputs("Uncompress a .xz file from stdin to stdout.\n" - "Arguments other than `--help' are ignored.\n", - stdout); + "Arguments other than `--help' are ignored.\n", + stdout); return 0; } @@ -46,7 +47,8 @@ int main(int argc, char **argv) * is allocated once the headers have been parsed. */ s = xz_dec_init(XZ_DYNALLOC, 1 << 26); - if (s == NULL) { + if (s == NULL) + { msg = "Memory allocation failed\n"; goto error; } @@ -58,16 +60,20 @@ int main(int argc, char **argv) b.out_pos = 0; b.out_size = BUFSIZ; - while (true) { - if (b.in_pos == b.in_size) { + while (true) + { + if (b.in_pos == b.in_size) + { b.in_size = fread(in, 1, sizeof(in), stdin); b.in_pos = 0; } ret = xz_dec_run(s, &b); - if (b.out_pos == sizeof(out)) { - if (fwrite(out, 1, b.out_pos, stdout) != b.out_pos) { + if (b.out_pos == sizeof(out)) + { + if (fwrite(out, 1, b.out_pos, stdout) != b.out_pos) + { msg = "Write error\n"; goto error; } @@ -79,22 +85,25 @@ int main(int argc, char **argv) continue; #ifdef XZ_DEC_ANY_CHECK - if (ret == XZ_UNSUPPORTED_CHECK) { + if (ret == XZ_UNSUPPORTED_CHECK) + { fputs(argv[0], stderr); fputs(": ", stderr); fputs("Unsupported check; not verifying " - "file integrity\n", stderr); + "file integrity\n", + stderr); continue; } #endif - if (fwrite(out, 1, b.out_pos, stdout) != b.out_pos - || fclose(stdout)) { + if (fwrite(out, 1, b.out_pos, stdout) != b.out_pos || fclose(stdout)) + { msg = "Write error\n"; goto error; } - switch (ret) { + switch (ret) + { case XZ_STREAM_END: xz_dec_end(s); return 0; diff --git a/gui/ConsoleWindow.cpp b/gui/ConsoleWindow.cpp new file mode 100644 index 00000000..ec25b9cf --- /dev/null +++ b/gui/ConsoleWindow.cpp @@ -0,0 +1,135 @@ +/* Copyright 2013 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 "ConsoleWindow.h" +#include "ui_ConsoleWindow.h" + +#include +#include + +#include +#include + +ConsoleWindow::ConsoleWindow(MinecraftProcess *mcproc, QWidget *parent) : + QDialog(parent), + ui(new Ui::ConsoleWindow), + m_mayclose(true), + proc(mcproc) +{ + MultiMCPlatform::fixWM_CLASS(this); + ui->setupUi(this); + this->setWindowFlags(Qt::Window); + connect(mcproc, SIGNAL(ended(BaseInstance*)), this, SLOT(onEnded(BaseInstance*))); +} + +ConsoleWindow::~ConsoleWindow() +{ + delete ui; +} + +void ConsoleWindow::writeColor(QString text, const char *color) +{ + // append a paragraph + if (color != nullptr) + ui->text->appendHtml(QString("%2").arg(color).arg(text)); + else + ui->text->appendPlainText(text); + // scroll down + QScrollBar *bar = ui->text->verticalScrollBar(); + bar->setValue(bar->maximum()); +} + +void ConsoleWindow::write(QString data, MessageLevel::Enum mode) +{ + if (data.endsWith('\n')) + data = data.left(data.length()-1); + QStringList paragraphs = data.split('\n'); + for(QString ¶graph : paragraphs) + { + paragraph = paragraph.trimmed(); + } + + QListIterator iter(paragraphs); + if (mode == MessageLevel::MultiMC) + while(iter.hasNext()) + writeColor(iter.next(), "blue"); + else if (mode == MessageLevel::Error) + while(iter.hasNext()) + writeColor(iter.next(), "red"); + else if (mode == MessageLevel::Warning) + while(iter.hasNext()) + writeColor(iter.next(), "orange"); + else if (mode == MessageLevel::Fatal) + while(iter.hasNext()) + writeColor(iter.next(), "pink"); + else if (mode == MessageLevel::Debug) + while(iter.hasNext()) + writeColor(iter.next(), "green"); + // TODO: implement other MessageLevels + else + while(iter.hasNext()) + writeColor(iter.next()); +} + +void ConsoleWindow::clear() +{ + ui->text->clear(); +} + +void ConsoleWindow::on_closeButton_clicked() +{ + close(); +} + +void ConsoleWindow::setMayClose(bool mayclose) +{ + m_mayclose = mayclose; + if (mayclose) + ui->closeButton->setEnabled(true); + else + ui->closeButton->setEnabled(false); +} + +void ConsoleWindow::closeEvent(QCloseEvent * event) +{ + if(!m_mayclose) + event->ignore(); + else + QDialog::closeEvent(event); +} + +void ConsoleWindow::on_btnKillMinecraft_clicked() +{ + ui->btnKillMinecraft->setEnabled(false); + auto response = CustomMessageBox::selectable(this, tr("Kill Minecraft?"), + tr("This can cause the instance to get corrupted and should only be used if Minecraft is frozen for some reason"), + QMessageBox::Question, QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes)->exec(); + if (response == QMessageBox::Yes) + proc->killMinecraft(); + else + ui->btnKillMinecraft->setEnabled(true); +} + +void ConsoleWindow::onEnded(BaseInstance *instance) +{ + ui->btnKillMinecraft->setEnabled(false); + + // TODO: Might need an option to forcefully close, even on an error + if(instance->settings().get("AutoCloseConsole").toBool()) + { + // TODO: Check why this doesn't work + if (!proc->exitCode()) this->close(); + } +} diff --git a/gui/ConsoleWindow.h b/gui/ConsoleWindow.h new file mode 100644 index 00000000..0ed35554 --- /dev/null +++ b/gui/ConsoleWindow.h @@ -0,0 +1,79 @@ +/* Copyright 2013 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 +#include "logic/MinecraftProcess.h" + +namespace Ui +{ +class ConsoleWindow; +} + +class ConsoleWindow : public QDialog +{ + Q_OBJECT + +public: + explicit ConsoleWindow(MinecraftProcess *proc, QWidget *parent = 0); + ~ConsoleWindow(); + + /** + * @brief specify if the window is allowed to close + * @param mayclose + * used to keep it alive while MC runs + */ + void setMayClose(bool mayclose); + +public +slots: + /** + * @brief write a string + * @param data the string + * @param mode the WriteMode + * lines have to be put through this as a whole! + */ + void write(QString data, MessageLevel::Enum level = MessageLevel::MultiMC); + + /** + * @brief write a colored paragraph + * @param data the string + * @param color the css color name + * this will only insert a single paragraph. + * \n are ignored. a real \n is always appended. + */ + void writeColor(QString data, const char *color = nullptr); + + /** + * @brief clear the text widget + */ + void clear(); + +private +slots: + void on_closeButton_clicked(); + void on_btnKillMinecraft_clicked(); + void onEnded(BaseInstance *instance); + +protected: + void closeEvent(QCloseEvent *); + +private: + Ui::ConsoleWindow *ui; + MinecraftProcess *proc; + bool m_mayclose; +}; + diff --git a/gui/ConsoleWindow.ui b/gui/ConsoleWindow.ui new file mode 100644 index 00000000..8dc80015 --- /dev/null +++ b/gui/ConsoleWindow.ui @@ -0,0 +1,85 @@ + + + ConsoleWindow + + + + 0 + 0 + 600 + 400 + + + + MultiMC Console + + + + 0 + + + 0 + + + 0 + + + + + + 10 + + + + false + + + true + + + + + + Qt::LinksAccessibleByKeyboard|Qt::LinksAccessibleByMouse|Qt::TextBrowserInteraction|Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse + + + false + + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Kill Minecraft + + + + + + + Close + + + + + + + + + + diff --git a/gui/CopyInstanceDialog.cpp b/gui/CopyInstanceDialog.cpp deleted file mode 100644 index 1e0b9e6c..00000000 --- a/gui/CopyInstanceDialog.cpp +++ /dev/null @@ -1,84 +0,0 @@ -/* Copyright 2013 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 -#include "CopyInstanceDialog.h" -#include "ui_CopyInstanceDialog.h" - -#include "logic/InstanceFactory.h" -#include "logic/BaseVersion.h" -#include "logic/lists/IconList.h" -#include "logic/lists/MinecraftVersionList.h" -#include "logic/tasks/Task.h" -#include - -#include "gui/platform.h" -#include "versionselectdialog.h" -#include "ProgressDialog.h" -#include "IconPickerDialog.h" - -#include -#include - -CopyInstanceDialog::CopyInstanceDialog(BaseInstance *original, QWidget *parent) - : m_original(original), QDialog(parent), ui(new Ui::CopyInstanceDialog) -{ - MultiMCPlatform::fixWM_CLASS(this); - ui->setupUi(this); - resize(minimumSizeHint()); - layout()->setSizeConstraint(QLayout::SetFixedSize); - - InstIconKey = original->iconKey(); - ui->iconButton->setIcon(MMC->icons()->getIcon(InstIconKey)); - ui->instNameTextBox->setText(original->name()); - ui->instNameTextBox->setFocus(); -} - -CopyInstanceDialog::~CopyInstanceDialog() -{ - delete ui; -} - -void CopyInstanceDialog::updateDialogState() -{ - ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(!instName().isEmpty()); -} - -QString CopyInstanceDialog::instName() const -{ - return ui->instNameTextBox->text(); -} - -QString CopyInstanceDialog::iconKey() const -{ - return InstIconKey; -} - -void CopyInstanceDialog::on_iconButton_clicked() -{ - IconPickerDialog dlg(this); - dlg.exec(InstIconKey); - - if (dlg.result() == QDialog::Accepted) - { - InstIconKey = dlg.selectedIconKey; - ui->iconButton->setIcon(MMC->icons()->getIcon(InstIconKey)); - } -} - -void CopyInstanceDialog::on_instNameTextBox_textChanged(const QString &arg1) -{ - updateDialogState(); -} diff --git a/gui/CopyInstanceDialog.h b/gui/CopyInstanceDialog.h deleted file mode 100644 index 7ab366e2..00000000 --- a/gui/CopyInstanceDialog.h +++ /dev/null @@ -1,50 +0,0 @@ -/* Copyright 2013 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 -#include "logic/BaseVersion.h" - -class BaseInstance; - -namespace Ui -{ -class CopyInstanceDialog; -} - -class CopyInstanceDialog : public QDialog -{ - Q_OBJECT - -public: - explicit CopyInstanceDialog(BaseInstance *original, QWidget *parent = 0); - ~CopyInstanceDialog(); - - void updateDialogState(); - - QString instName() const; - QString iconKey() const; - -private -slots: - void on_iconButton_clicked(); - void on_instNameTextBox_textChanged(const QString &arg1); - -private: - Ui::CopyInstanceDialog *ui; - QString InstIconKey; - BaseInstance *m_original; -}; diff --git a/gui/CopyInstanceDialog.ui b/gui/CopyInstanceDialog.ui deleted file mode 100644 index 1327ce0b..00000000 --- a/gui/CopyInstanceDialog.ui +++ /dev/null @@ -1,134 +0,0 @@ - - - CopyInstanceDialog - - - Qt::ApplicationModal - - - - 0 - 0 - 345 - 205 - - - - Copy Instance - - - - :/icons/toolbar/copy:/icons/toolbar/copy - - - true - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - :/icons/instances/infinity:/icons/instances/infinity - - - - 80 - 80 - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - Name - - - - - - - Qt::Horizontal - - - - - - - Qt::Horizontal - - - QDialogButtonBox::Cancel|QDialogButtonBox::Ok - - - - - - - - - - - buttonBox - accepted() - CopyInstanceDialog - accept() - - - 248 - 254 - - - 157 - 274 - - - - - buttonBox - rejected() - CopyInstanceDialog - reject() - - - 316 - 260 - - - 286 - 274 - - - - - diff --git a/gui/CustomMessageBox.cpp b/gui/CustomMessageBox.cpp deleted file mode 100644 index e55ebbbb..00000000 --- a/gui/CustomMessageBox.cpp +++ /dev/null @@ -1,19 +0,0 @@ -#include "CustomMessageBox.h" - -namespace CustomMessageBox -{ - QMessageBox *selectable(QWidget *parent, const QString &title, const QString &text, - QMessageBox::Icon icon, QMessageBox::StandardButtons buttons, - QMessageBox::StandardButton defaultButton) - { - QMessageBox *messageBox = new QMessageBox(parent); - messageBox->setWindowTitle(title); - messageBox->setText(text); - messageBox->setStandardButtons(buttons); - messageBox->setDefaultButton(defaultButton); - messageBox->setTextInteractionFlags(Qt::TextSelectableByMouse); - messageBox->setIcon(icon); - - return messageBox; - } -} diff --git a/gui/CustomMessageBox.h b/gui/CustomMessageBox.h deleted file mode 100644 index 145651ec..00000000 --- a/gui/CustomMessageBox.h +++ /dev/null @@ -1,11 +0,0 @@ -#pragma once - -#include - -namespace CustomMessageBox -{ - QMessageBox *selectable(QWidget *parent, const QString &title, const QString &text, - QMessageBox::Icon icon = QMessageBox::NoIcon, - QMessageBox::StandardButtons buttons = QMessageBox::Ok, - QMessageBox::StandardButton defaultButton = QMessageBox::NoButton); -} diff --git a/gui/EditNotesDialog.cpp b/gui/EditNotesDialog.cpp deleted file mode 100644 index 535ca804..00000000 --- a/gui/EditNotesDialog.cpp +++ /dev/null @@ -1,29 +0,0 @@ -#include "EditNotesDialog.h" -#include "ui_EditNotesDialog.h" -#include "gui/platform.h" - -#include -#include - -EditNotesDialog::EditNotesDialog( QString notes, QString name, QWidget* parent ) : - m_instance_notes(notes), - m_instance_name(name), - QDialog(parent), - ui(new Ui::EditNotesDialog) -{ - MultiMCPlatform::fixWM_CLASS(this); - ui->setupUi(this); - ui->noteEditor->setText(notes); - setWindowTitle(tr("Edit notes of %1").arg(m_instance_name)); - //connect(ui->closeButton, SIGNAL(clicked()), SLOT(close())); -} - -EditNotesDialog::~EditNotesDialog() -{ - delete ui; -} - -QString EditNotesDialog::getText() -{ - return ui->noteEditor->toPlainText(); -} diff --git a/gui/EditNotesDialog.h b/gui/EditNotesDialog.h deleted file mode 100644 index 582e019f..00000000 --- a/gui/EditNotesDialog.h +++ /dev/null @@ -1,20 +0,0 @@ -#pragma once -#include - -namespace Ui { -class EditNotesDialog; -} - -class EditNotesDialog : public QDialog -{ - Q_OBJECT - -public: - explicit EditNotesDialog(QString notes, QString name, QWidget *parent = 0); - ~EditNotesDialog(); - QString getText(); -private: - Ui::EditNotesDialog *ui; - QString m_instance_name; - QString m_instance_notes; -}; diff --git a/gui/EditNotesDialog.ui b/gui/EditNotesDialog.ui deleted file mode 100644 index 487dfb84..00000000 --- a/gui/EditNotesDialog.ui +++ /dev/null @@ -1,77 +0,0 @@ - - - EditNotesDialog - - - - 0 - 0 - 459 - 399 - - - - Edit Notes - - - - - - Qt::ScrollBarAlwaysOn - - - false - - - Qt::LinksAccessibleByKeyboard|Qt::LinksAccessibleByMouse|Qt::TextBrowserInteraction|Qt::TextEditable|Qt::TextEditorInteraction|Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse - - - - - - - Qt::Horizontal - - - QDialogButtonBox::Cancel|QDialogButtonBox::Ok - - - - - - - - - buttonBox - accepted() - EditNotesDialog - accept() - - - 248 - 254 - - - 157 - 274 - - - - - buttonBox - rejected() - EditNotesDialog - reject() - - - 316 - 260 - - - 286 - 274 - - - - - diff --git a/gui/IconPickerDialog.cpp b/gui/IconPickerDialog.cpp deleted file mode 100644 index ebacf87c..00000000 --- a/gui/IconPickerDialog.cpp +++ /dev/null @@ -1,147 +0,0 @@ -#include -#include "IconPickerDialog.h" -#include "instancedelegate.h" -#include "ui_IconPickerDialog.h" -#include "logic/lists/IconList.h" -#include "gui/platform.h" -#include -#include -#include - -IconPickerDialog::IconPickerDialog(QWidget *parent) : - QDialog(parent), - ui(new Ui::IconPickerDialog) -{ - MultiMCPlatform::fixWM_CLASS(this); - ui->setupUi(this); - setWindowModality(Qt::WindowModal); - - auto contentsWidget = ui->iconView; - contentsWidget->setViewMode(QListView::IconMode); - contentsWidget->setFlow(QListView::LeftToRight); - contentsWidget->setIconSize(QSize(48, 48)); - contentsWidget->setMovement(QListView::Static); - contentsWidget->setResizeMode(QListView::Adjust); - contentsWidget->setSelectionMode(QAbstractItemView::SingleSelection); - contentsWidget->setSpacing(5); - contentsWidget->setWordWrap(false); - contentsWidget->setWrapping(true); - contentsWidget->setUniformItemSizes(true); - contentsWidget->setTextElideMode(Qt::ElideRight); - contentsWidget->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel); - contentsWidget->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn); - contentsWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - contentsWidget->setItemDelegate(new ListViewDelegate()); - - //contentsWidget->setAcceptDrops(true); - contentsWidget->setDropIndicatorShown(true); - contentsWidget->viewport()->setAcceptDrops(true); - contentsWidget->setDragDropMode(QAbstractItemView::DropOnly); - contentsWidget->setDefaultDropAction(Qt::CopyAction); - - contentsWidget->installEventFilter(this); - - contentsWidget->setModel(MMC->icons().get()); - - auto buttonAdd = ui->buttonBox->addButton(tr("Add Icon"),QDialogButtonBox::ResetRole); - auto buttonRemove = ui->buttonBox->addButton(tr("Remove Icon"),QDialogButtonBox::ResetRole); - - - connect(buttonAdd,SIGNAL(clicked(bool)),SLOT(addNewIcon())); - connect(buttonRemove,SIGNAL(clicked(bool)),SLOT(removeSelectedIcon())); - - connect - ( - contentsWidget, - SIGNAL(doubleClicked(QModelIndex)), - SLOT(activated(QModelIndex)) - ); - - connect - ( - contentsWidget->selectionModel(), - SIGNAL(selectionChanged(QItemSelection,QItemSelection)), - SLOT(selectionChanged(QItemSelection,QItemSelection)) - ); -} -bool IconPickerDialog::eventFilter ( QObject* obj, QEvent* evt) -{ - if(obj != ui->iconView) - return QDialog::eventFilter(obj ,evt); - if (evt->type() != QEvent::KeyPress) - { - return QDialog::eventFilter(obj ,evt); - } - QKeyEvent *keyEvent = static_cast(evt); - switch(keyEvent->key()) - { - case Qt::Key_Delete: - removeSelectedIcon(); - return true; - case Qt::Key_Plus: - addNewIcon(); - return true; - default: - break; - } - return QDialog::eventFilter(obj ,evt); -} - -void IconPickerDialog::addNewIcon() -{ - //: The title of the select icons open file dialog - QString selectIcons = tr("Select Icons"); - //: The type of icon files - QStringList fileNames = QFileDialog::getOpenFileNames(this, selectIcons, QString(), tr("Icons") + "(*.png *.jpg *.jpeg)"); - MMC->icons()->installIcons(fileNames); -} - -void IconPickerDialog::removeSelectedIcon() -{ - MMC->icons()->deleteIcon(selectedIconKey); -} - - -void IconPickerDialog::activated ( QModelIndex index ) -{ - selectedIconKey = index.data(Qt::UserRole).toString(); - accept(); -} - - -void IconPickerDialog::selectionChanged ( QItemSelection selected, QItemSelection deselected ) -{ - if(selected.empty()) - return; - - QString key = selected.first().indexes().first().data(Qt::UserRole).toString(); - if(!key.isEmpty()) - selectedIconKey = key; -} - -int IconPickerDialog::exec ( QString selection ) -{ - auto list = MMC->icons(); - auto contentsWidget = ui->iconView; - selectedIconKey = selection; - - - int index_nr = list->getIconIndex(selection); - auto model_index = list->index(index_nr); - contentsWidget->selectionModel()->select(model_index, QItemSelectionModel::Current | QItemSelectionModel::Select); - - QMetaObject::invokeMethod(this, "delayed_scroll", Qt::QueuedConnection, Q_ARG(QModelIndex,model_index)); - return QDialog::exec(); -} - -void IconPickerDialog::delayed_scroll ( QModelIndex model_index ) -{ - auto contentsWidget = ui->iconView; - contentsWidget->scrollTo(model_index); -} - - -IconPickerDialog::~IconPickerDialog() -{ - delete ui; -} diff --git a/gui/IconPickerDialog.h b/gui/IconPickerDialog.h deleted file mode 100644 index 96fc61ff..00000000 --- a/gui/IconPickerDialog.h +++ /dev/null @@ -1,29 +0,0 @@ -#pragma once -#include -#include - -namespace Ui { -class IconPickerDialog; -} - -class IconPickerDialog : public QDialog -{ - Q_OBJECT - -public: - explicit IconPickerDialog(QWidget *parent = 0); - ~IconPickerDialog(); - int exec(QString selection); - QString selectedIconKey; -protected: - virtual bool eventFilter ( QObject* , QEvent* ); -private: - Ui::IconPickerDialog *ui; - -private slots: - void selectionChanged ( QItemSelection,QItemSelection ); - void activated ( QModelIndex ); - void delayed_scroll ( QModelIndex ); - void addNewIcon(); - void removeSelectedIcon(); -}; diff --git a/gui/IconPickerDialog.ui b/gui/IconPickerDialog.ui deleted file mode 100644 index c548edfb..00000000 --- a/gui/IconPickerDialog.ui +++ /dev/null @@ -1,67 +0,0 @@ - - - IconPickerDialog - - - - 0 - 0 - 676 - 555 - - - - Pick icon - - - - - - - - - Qt::Horizontal - - - QDialogButtonBox::Cancel|QDialogButtonBox::Ok - - - - - - - - - buttonBox - accepted() - IconPickerDialog - accept() - - - 248 - 254 - - - 157 - 274 - - - - - buttonBox - rejected() - IconPickerDialog - reject() - - - 316 - 260 - - - 286 - 274 - - - - - diff --git a/gui/LabeledToolButton.cpp b/gui/LabeledToolButton.cpp deleted file mode 100644 index be84d1b7..00000000 --- a/gui/LabeledToolButton.cpp +++ /dev/null @@ -1,72 +0,0 @@ -#include -#include -#include -#include -#include "LabeledToolButton.h" -#include - - -/* - * - * Tool Button with a label on it, instead of the normal text rendering - * - */ - -LabeledToolButton::LabeledToolButton(QWidget * parent) - : QToolButton(parent) - , m_label(new QLabel(this)) -{ - //QToolButton::setText(" "); - m_label->setWordWrap(true); - m_label->setMouseTracking(false); - m_label->setAlignment(Qt::AlignCenter); - m_label->setTextInteractionFlags(Qt::NoTextInteraction); - // somehow, this makes word wrap work in the QLabel. yay. - m_label->setMinimumWidth(100); -} - -QString LabeledToolButton::text() const -{ - return m_label->text(); -} - -void LabeledToolButton::setText(const QString & text) -{ - m_label->setText(text); -} - -/*! - \reimp -*/ -QSize LabeledToolButton::sizeHint() const -{ - /* - Q_D(const QToolButton); - if (d->sizeHint.isValid()) - return d->sizeHint; - */ - ensurePolished(); - - int w = 0, h = 0; - QStyleOptionToolButton opt; - initStyleOption(&opt); - QSize sz =m_label->sizeHint(); - w = sz.width(); - h = sz.height(); - - opt.rect.setSize(QSize(w, h)); // PM_MenuButtonIndicator depends on the height - if (popupMode() == MenuButtonPopup) - w += style()->pixelMetric(QStyle::PM_MenuButtonIndicator, &opt, this); - - QSize rawSize = style()->sizeFromContents(QStyle::CT_ToolButton, &opt, QSize(w, h), this); - QSize sizeHint = rawSize.expandedTo(QApplication::globalStrut()); - return sizeHint; -} - - - -void LabeledToolButton::resizeEvent(QResizeEvent * event) -{ - m_label->setGeometry(QRect(4, 4, width()-8, height()-8)); - QWidget::resizeEvent(event); -} diff --git a/gui/LabeledToolButton.h b/gui/LabeledToolButton.h deleted file mode 100644 index 24ef798a..00000000 --- a/gui/LabeledToolButton.h +++ /dev/null @@ -1,22 +0,0 @@ -#pragma once - -#include -#include - -class QLabel; - -class LabeledToolButton : public QToolButton -{ - Q_OBJECT - - QLabel * m_label; - -public: - LabeledToolButton(QWidget * parent = 0); - - QString text() const; - void setText(const QString & text); - virtual QSize sizeHint() const; -protected: - void resizeEvent(QResizeEvent * event); -}; diff --git a/gui/LegacyModEditDialog.cpp b/gui/LegacyModEditDialog.cpp deleted file mode 100644 index a7021bf9..00000000 --- a/gui/LegacyModEditDialog.cpp +++ /dev/null @@ -1,393 +0,0 @@ -/* Copyright 2013 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 "MultiMC.h" -#include "LegacyModEditDialog.h" -#include "ModEditDialogCommon.h" -#include "versionselectdialog.h" -#include "ProgressDialog.h" -#include "ui_LegacyModEditDialog.h" -#include "logic/ModList.h" -#include "logic/lists/ForgeVersionList.h" -#include "gui/platform.h" - -#include -#include -//#include -#include -#include -#include - -LegacyModEditDialog::LegacyModEditDialog(LegacyInstance *inst, QWidget *parent) - : m_inst(inst), QDialog(parent), ui(new Ui::LegacyModEditDialog) -{ - MultiMCPlatform::fixWM_CLASS(this); - ui->setupUi(this); - - // Jar mods - { - ensureFolderPathExists(m_inst->jarModsDir()); - m_jarmods = m_inst->jarModList(); - ui->jarModsTreeView->setModel(m_jarmods.get()); -#ifndef Q_OS_LINUX - // FIXME: internal DnD causes segfaults later - ui->jarModsTreeView->setDragDropMode(QAbstractItemView::DragDrop); - // FIXME: DnD is glitched with contiguous (we move only first item in selection) - ui->jarModsTreeView->setSelectionMode(QAbstractItemView::SingleSelection); -#endif - ui->jarModsTreeView->installEventFilter(this); - m_jarmods->startWatching(); - auto smodel = ui->jarModsTreeView->selectionModel(); - connect(smodel, SIGNAL(currentChanged(QModelIndex, QModelIndex)), - SLOT(jarCurrent(QModelIndex, QModelIndex))); - } - // Core mods - { - ensureFolderPathExists(m_inst->coreModsDir()); - m_coremods = m_inst->coreModList(); - ui->coreModsTreeView->setModel(m_coremods.get()); - ui->coreModsTreeView->installEventFilter(this); - m_coremods->startWatching(); - auto smodel = ui->coreModsTreeView->selectionModel(); - connect(smodel, SIGNAL(currentChanged(QModelIndex, QModelIndex)), - SLOT(coreCurrent(QModelIndex, QModelIndex))); - } - // Loader mods - { - ensureFolderPathExists(m_inst->loaderModsDir()); - m_mods = m_inst->loaderModList(); - ui->loaderModTreeView->setModel(m_mods.get()); - ui->loaderModTreeView->installEventFilter(this); - m_mods->startWatching(); - auto smodel = ui->loaderModTreeView->selectionModel(); - connect(smodel, SIGNAL(currentChanged(QModelIndex, QModelIndex)), - SLOT(loaderCurrent(QModelIndex, QModelIndex))); - } - // texture packs - { - ensureFolderPathExists(m_inst->texturePacksDir()); - m_texturepacks = m_inst->texturePackList(); - ui->texPackTreeView->setModel(m_texturepacks.get()); - ui->texPackTreeView->installEventFilter(this); - m_texturepacks->startWatching(); - } -} - -LegacyModEditDialog::~LegacyModEditDialog() -{ - m_mods->stopWatching(); - m_coremods->stopWatching(); - m_jarmods->stopWatching(); - m_texturepacks->stopWatching(); - delete ui; -} - -bool LegacyModEditDialog::coreListFilter(QKeyEvent *keyEvent) -{ - switch (keyEvent->key()) - { - case Qt::Key_Delete: - on_rmCoreBtn_clicked(); - return true; - case Qt::Key_Plus: - on_addCoreBtn_clicked(); - return true; - default: - break; - } - return QDialog::eventFilter(ui->coreModsTreeView, keyEvent); -} - -bool LegacyModEditDialog::jarListFilter(QKeyEvent *keyEvent) -{ - switch (keyEvent->key()) - { - case Qt::Key_Up: - { - if (keyEvent->modifiers() & Qt::ControlModifier) - { - on_moveJarUpBtn_clicked(); - return true; - } - break; - } - case Qt::Key_Down: - { - if (keyEvent->modifiers() & Qt::ControlModifier) - { - on_moveJarDownBtn_clicked(); - return true; - } - break; - } - case Qt::Key_Delete: - on_rmJarBtn_clicked(); - return true; - case Qt::Key_Plus: - on_addJarBtn_clicked(); - return true; - default: - break; - } - return QDialog::eventFilter(ui->jarModsTreeView, keyEvent); -} - -bool LegacyModEditDialog::loaderListFilter(QKeyEvent *keyEvent) -{ - switch (keyEvent->key()) - { - case Qt::Key_Delete: - on_rmModBtn_clicked(); - return true; - case Qt::Key_Plus: - on_addModBtn_clicked(); - return true; - default: - break; - } - return QDialog::eventFilter(ui->loaderModTreeView, keyEvent); -} - -bool LegacyModEditDialog::texturePackListFilter(QKeyEvent *keyEvent) -{ - switch (keyEvent->key()) - { - case Qt::Key_Delete: - on_rmTexPackBtn_clicked(); - return true; - case Qt::Key_Plus: - on_addTexPackBtn_clicked(); - return true; - default: - break; - } - return QDialog::eventFilter(ui->texPackTreeView, keyEvent); -} - -bool LegacyModEditDialog::eventFilter(QObject *obj, QEvent *ev) -{ - if (ev->type() != QEvent::KeyPress) - { - return QDialog::eventFilter(obj, ev); - } - QKeyEvent *keyEvent = static_cast(ev); - if (obj == ui->jarModsTreeView) - return jarListFilter(keyEvent); - if (obj == ui->coreModsTreeView) - return coreListFilter(keyEvent); - if (obj == ui->loaderModTreeView) - return loaderListFilter(keyEvent); - if (obj == ui->texPackTreeView) - return texturePackListFilter(keyEvent); - return QDialog::eventFilter(obj, ev); -} - -void LegacyModEditDialog::on_addCoreBtn_clicked() -{ - //: Title of core mod selection dialog - QStringList fileNames = QFileDialog::getOpenFileNames(this, tr("Select Core Mods")); - for (auto filename : fileNames) - { - m_coremods->stopWatching(); - m_coremods->installMod(QFileInfo(filename)); - m_coremods->startWatching(); - } -} -void LegacyModEditDialog::on_addForgeBtn_clicked() -{ - VersionSelectDialog vselect(MMC->forgelist().get(), tr("Select Forge version"), this); - vselect.setFilter(1, m_inst->intendedVersionId()); - if (vselect.exec() && vselect.selectedVersion()) - { - ForgeVersionPtr forge = - std::dynamic_pointer_cast(vselect.selectedVersion()); - if (!forge) - return; - auto entry = MMC->metacache()->resolveEntry("minecraftforge", forge->filename); - if (entry->stale) - { - NetJob *fjob = new NetJob("Forge download"); - fjob->addNetAction(CacheDownload::make(forge->universal_url, entry)); - ProgressDialog dlg(this); - dlg.exec(fjob); - if (dlg.result() == QDialog::Accepted) - { - m_jarmods->stopWatching(); - m_jarmods->installMod(QFileInfo(entry->getFullPath())); - m_jarmods->startWatching(); - } - else - { - // failed to download forge :/ - } - } - else - { - m_jarmods->stopWatching(); - m_jarmods->installMod(QFileInfo(entry->getFullPath())); - m_jarmods->startWatching(); - } - } -} -void LegacyModEditDialog::on_addJarBtn_clicked() -{ - //: Title of jar mod selection dialog - QStringList fileNames = QFileDialog::getOpenFileNames(this, tr("Select Jar Mods")); - for (auto filename : fileNames) - { - m_jarmods->stopWatching(); - m_jarmods->installMod(QFileInfo(filename)); - m_jarmods->startWatching(); - } -} -void LegacyModEditDialog::on_addModBtn_clicked() -{ - //: Title of regular mod selection dialog - QStringList fileNames = QFileDialog::getOpenFileNames(this, tr("Select Loader Mods")); - for (auto filename : fileNames) - { - m_mods->stopWatching(); - m_mods->installMod(QFileInfo(filename)); - m_mods->startWatching(); - } -} -void LegacyModEditDialog::on_addTexPackBtn_clicked() -{ - //: Title of texture pack selection dialog - QStringList fileNames = QFileDialog::getOpenFileNames(this, tr("Select Texture Packs")); - for (auto filename : fileNames) - { - m_texturepacks->stopWatching(); - m_texturepacks->installMod(QFileInfo(filename)); - m_texturepacks->startWatching(); - } -} - -void LegacyModEditDialog::on_moveJarDownBtn_clicked() -{ - int first, last; - auto list = ui->jarModsTreeView->selectionModel()->selectedRows(); - - if (!lastfirst(list, first, last)) - return; - - m_jarmods->moveModsDown(first, last); -} -void LegacyModEditDialog::on_moveJarUpBtn_clicked() -{ - int first, last; - auto list = ui->jarModsTreeView->selectionModel()->selectedRows(); - - if (!lastfirst(list, first, last)) - return; - m_jarmods->moveModsUp(first, last); -} -void LegacyModEditDialog::on_rmCoreBtn_clicked() -{ - int first, last; - auto list = ui->coreModsTreeView->selectionModel()->selectedRows(); - - if (!lastfirst(list, first, last)) - return; - m_coremods->stopWatching(); - m_coremods->deleteMods(first, last); - m_coremods->startWatching(); -} -void LegacyModEditDialog::on_rmJarBtn_clicked() -{ - int first, last; - auto list = ui->jarModsTreeView->selectionModel()->selectedRows(); - - if (!lastfirst(list, first, last)) - return; - m_jarmods->stopWatching(); - m_jarmods->deleteMods(first, last); - m_jarmods->startWatching(); -} -void LegacyModEditDialog::on_rmModBtn_clicked() -{ - int first, last; - auto list = ui->loaderModTreeView->selectionModel()->selectedRows(); - - if (!lastfirst(list, first, last)) - return; - m_mods->stopWatching(); - m_mods->deleteMods(first, last); - m_mods->startWatching(); -} -void LegacyModEditDialog::on_rmTexPackBtn_clicked() -{ - int first, last; - auto list = ui->texPackTreeView->selectionModel()->selectedRows(); - - if (!lastfirst(list, first, last)) - return; - m_texturepacks->stopWatching(); - m_texturepacks->deleteMods(first, last); - m_texturepacks->startWatching(); -} -void LegacyModEditDialog::on_viewCoreBtn_clicked() -{ - openDirInDefaultProgram(m_inst->coreModsDir(), true); -} -void LegacyModEditDialog::on_viewModBtn_clicked() -{ - openDirInDefaultProgram(m_inst->loaderModsDir(), true); -} -void LegacyModEditDialog::on_viewTexPackBtn_clicked() -{ - openDirInDefaultProgram(m_inst->texturePacksDir(), true); -} - -void LegacyModEditDialog::on_buttonBox_rejected() -{ - close(); -} - -void LegacyModEditDialog::jarCurrent(QModelIndex current, QModelIndex previous) -{ - if(!current.isValid()) - { - ui->jarMIFrame->clear(); - return; - } - int row = current.row(); - Mod &m = m_jarmods->operator[](row); - ui->jarMIFrame->updateWithMod(m); -} - -void LegacyModEditDialog::coreCurrent(QModelIndex current, QModelIndex previous) -{ - if(!current.isValid()) - { - ui->coreMIFrame->clear(); - return; - } - int row = current.row(); - Mod &m = m_coremods->operator[](row); - ui->coreMIFrame->updateWithMod(m); -} - -void LegacyModEditDialog::loaderCurrent(QModelIndex current, QModelIndex previous) -{ - if(!current.isValid()) - { - ui->loaderMIFrame->clear(); - return; - } - int row = current.row(); - Mod &m = m_mods->operator[](row); - ui->loaderMIFrame->updateWithMod(m); -} diff --git a/gui/LegacyModEditDialog.h b/gui/LegacyModEditDialog.h deleted file mode 100644 index d5582aef..00000000 --- a/gui/LegacyModEditDialog.h +++ /dev/null @@ -1,78 +0,0 @@ -/* Copyright 2013 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 -#include "logic/LegacyInstance.h" -#include - -namespace Ui -{ -class LegacyModEditDialog; -} - -class LegacyModEditDialog : public QDialog -{ - Q_OBJECT - -public: - explicit LegacyModEditDialog(LegacyInstance *inst, QWidget *parent = 0); - ~LegacyModEditDialog(); - -private -slots: - - void on_addJarBtn_clicked(); - void on_rmJarBtn_clicked(); - void on_addForgeBtn_clicked(); - void on_moveJarUpBtn_clicked(); - void on_moveJarDownBtn_clicked(); - - void on_addCoreBtn_clicked(); - void on_rmCoreBtn_clicked(); - void on_viewCoreBtn_clicked(); - - void on_addModBtn_clicked(); - void on_rmModBtn_clicked(); - void on_viewModBtn_clicked(); - - void on_addTexPackBtn_clicked(); - void on_rmTexPackBtn_clicked(); - void on_viewTexPackBtn_clicked(); - - // Questionable: SettingsDialog doesn't need this for some reason? - void on_buttonBox_rejected(); - - void jarCurrent(QModelIndex current, QModelIndex previous); - void coreCurrent(QModelIndex current, QModelIndex previous); - void loaderCurrent(QModelIndex current, QModelIndex previous); - -protected: - bool eventFilter(QObject *obj, QEvent *ev); - bool jarListFilter(QKeyEvent *ev); - bool coreListFilter(QKeyEvent *ev); - bool loaderListFilter(QKeyEvent *ev); - bool texturePackListFilter(QKeyEvent *ev); - -private: - Ui::LegacyModEditDialog *ui; - std::shared_ptr m_mods; - std::shared_ptr m_coremods; - std::shared_ptr m_jarmods; - std::shared_ptr m_texturepacks; - LegacyInstance *m_inst; - NetJobPtr forgeJob; -}; diff --git a/gui/LegacyModEditDialog.ui b/gui/LegacyModEditDialog.ui deleted file mode 100644 index bb0d9ef2..00000000 --- a/gui/LegacyModEditDialog.ui +++ /dev/null @@ -1,321 +0,0 @@ - - - LegacyModEditDialog - - - - 0 - 0 - 540 - 420 - - - - Dialog - - - - - - 0 - - - - Jar Mods - - - - - - - - Qt::ScrollBarAlwaysOn - - - Qt::ScrollBarAlwaysOff - - - - - - - - - &Add - - - - - - - &Remove - - - - - - - MCForge - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - Move &Up - - - - - - - Move &Down - - - - - - - - - - - QFrame::Plain - - - - - - - - Core Mods - - - - - - - - QAbstractItemView::DropOnly - - - - - - - - - &Add - - - - - - - &Remove - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - &View Folder - - - - - - - - - - - QFrame::StyledPanel - - - QFrame::Raised - - - - - - - - Loader Mods - - - - - - - - true - - - QAbstractItemView::DropOnly - - - - - - - - - &Add - - - - - - - &Remove - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - &View Folder - - - - - - - - - - - QFrame::StyledPanel - - - QFrame::Raised - - - - - - - - false - - - Texture Packs - - - - - - true - - - QAbstractItemView::DropOnly - - - - - - - - - &Add - - - - - - - &Remove - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - &View Folder - - - - - - - - - - - - - QDialogButtonBox::Close - - - - - - - - ModListView - QTreeView -
gui/ModListView.h
-
- - MCModInfoFrame - QFrame -
gui/MCModInfoFrame.h
- 1 -
-
- - -
diff --git a/gui/MCModInfoFrame.cpp b/gui/MCModInfoFrame.cpp deleted file mode 100644 index 55ef13f1..00000000 --- a/gui/MCModInfoFrame.cpp +++ /dev/null @@ -1,109 +0,0 @@ -/* Copyright 2013 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 "MCModInfoFrame.h" -#include "ui_MCModInfoFrame.h" -#include "CustomMessageBox.h" -#include -#include -void MCModInfoFrame::updateWithMod(Mod &m) -{ - if(m.type() == m.MOD_FOLDER) - { - clear(); - return; - } - - QString text = ""; - QString name = ""; - if(m.name().isEmpty()) name = m.id(); - else name = m.name(); - - if(m.homeurl().isEmpty()) text = name; - else text = "" + name + ""; - if(!m.authors().isEmpty()) text += " by " + m.authors(); - - setModText(text); - - if(m.description().isEmpty()) - { - setModDescription(tr("No description provided in mcmod.info")); - } - else - { - setModDescription(m.description()); - } -} - -void MCModInfoFrame::clear() -{ - setModText(tr("Select a mod to view title and authors...")); - setModDescription(tr("Select a mod to view description...")); -} - -MCModInfoFrame::MCModInfoFrame(QWidget *parent) : - QFrame(parent), - ui(new Ui::MCModInfoFrame) -{ - ui->setupUi(this); -} - -MCModInfoFrame::~MCModInfoFrame() -{ - delete ui; -} - -void MCModInfoFrame::setModText(QString text) -{ - ui->label_ModText->setText(text); -} - -void MCModInfoFrame::setModDescription(QString text) -{ - ui->label_ModDescription->setToolTip(""); - QString intermediatetext = text.trimmed(); - bool prev(false); - QChar rem('\n'); - QString finaltext; - finaltext.reserve(intermediatetext.size()); - foreach(const QChar& c, intermediatetext) - { - if(c == rem && prev){ - continue; - } - prev = c == rem; - finaltext += c; - } - QString labeltext; - labeltext.reserve(300); - if(finaltext.length() > 290) - { - ui->label_ModDescription->setOpenExternalLinks(false); - ui->label_ModDescription->setTextFormat(Qt::TextFormat::RichText); - desc = text; - labeltext.append("" + finaltext.left(287) + "..."); - QObject::connect(ui->label_ModDescription, &QLabel::linkActivated, this, &MCModInfoFrame::modDescEllipsisHandler); - } - else - { - ui->label_ModDescription->setTextFormat(Qt::TextFormat::PlainText); - labeltext.append(finaltext); - } - ui->label_ModDescription->setText(labeltext); -} -void MCModInfoFrame::modDescEllipsisHandler(const QString &link) -{ - CustomMessageBox::selectable(this, tr(""), desc)->show(); -} diff --git a/gui/MCModInfoFrame.h b/gui/MCModInfoFrame.h deleted file mode 100644 index 54c5d674..00000000 --- a/gui/MCModInfoFrame.h +++ /dev/null @@ -1,46 +0,0 @@ -/* Copyright 2013 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 -#include "logic/Mod.h" - -namespace Ui -{ -class MCModInfoFrame; -} - -class MCModInfoFrame : public QFrame -{ - Q_OBJECT - -public: - explicit MCModInfoFrame(QWidget *parent = 0); - ~MCModInfoFrame(); - - void setModText(QString text); - void setModDescription(QString text); - - void updateWithMod(Mod &m); - void clear(); - -public slots: - void modDescEllipsisHandler(const QString& link ); - -private: - Ui::MCModInfoFrame *ui; - QString desc; -}; diff --git a/gui/MCModInfoFrame.ui b/gui/MCModInfoFrame.ui deleted file mode 100644 index 60e0a65c..00000000 --- a/gui/MCModInfoFrame.ui +++ /dev/null @@ -1,68 +0,0 @@ - - - MCModInfoFrame - - - - 0 - 0 - 527 - 113 - - - - - 0 - 0 - - - - - 16777215 - 120 - - - - Frame - - - - - - Select a mod to view title and authors... - - - Qt::RichText - - - Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop - - - true - - - true - - - - - - - Select a mod to view description... - - - Qt::PlainText - - - Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop - - - true - - - - - - - - diff --git a/gui/MainWindow.cpp b/gui/MainWindow.cpp new file mode 100644 index 00000000..39e6dff2 --- /dev/null +++ b/gui/MainWindow.cpp @@ -0,0 +1,976 @@ +/* Copyright 2013 MultiMC Contributors + * + * Authors: Andrew Okin + * Peterix + * Orochimarufan + * + * 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 "MultiMC.h" + +#include "MainWindow.h" +#include "ui_MainWindow.h" +#include "keyring.h" + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "osutils.h" +#include "userutils.h" +#include "pathutils.h" + +#include "categorizedview.h" +#include "categorydrawer.h" + +#include "gui/Platform.h" + +#include "gui/widgets/InstanceDelegate.h" +#include "gui/widgets/LabeledToolButton.h" + +#include "gui/dialogs/SettingsDialog.h" +#include "gui/dialogs/NewInstanceDialog.h" +#include "gui/dialogs/LoginDialog.h" +#include "gui/dialogs/ProgressDialog.h" +#include "gui/dialogs/AboutDialog.h" +#include "gui/dialogs/VersionSelectDialog.h" +#include "gui/dialogs/CustomMessageBox.h" +#include "gui/dialogs/LwjglSelectDialog.h" +#include "gui/dialogs/InstanceSettings.h" +#include "gui/dialogs/IconPickerDialog.h" +#include "gui/dialogs/EditNotesDialog.h" +#include "gui/dialogs/CopyInstanceDialog.h" + +#include "gui/ConsoleWindow.h" + +#include "logic/lists/InstanceList.h" +#include "logic/lists/MinecraftVersionList.h" +#include "logic/lists/LwjglVersionList.h" +#include "logic/lists/IconList.h" +#include "logic/lists/JavaVersionList.h" + +#include "logic/net/LoginTask.h" + +#include "logic/BaseInstance.h" +#include "logic/InstanceFactory.h" +#include "logic/MinecraftProcess.h" +#include "logic/OneSixAssets.h" +#include "logic/OneSixUpdate.h" +#include "logic/JavaUtils.h" +#include "logic/NagUtils.h" + +#include "logic/LegacyInstance.h" + +MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) +{ + MultiMCPlatform::fixWM_CLASS(this); + ui->setupUi(this); + setWindowTitle(QString("MultiMC %1").arg(MMC->version().toString())); + + // Set the selected instance to null + m_selectedInstance = nullptr; + // Set active instance to null. + m_activeInst = nullptr; + + // OSX magic. + setUnifiedTitleAndToolBarOnMac(true); + + // The instance action toolbar customizations + { + // disabled until we have an instance selected + ui->instanceToolBar->setEnabled(false); + + // the rename label is inside the rename tool button + renameButton = new LabeledToolButton(); + renameButton->setText("Instance Name"); + renameButton->setToolTip(ui->actionRenameInstance->toolTip()); + connect(renameButton, SIGNAL(clicked(bool)), SLOT(on_actionRenameInstance_triggered())); + ui->instanceToolBar->insertWidget(ui->actionLaunchInstance, renameButton); + ui->instanceToolBar->insertSeparator(ui->actionLaunchInstance); + renameButton->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); + } + + // Create the instance list widget + { + view = new KCategorizedView(ui->centralWidget); + drawer = new KCategoryDrawer(view); + + view->setSelectionMode(QAbstractItemView::SingleSelection); + view->setCategoryDrawer(drawer); + view->setCollapsibleBlocks(true); + view->setViewMode(QListView::IconMode); + view->setFlow(QListView::LeftToRight); + view->setWordWrap(true); + view->setMouseTracking(true); + view->viewport()->setAttribute(Qt::WA_Hover); + auto delegate = new ListViewDelegate(); + view->setItemDelegate(delegate); + view->setSpacing(10); + view->setUniformItemWidths(true); + + // do not show ugly blue border on the mac + view->setAttribute(Qt::WA_MacShowFocusRect, false); + + view->installEventFilter(this); + + proxymodel = new InstanceProxyModel(this); +// proxymodel->setSortRole(KCategorizedSortFilterProxyModel::CategorySortRole); + //proxymodel->setFilterRole(KCategorizedSortFilterProxyModel::CategorySortRole); + // proxymodel->setDynamicSortFilter ( true ); + + // FIXME: instList should be global-ish, or at least not tied to the main window... + // maybe the application itself? + proxymodel->setSourceModel(MMC->instances().get()); + proxymodel->sort(0); + view->setFrameShape(QFrame::NoFrame); + view->setModel(proxymodel); + + ui->horizontalLayout->addWidget(view); + } + // The cat background + { + bool cat_enable = MMC->settings()->get("TheCat").toBool(); + ui->actionCAT->setChecked(cat_enable); + connect(ui->actionCAT, SIGNAL(toggled(bool)), SLOT(onCatToggled(bool))); + setCatBackground(cat_enable); + } + // start instance when double-clicked + connect(view, SIGNAL(doubleClicked(const QModelIndex &)), this, + SLOT(instanceActivated(const QModelIndex &))); + // track the selection -- update the instance toolbar + connect(view->selectionModel(), + SIGNAL(currentChanged(const QModelIndex &, const QModelIndex &)), this, + SLOT(instanceChanged(const QModelIndex &, const QModelIndex &))); + // model reset -> selection is invalid. All the instance pointers are wrong. + // FIXME: stop using POINTERS everywhere + connect(MMC->instances().get(), SIGNAL(dataIsInvalid()), SLOT(selectionBad())); + + m_statusLeft = new QLabel(tr("Instance type"), this); + m_statusRight = new QLabel(tr("Assets information"), this); + m_statusRight->setAlignment(Qt::AlignRight); + statusBar()->addPermanentWidget(m_statusLeft, 1); + statusBar()->addPermanentWidget(m_statusRight, 0); + + // run the things that load and download other things... FIXME: this is NOT the place + // FIXME: invisible actions in the background = NOPE. + { + if (!MMC->minecraftlist()->isLoaded()) + { + m_versionLoadTask = MMC->minecraftlist()->getLoadTask(); + startTask(m_versionLoadTask); + } + if (!MMC->lwjgllist()->isLoaded()) + { + MMC->lwjgllist()->loadList(); + } + assets_downloader = new OneSixAssets(); + connect(assets_downloader, SIGNAL(indexStarted()), SLOT(assetsIndexStarted())); + connect(assets_downloader, SIGNAL(filesStarted()), SLOT(assetsFilesStarted())); + connect(assets_downloader, SIGNAL(filesProgress(int, int, int)), + SLOT(assetsFilesProgress(int, int, int))); + connect(assets_downloader, SIGNAL(failed()), SLOT(assetsFailed())); + connect(assets_downloader, SIGNAL(finished()), SLOT(assetsFinished())); + assets_downloader->start(); + } +} + +MainWindow::~MainWindow() +{ + delete ui; + delete proxymodel; + delete drawer; + delete assets_downloader; +} + +bool MainWindow::eventFilter(QObject *obj, QEvent *ev) +{ + if (obj == view) + { + if (ev->type() == QEvent::KeyPress) + { + QKeyEvent *keyEvent = static_cast(ev); + switch (keyEvent->key()) + { + case Qt::Key_Enter: + case Qt::Key_Return: + on_actionLaunchInstance_triggered(); + return true; + case Qt::Key_Delete: + on_actionDeleteInstance_triggered(); + return true; + case Qt::Key_F5: + on_actionRefresh_triggered(); + return true; + case Qt::Key_F2: + on_actionRenameInstance_triggered(); + return true; + default: + break; + } + } + } + return QMainWindow::eventFilter(obj, ev); +} + +void MainWindow::onCatToggled(bool state) +{ + setCatBackground(state); + MMC->settings()->set("TheCat", state); +} + +void MainWindow::setCatBackground(bool enabled) +{ + if (enabled) + { + view->setStyleSheet("QListView" + "{" + "background-image: url(:/backgrounds/kitteh);" + "background-attachment: fixed;" + "background-clip: padding;" + "background-position: top right;" + "background-repeat: none;" + "background-color:palette(base);" + "}"); + } + else + { + view->setStyleSheet(QString()); + } +} + +void MainWindow::on_actionAddInstance_triggered() +{ + if (!MMC->minecraftlist()->isLoaded() && m_versionLoadTask && + m_versionLoadTask->isRunning()) + { + QEventLoop waitLoop; + waitLoop.connect(m_versionLoadTask, SIGNAL(failed(QString)), SLOT(quit())); + waitLoop.connect(m_versionLoadTask, SIGNAL(succeeded()), SLOT(quit())); + waitLoop.exec(); + } + + NewInstanceDialog newInstDlg(this); + if (!newInstDlg.exec()) + return; + + BaseInstance *newInstance = NULL; + + QString instancesDir = MMC->settings()->get("InstanceDir").toString(); + QString instDirName = DirNameFromString(newInstDlg.instName(), instancesDir); + QString instDir = PathCombine(instancesDir, instDirName); + + auto &loader = InstanceFactory::get(); + + auto error = loader.createInstance(newInstance, newInstDlg.selectedVersion(), instDir); + QString errorMsg = QString("Failed to create instance %1: ").arg(instDirName); + switch (error) + { + case InstanceFactory::NoCreateError: + newInstance->setName(newInstDlg.instName()); + newInstance->setIconKey(newInstDlg.iconKey()); + MMC->instances()->add(InstancePtr(newInstance)); + return; + + case InstanceFactory::InstExists: + { + errorMsg += "An instance with the given directory name already exists."; + CustomMessageBox::selectable(this, tr("Error"), errorMsg, QMessageBox::Warning)->show(); + break; + } + + case InstanceFactory::CantCreateDir: + { + errorMsg += "Failed to create the instance directory."; + CustomMessageBox::selectable(this, tr("Error"), errorMsg, QMessageBox::Warning)->show(); + break; + } + + default: + { + errorMsg += QString("Unknown instance loader error %1").arg(error); + CustomMessageBox::selectable(this, tr("Error"), errorMsg, QMessageBox::Warning)->show(); + break; + } + } +} + +void MainWindow::on_actionCopyInstance_triggered() +{ + if (!m_selectedInstance) + return; + + CopyInstanceDialog copyInstDlg(m_selectedInstance, this); + if (!copyInstDlg.exec()) + return; + + QString instancesDir = MMC->settings()->get("InstanceDir").toString(); + QString instDirName = DirNameFromString(copyInstDlg.instName(), instancesDir); + QString instDir = PathCombine(instancesDir, instDirName); + + auto &loader = InstanceFactory::get(); + + BaseInstance *newInstance = NULL; + auto error = loader.copyInstance(newInstance, m_selectedInstance, instDir); + + QString errorMsg = QString("Failed to create instance %1: ").arg(instDirName); + switch (error) + { + case InstanceFactory::NoCreateError: + newInstance->setName(copyInstDlg.instName()); + newInstance->setIconKey(copyInstDlg.iconKey()); + MMC->instances()->add(InstancePtr(newInstance)); + return; + + case InstanceFactory::InstExists: + { + errorMsg += "An instance with the given directory name already exists."; + CustomMessageBox::selectable(this, tr("Error"), errorMsg, QMessageBox::Warning)->show(); + break; + } + + case InstanceFactory::CantCreateDir: + { + errorMsg += "Failed to create the instance directory."; + CustomMessageBox::selectable(this, tr("Error"), errorMsg, QMessageBox::Warning)->show(); + break; + } + + default: + { + errorMsg += QString("Unknown instance loader error %1").arg(error); + CustomMessageBox::selectable(this, tr("Error"), errorMsg, QMessageBox::Warning)->show(); + break; + } + } +} + +void MainWindow::on_actionChangeInstIcon_triggered() +{ + if (!m_selectedInstance) + return; + + IconPickerDialog dlg(this); + dlg.exec(m_selectedInstance->iconKey()); + if (dlg.result() == QDialog::Accepted) + { + m_selectedInstance->setIconKey(dlg.selectedIconKey); + auto ico = MMC->icons()->getIcon(dlg.selectedIconKey); + ui->actionChangeInstIcon->setIcon(ico); + } +} + +void MainWindow::on_actionChangeInstGroup_triggered() +{ + if (!m_selectedInstance) + return; + + bool ok = false; + QString name(m_selectedInstance->group()); + name = QInputDialog::getText(this, tr("Group name"), tr("Enter a new group name."), + QLineEdit::Normal, name, &ok); + if (ok) + m_selectedInstance->setGroupPost(name); +} + +void MainWindow::on_actionViewInstanceFolder_triggered() +{ + QString str = MMC->settings()->get("InstanceDir").toString(); + openDirInDefaultProgram(str); +} + +void MainWindow::on_actionRefresh_triggered() +{ + MMC->instances()->loadList(); +} + +void MainWindow::on_actionViewCentralModsFolder_triggered() +{ + openDirInDefaultProgram(MMC->settings()->get("CentralModsDir").toString(), true); +} + +void MainWindow::on_actionConfig_Folder_triggered() +{ + if (m_selectedInstance) + { + QString str = m_selectedInstance->instanceConfigFolder(); + openDirInDefaultProgram(QDir(str).absolutePath()); + } +} + +void MainWindow::on_actionCheckUpdate_triggered() +{ +} + +void MainWindow::on_actionSettings_triggered() +{ + SettingsDialog dialog(this); + dialog.exec(); + //FIXME: quick HACK to make this work. improve, optimize. + proxymodel->invalidate(); + proxymodel->sort(0); +} + +void MainWindow::on_actionReportBug_triggered() +{ + openWebPage(QUrl("http://multimc.myjetbrains.com/youtrack/dashboard#newissue=yes")); +} + +void MainWindow::on_actionNews_triggered() +{ + openWebPage(QUrl("http://multimc.org/posts.html")); +} + +void MainWindow::on_actionAbout_triggered() +{ + AboutDialog dialog(this); + dialog.exec(); +} + +void MainWindow::on_mainToolBar_visibilityChanged(bool) +{ + // Don't allow hiding the main toolbar. + // This is the only way I could find to prevent it... :/ + ui->mainToolBar->setVisible(true); +} + +void MainWindow::on_actionDeleteInstance_triggered() +{ + if (m_selectedInstance) + { + auto response = CustomMessageBox::selectable( + this, tr("CAREFUL"), tr("This is permanent! Are you sure?\nAbout to delete: ") + + m_selectedInstance->name(), + QMessageBox::Question, QMessageBox::Yes | QMessageBox::No)->exec(); + if (response == QMessageBox::Yes) + { + m_selectedInstance->nuke(); + } + } +} + +void MainWindow::on_actionRenameInstance_triggered() +{ + if (m_selectedInstance) + { + bool ok = false; + QString name(m_selectedInstance->name()); + name = + QInputDialog::getText(this, tr("Instance name"), tr("Enter a new instance name."), + QLineEdit::Normal, name, &ok); + + if (name.length() > 0) + { + if (ok && name.length()) + { + m_selectedInstance->setName(name); + renameButton->setText(name); + } + } + } +} + +void MainWindow::on_actionViewSelectedInstFolder_triggered() +{ + if (m_selectedInstance) + { + QString str = m_selectedInstance->instanceRoot(); + openDirInDefaultProgram(QDir(str).absolutePath()); + } +} + +void MainWindow::on_actionEditInstMods_triggered() +{ + if (m_selectedInstance) + { + auto dialog = m_selectedInstance->createModEditDialog(this); + if (dialog) + dialog->exec(); + dialog->deleteLater(); + } +} + +void MainWindow::closeEvent(QCloseEvent *event) +{ + // Save the window state and geometry. + + MMC->settings()->set("MainWindowState", saveState().toBase64()); + MMC->settings()->set("MainWindowGeometry", saveGeometry().toBase64()); + + QMainWindow::closeEvent(event); + QApplication::exit(); +} +/* +void MainWindow::on_instanceView_customContextMenuRequested(const QPoint &pos) +{ + QMenu *instContextMenu = new QMenu("Instance", this); + + // Add the actions from the toolbar to the context menu. + instContextMenu->addActions(ui->instanceToolBar->actions()); + + instContextMenu->exec(view->mapToGlobal(pos)); +} +*/ +void MainWindow::instanceActivated(QModelIndex index) +{ + if (!index.isValid()) + return; + + BaseInstance *inst = + (BaseInstance *)index.data(InstanceList::InstancePointerRole).value(); + + NagUtils::checkJVMArgs(MMC->settings()->get("JvmArgs").toString(), this); + + bool autoLogin = MMC->settings()->get("AutoLogin").toBool(); + if (autoLogin) + doAutoLogin(); + else + doLogin(); +} + +void MainWindow::on_actionLaunchInstance_triggered() +{ + if (m_selectedInstance) + { + NagUtils::checkJVMArgs(MMC->settings()->get("JvmArgs").toString(), this); + doLogin(); + } +} + +void MainWindow::doAutoLogin() +{ + if (!m_selectedInstance) + return; + + Keyring *k = Keyring::instance(); + QStringList accounts = k->getStoredAccounts("minecraft"); + + if (!accounts.isEmpty()) + { + QString username = accounts[0]; + QString password = k->getPassword("minecraft", username); + + if (!password.isEmpty()) + { + QLOG_INFO() << "Automatically logging in with stored account: " << username; + m_activeInst = m_selectedInstance; + doLogin(username, password); + } + else + { + QLOG_ERROR() << "Auto login set for account, but no password was found: " + << username; + doLogin(tr("Auto login attempted, but no password is stored.")); + } + } + else + { + QLOG_ERROR() << "Auto login set but no accounts were stored."; + doLogin(tr("Auto login attempted, but no accounts are stored.")); + } +} + +void MainWindow::doLogin(QString username, QString password) +{ + UserInfo uInfo{username, password}; + + ProgressDialog *tDialog = new ProgressDialog(this); + LoginTask *loginTask = new LoginTask(uInfo, tDialog); + connect(loginTask, SIGNAL(succeeded()), SLOT(onLoginComplete()), Qt::QueuedConnection); + connect(loginTask, SIGNAL(failed(QString)), SLOT(doLogin(QString)), Qt::QueuedConnection); + + tDialog->exec(loginTask); +} + +void MainWindow::doLogin(const QString &errorMsg) +{ + if (!m_selectedInstance) + return; + + LoginDialog *loginDlg = new LoginDialog(this, errorMsg); + if (!m_selectedInstance->lastLaunch()) + loginDlg->forceOnline(); + + loginDlg->exec(); + if (loginDlg->result() == QDialog::Accepted) + { + if (loginDlg->isOnline()) + { + m_activeInst = m_selectedInstance; + doLogin(loginDlg->getUsername(), loginDlg->getPassword()); + } + else + { + QString user = loginDlg->getUsername(); + if (user.length() == 0) + user = QString("Player"); + m_activeLogin = {user, QString("Offline"), user, QString()}; + m_activeInst = m_selectedInstance; + launchInstance(m_activeInst, m_activeLogin); + } + } +} + +void MainWindow::onLoginComplete() +{ + if (!m_activeInst) + return; + LoginTask *task = (LoginTask *)QObject::sender(); + m_activeLogin = task->getResult(); + + BaseUpdate *updateTask = m_activeInst->doUpdate(); + if (!updateTask) + { + launchInstance(m_activeInst, m_activeLogin); + } + else + { + ProgressDialog tDialog(this); + connect(updateTask, SIGNAL(succeeded()), SLOT(onGameUpdateComplete())); + connect(updateTask, SIGNAL(failed(QString)), SLOT(onGameUpdateError(QString))); + tDialog.exec(updateTask); + delete updateTask; + } + + auto job = new NetJob("Player skin: " + m_activeLogin.player_name); + + auto meta = MMC->metacache()->resolveEntry("skins", m_activeLogin.player_name + ".png"); + auto action = CacheDownload::make( + QUrl("http://skins.minecraft.net/MinecraftSkins/" + m_activeLogin.player_name + ".png"), + meta); + job->addNetAction(action); + meta->stale = true; + + job->start(); + auto filename = MMC->metacache()->resolveEntry("skins", "skins.json")->getFullPath(); + QFile listFile(filename); + + // Add skin mapping + QByteArray data; + { + if (!listFile.open(QIODevice::ReadWrite)) + { + QLOG_ERROR() << "Failed to open/make skins list JSON"; + return; + } + + data = listFile.readAll(); + } + + QJsonParseError jsonError; + QJsonDocument jsonDoc = QJsonDocument::fromJson(data, &jsonError); + QJsonObject root = jsonDoc.object(); + QJsonObject mappings = root.value("mappings").toObject(); + QJsonArray usernames = mappings.value(m_activeLogin.username).toArray(); + + if (!usernames.contains(m_activeLogin.player_name)) + { + usernames.prepend(m_activeLogin.player_name); + mappings[m_activeLogin.username] = usernames; + root["mappings"] = mappings; + jsonDoc.setObject(root); + + // QJson hack - shouldn't have to clear the file every time a save happens + listFile.resize(0); + listFile.write(jsonDoc.toJson()); + } +} + +void MainWindow::onGameUpdateComplete() +{ + launchInstance(m_activeInst, m_activeLogin); +} + +void MainWindow::onGameUpdateError(QString error) +{ + CustomMessageBox::selectable(this, tr("Error updating instance"), error, + QMessageBox::Warning)->show(); +} + +void MainWindow::launchInstance(BaseInstance *instance, LoginResponse response) +{ + Q_ASSERT_X(instance != NULL, "launchInstance", "instance is NULL"); + + proc = instance->prepareForLaunch(response); + if (!proc) + return; + + // Prepare GUI: If it shall stay open disable the required parts + if (MMC->settings()->get("NoHide").toBool()) + { + ui->actionLaunchInstance->setEnabled(false); + } + else + { + this->hide(); + } + + console = new ConsoleWindow(proc); + + connect(proc, SIGNAL(log(QString, MessageLevel::Enum)), console, + SLOT(write(QString, MessageLevel::Enum))); + connect(proc, SIGNAL(ended(BaseInstance *)), this, SLOT(instanceEnded(BaseInstance *))); + + if (instance->settings().get("ShowConsole").toBool()) + { + console->show(); + } + + proc->setLogin(response.username, response.session_id); + proc->launch(); +} + +void MainWindow::taskStart() +{ + // Nothing to do here yet. +} + +void MainWindow::taskEnd() +{ + QObject *sender = QObject::sender(); + if (sender == m_versionLoadTask) + m_versionLoadTask = NULL; + + sender->deleteLater(); +} + +void MainWindow::startTask(Task *task) +{ + connect(task, SIGNAL(started()), SLOT(taskStart())); + connect(task, SIGNAL(succeeded()), SLOT(taskEnd())); + connect(task, SIGNAL(failed(QString)), SLOT(taskEnd())); + task->start(); +} + +// Create A Desktop Shortcut +void MainWindow::on_actionMakeDesktopShortcut_triggered() +{ + QString name("Test"); + name = QInputDialog::getText(this, tr("MultiMC Shortcut"), tr("Enter a Shortcut Name."), + QLineEdit::Normal, name); + + Util::createShortCut(Util::getDesktopDir(), QApplication::instance()->applicationFilePath(), + QStringList() << "-dl" << QDir::currentPath() << "test", name, + "application-x-octet-stream"); + + CustomMessageBox::selectable( + this, tr("Not useful"), + tr("A Dummy Shortcut was created. it will not do anything productive"), + QMessageBox::Warning)->show(); +} + +// BrowserDialog +void MainWindow::openWebPage(QUrl url) +{ + QDesktopServices::openUrl(url); +} + +void MainWindow::on_actionChangeInstMCVersion_triggered() +{ + if (view->selectionModel()->selectedIndexes().count() < 1) + return; + + VersionSelectDialog vselect(m_selectedInstance->versionList().get(), + tr("Change Minecraft version"), this); + vselect.setFilter(1, "OneSix"); + if (vselect.exec() && vselect.selectedVersion()) + { + if (m_selectedInstance->versionIsCustom()) + { + auto result = CustomMessageBox::selectable( + this, tr("Are you sure?"), + tr("This will remove any library/version customization you did previously. " + "This includes things like Forge install and similar."), + QMessageBox::Warning, QMessageBox::Ok, QMessageBox::Abort)->exec(); + + if (result != QMessageBox::Ok) + return; + } + m_selectedInstance->setIntendedVersionId(vselect.selectedVersion()->descriptor()); + } +} + +void MainWindow::on_actionChangeInstLWJGLVersion_triggered() +{ + if (!m_selectedInstance) + return; + + LWJGLSelectDialog lselect(this); + lselect.exec(); + if (lselect.result() == QDialog::Accepted) + { + LegacyInstance *linst = (LegacyInstance *)m_selectedInstance; + linst->setLWJGLVersion(lselect.selectedVersion()); + } +} + +void MainWindow::on_actionInstanceSettings_triggered() +{ + if (view->selectionModel()->selectedIndexes().count() < 1) + return; + + InstanceSettings settings(&m_selectedInstance->settings(), this); + settings.setWindowTitle(QString("Instance settings")); + settings.exec(); +} + +void MainWindow::instanceChanged(const QModelIndex ¤t, const QModelIndex &previous) +{ + if (current.isValid() && + nullptr != (m_selectedInstance = + (BaseInstance *)current.data(InstanceList::InstancePointerRole) + .value())) + { + ui->instanceToolBar->setEnabled(true); + QString iconKey = m_selectedInstance->iconKey(); + renameButton->setText(m_selectedInstance->name()); + ui->actionChangeInstLWJGLVersion->setEnabled( + m_selectedInstance->menuActionEnabled("actionChangeInstLWJGLVersion")); + ui->actionEditInstMods->setEnabled( + m_selectedInstance->menuActionEnabled("actionEditInstMods")); + ui->actionChangeInstMCVersion->setEnabled( + m_selectedInstance->menuActionEnabled("actionChangeInstMCVersion")); + m_statusLeft->setText(m_selectedInstance->getStatusbarDescription()); + auto ico = MMC->icons()->getIcon(iconKey); + ui->actionChangeInstIcon->setIcon(ico); + } + else + { + selectionBad(); + } +} + +void MainWindow::selectionBad() +{ + m_selectedInstance = nullptr; + QString iconKey = "infinity"; + statusBar()->clearMessage(); + ui->instanceToolBar->setEnabled(false); + renameButton->setText(tr("Rename Instance")); + auto ico = MMC->icons()->getIcon(iconKey); + ui->actionChangeInstIcon->setIcon(ico); +} + +void MainWindow::on_actionEditInstNotes_triggered() +{ + if (!m_selectedInstance) + return; + LegacyInstance *linst = (LegacyInstance *)m_selectedInstance; + + EditNotesDialog noteedit(linst->notes(), linst->name(), this); + noteedit.exec(); + if (noteedit.result() == QDialog::Accepted) + { + + linst->setNotes(noteedit.getText()); + } +} + +void MainWindow::instanceEnded(BaseInstance *instance) +{ + this->show(); + ui->actionLaunchInstance->setEnabled(m_selectedInstance); + + if (instance->settings().get("AutoCloseConsole").toBool()) + { + console->close(); + } +} + +void MainWindow::checkSetDefaultJava() +{ + bool askForJava = false; + { + QString currentHostName = QHostInfo::localHostName(); + QString oldHostName = MMC->settings()->get("LastHostname").toString(); + if (currentHostName != oldHostName) + { + MMC->settings()->set("LastHostname", currentHostName); + askForJava = true; + } + } + + { + QString currentJavaPath = MMC->settings()->get("JavaPath").toString(); + if (currentJavaPath.isEmpty()) + { + askForJava = true; + } + } + + if (askForJava) + { + QLOG_DEBUG() << "Java path needs resetting, showing Java selection dialog..."; + + JavaVersionPtr java; + + VersionSelectDialog vselect(MMC->javalist().get(), tr("Select a Java version"), this, + false); + vselect.setResizeOn(2); + vselect.exec(); + + if (vselect.selectedVersion()) + java = std::dynamic_pointer_cast(vselect.selectedVersion()); + else + { + CustomMessageBox::selectable( + this, tr("Invalid version selected"), + tr("You didn't select a valid Java version, so MultiMC will " + "select the default. " + "You can change this in the settings dialog."), + QMessageBox::Warning)->show(); + + JavaUtils ju; + java = ju.GetDefaultJava(); + } + if (java) + MMC->settings()->set("JavaPath", java->path); + else + MMC->settings()->set("JavaPath", QString("java")); + } +} + +void MainWindow::assetsIndexStarted() +{ + m_statusRight->setText(tr("Checking assets...")); +} + +void MainWindow::assetsFilesStarted() +{ + m_statusRight->setText(tr("Downloading assets...")); +} + +void MainWindow::assetsFilesProgress(int succeeded, int failed, int total) +{ + QString status = tr("Downloading assets: %1 / %2").arg(succeeded + failed).arg(total); + if (failed > 0) + status += tr(" (%1 failed)").arg(failed); + status += tr("..."); + m_statusRight->setText(status); +} + +void MainWindow::assetsFailed() +{ + m_statusRight->setText(tr("Failed to update assets.")); +} + +void MainWindow::assetsFinished() +{ + m_statusRight->setText(tr("Assets up to date.")); +} diff --git a/gui/MainWindow.h b/gui/MainWindow.h new file mode 100644 index 00000000..97aa0d9f --- /dev/null +++ b/gui/MainWindow.h @@ -0,0 +1,167 @@ +/* Copyright 2013 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 + +#include "logic/lists/InstanceList.h" +#include "logic/net/LoginTask.h" +#include "logic/BaseInstance.h" + +class QToolButton; +class LabeledToolButton; +class QLabel; +class InstanceProxyModel; +class KCategorizedView; +class KCategoryDrawer; +class MinecraftProcess; +class ConsoleWindow; +class OneSixAssets; + +namespace Ui +{ +class MainWindow; +} + +class MainWindow : public QMainWindow +{ + Q_OBJECT + +public: + explicit MainWindow(QWidget *parent = 0); + ~MainWindow(); + + void closeEvent(QCloseEvent *event); + + // Browser Dialog + void openWebPage(QUrl url); + + void checkSetDefaultJava(); + +private +slots: + void onCatToggled(bool); + + void on_actionAbout_triggered(); + + void on_actionAddInstance_triggered(); + + void on_actionCopyInstance_triggered(); + + void on_actionChangeInstGroup_triggered(); + + void on_actionChangeInstIcon_triggered(); + + void on_actionViewInstanceFolder_triggered(); + + void on_actionConfig_Folder_triggered(); + + void on_actionViewSelectedInstFolder_triggered(); + + void on_actionRefresh_triggered(); + + void on_actionViewCentralModsFolder_triggered(); + + void on_actionCheckUpdate_triggered(); + + void on_actionSettings_triggered(); + + void on_actionReportBug_triggered(); + + void on_actionNews_triggered(); + + void on_mainToolBar_visibilityChanged(bool); + + // void on_instanceView_customContextMenuRequested(const QPoint &pos); + + void on_actionLaunchInstance_triggered(); + + void on_actionDeleteInstance_triggered(); + + void on_actionRenameInstance_triggered(); + + void on_actionMakeDesktopShortcut_triggered(); + + void on_actionChangeInstMCVersion_triggered(); + + void on_actionEditInstMods_triggered(); + + void on_actionEditInstNotes_triggered(); + + void doLogin(const QString &errorMsg = ""); + void doLogin(QString username, QString password); + void doAutoLogin(); + + void onLoginComplete(); + + void onGameUpdateComplete(); + void onGameUpdateError(QString error); + + void taskStart(); + void taskEnd(); + + void on_actionChangeInstLWJGLVersion_triggered(); + + void instanceEnded(BaseInstance *instance); + + void on_actionInstanceSettings_triggered(); + + void assetsIndexStarted(); + void assetsFilesStarted(); + void assetsFilesProgress(int, int, int); + void assetsFailed(); + void assetsFinished(); + +public +slots: + void instanceActivated(QModelIndex); + + void instanceChanged(const QModelIndex ¤t, const QModelIndex &previous); + + void selectionBad(); + + void startTask(Task *task); + + void launchInstance(BaseInstance *inst, LoginResponse response); + +protected: + bool eventFilter(QObject *obj, QEvent *ev); + void setCatBackground(bool enabled); + +private: + Ui::MainWindow *ui; + KCategoryDrawer *drawer; + KCategorizedView *view; + InstanceProxyModel *proxymodel; + MinecraftProcess *proc; + ConsoleWindow *console; + OneSixAssets *assets_downloader; + LabeledToolButton *renameButton; + QToolButton *changeIconButton; + + BaseInstance *m_selectedInstance; + + // A pointer to the instance we are actively doing stuff with. + // This is set when the user launches an instance and is used to refer to that + // instance throughout the launching process. + BaseInstance *m_activeInst; + LoginResponse m_activeLogin; + + Task *m_versionLoadTask; + + QLabel *m_statusLeft; + QLabel *m_statusRight; +}; diff --git a/gui/MainWindow.ui b/gui/MainWindow.ui new file mode 100644 index 00000000..6f70fc98 --- /dev/null +++ b/gui/MainWindow.ui @@ -0,0 +1,474 @@ + + + MainWindow + + + + 0 + 0 + 688 + 650 + + + + MultiMC 5 + + + + :/icons/multimc/scalable/apps/multimc.svg:/icons/multimc/scalable/apps/multimc.svg + + + + + 0 + + + QLayout::SetDefaultConstraint + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + Main Toolbar + + + false + + + Qt::TopToolBarArea + + + Qt::ToolButtonIconOnly + + + false + + + TopToolBarArea + + + false + + + + + + + + + + + + + + + + + + + + + true + + + Instance Toolbar + + + Qt::LeftToolBarArea|Qt::RightToolBarArea + + + + 80 + 80 + + + + Qt::ToolButtonIconOnly + + + false + + + RightToolBarArea + + + false + + + + + + + + + + + + + + + + + + + + :/icons/toolbar/new:/icons/toolbar/new + + + Add Instance + + + Add a new instance. + + + Add a new instance. + + + + + + :/icons/toolbar/viewfolder:/icons/toolbar/viewfolder + + + View Instance Folder + + + Open the instance folder in a file browser. + + + Open the instance folder in a file browser. + + + + + + :/icons/toolbar/refresh:/icons/toolbar/refresh + + + Refresh + + + Reload the instance list. + + + Reload the instance list. + + + + + + :/icons/toolbar/centralmods:/icons/toolbar/centralmods + + + View Central Mods Folder + + + Open the central mods folder in a file browser. + + + Open the central mods folder in a file browser. + + + + + + :/icons/toolbar/checkupdate:/icons/toolbar/checkupdate + + + Check for Updates + + + Check for new updates for MultiMC + + + Check for new updates for MultiMC + + + + + + :/icons/toolbar/settings:/icons/toolbar/settings + + + Settings + + + Change settings. + + + Change settings. + + + QAction::PreferencesRole + + + + + + :/icons/toolbar/bug:/icons/toolbar/bug + + + Report a Bug + + + Open the bug tracker to report a bug with MultiMC. + + + Open the bug tracker to report a bug with MultiMC. + + + + + + :/icons/toolbar/news:/icons/toolbar/news + + + News + + + Open the MultiMC dev blog to read news about MultiMC. + + + Open the MultiMC dev blog to read news about MultiMC. + + + + + + :/icons/toolbar/about:/icons/toolbar/about + + + About MultiMC + + + View information about MultiMC. + + + About MultiMC + + + QAction::AboutRole + + + + + Play + + + Launch the selected instance. + + + Launch the selected instance. + + + + + Instance Name + + + Rename the selected instance. + + + Rename the selected instance. + + + + + Change Group + + + Change the selected instance's group. + + + Change the selected instance's group. + + + + + true + + + + :/icons/instances/infinity:/icons/instances/infinity + + + Change Icon + + + Change the selected instance's icon. + + + Change the selected instance's icon. + + + true + + + + + Edit Notes + + + Edit the notes for the selected instance. + + + Edit the notes for the selected instance. + + + + + true + + + Settings + + + Change settings for the selected instance. + + + Change settings for the selected instance. + + + + + false + + + Make Shortcut + + + Make a shortcut on the desktop for the selected instance. + + + Make a shortcut on the desktop for the selected instance. + + + + + false + + + Manage Saves + + + Manage saves for the selected instance. + + + Manage saves for the selected instance. + + + + + Edit Mods + + + Edit the mods for the selected instance. + + + Edit the mods for the selected instance. + + + + + Change Version + + + Change the selected instance's Minecraft version. + + + Change the selected instance's Minecraft version. + + + + + false + + + Change LWJGL + + + Change the version of LWJGL for the selected instance to use. + + + Change the version of LWJGL for the selected instance to use. + + + + + Instance Folder + + + Open the selected instance's root folder in a file browser. + + + Open the selected instance's root folder in a file browser. + + + + + Delete + + + Delete the selected instance. + + + Delete the selected instance. + + + + + Config Folder + + + Open the instance's config folder + + + + + true + + + + :/icons/toolbar/cat:/icons/toolbar/cat + + + Meow + + + <html><head/><body><p align="center"><span style=" font-weight:600; color:#ff0004;">Catnarok!</span></p><p align="center">Or just a cat with a ball of yarn?</p><p align="center"><span style=" font-style:italic;">WHO KNOWS?!</span></p><p align="center"><img src=":/icons/instances/tnt"/></p></body></html> + + + + + + :/icons/toolbar/copy:/icons/toolbar/copy + + + Copy Instance + + + Copy the selected instance. + + + Add a new instance. + + + + + + + + + diff --git a/gui/ModEditDialogCommon.cpp b/gui/ModEditDialogCommon.cpp deleted file mode 100644 index 873cd8ea..00000000 --- a/gui/ModEditDialogCommon.cpp +++ /dev/null @@ -1,41 +0,0 @@ -#include "ModEditDialogCommon.h" -#include "CustomMessageBox.h" -#include -#include -#include -#include -bool lastfirst(QModelIndexList &list, int &first, int &last) -{ - if (!list.size()) - return false; - first = last = list[0].row(); - for (auto item : list) - { - int row = item.row(); - if (row < first) - first = row; - if (row > last) - last = row; - } - return true; -} - -void showWebsiteForMod(QWidget *parentDlg, Mod &m) -{ - QString url = m.homeurl(); - if (url.size()) - { - // catch the cases where the protocol is missing - if(!url.startsWith("http")) - { - url = "http://" + url; - } - QDesktopServices::openUrl(url); - } - else - { - CustomMessageBox::selectable(parentDlg, parentDlg->tr("How sad!"), - parentDlg->tr("The mod author didn't provide a website link for this mod."), - QMessageBox::Warning); - } -} diff --git a/gui/ModEditDialogCommon.h b/gui/ModEditDialogCommon.h deleted file mode 100644 index bc8e223f..00000000 --- a/gui/ModEditDialogCommon.h +++ /dev/null @@ -1,7 +0,0 @@ -#pragma once -#include -#include - -bool lastfirst (QModelIndexList & list, int & first, int & last); - -void showWebsiteForMod(QWidget * parentDlg, Mod& m); \ No newline at end of file diff --git a/gui/ModListView.cpp b/gui/ModListView.cpp deleted file mode 100644 index 1d0e834c..00000000 --- a/gui/ModListView.cpp +++ /dev/null @@ -1,36 +0,0 @@ -#include "ModListView.h" -#include -#include -#include -#include -#include - -ModListView::ModListView ( QWidget* parent ) - :QTreeView ( parent ) -{ - setAllColumnsShowFocus ( true ); - setExpandsOnDoubleClick ( false ); - setRootIsDecorated ( false ); - setSortingEnabled ( false ); - setAlternatingRowColors ( true ); - setSelectionMode ( QAbstractItemView::ContiguousSelection ); - setHeaderHidden ( false ); - setSelectionBehavior(QAbstractItemView::SelectRows); - setVerticalScrollBarPolicy ( Qt::ScrollBarAlwaysOn ); - setHorizontalScrollBarPolicy ( Qt::ScrollBarAsNeeded ); - setDropIndicatorShown(true); - setDragEnabled(true); - setDragDropMode(QAbstractItemView::DropOnly); - viewport()->setAcceptDrops(true); -} - -void ModListView::setModel ( QAbstractItemModel* model ) -{ - QTreeView::setModel ( model ); - auto head = header(); - head->setStretchLastSection(false); - head->setSectionResizeMode(0, QHeaderView::Stretch); - for(int i = 1; i < head->count(); i++) - head->setSectionResizeMode(i, QHeaderView::ResizeToContents); - dropIndicatorPosition(); -} diff --git a/gui/ModListView.h b/gui/ModListView.h deleted file mode 100644 index 69a26755..00000000 --- a/gui/ModListView.h +++ /dev/null @@ -1,13 +0,0 @@ -#pragma once -#include - -class Mod; - -class ModListView: public QTreeView -{ - Q_OBJECT -public: - explicit ModListView ( QWidget* parent = 0 ); - virtual void setModel ( QAbstractItemModel* model ); - -}; diff --git a/gui/OneSixModEditDialog.cpp b/gui/OneSixModEditDialog.cpp deleted file mode 100644 index 42bcfeb0..00000000 --- a/gui/OneSixModEditDialog.cpp +++ /dev/null @@ -1,317 +0,0 @@ -/* Copyright 2013 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 "MultiMC.h" -#include "OneSixModEditDialog.h" -#include "ModEditDialogCommon.h" -#include "ui_OneSixModEditDialog.h" -#include "logic/ModList.h" -#include "logic/OneSixVersion.h" -#include "logic/EnabledItemFilter.h" -#include "logic/lists/ForgeVersionList.h" -#include "logic/ForgeInstaller.h" -#include "gui/versionselectdialog.h" -#include "gui/platform.h" -#include "gui/CustomMessageBox.h" -#include "ProgressDialog.h" - -#include -#include -#include -#include -#include -#include -#include - -OneSixModEditDialog::OneSixModEditDialog(OneSixInstance *inst, QWidget *parent) - : m_inst(inst), QDialog(parent), ui(new Ui::OneSixModEditDialog) -{ - MultiMCPlatform::fixWM_CLASS(this); - ui->setupUi(this); - // libraries! - - m_version = m_inst->getFullVersion(); - if (m_version) - { - main_model = new EnabledItemFilter(this); - main_model->setActive(true); - main_model->setSourceModel(m_version.get()); - ui->libraryTreeView->setModel(main_model); - ui->libraryTreeView->installEventFilter(this); - ui->mainClassEdit->setText(m_version->mainClass); - updateVersionControls(); - } - else - { - disableVersionControls(); - } - // Loader mods - { - ensureFolderPathExists(m_inst->loaderModsDir()); - m_mods = m_inst->loaderModList(); - ui->loaderModTreeView->setModel(m_mods.get()); - ui->loaderModTreeView->installEventFilter(this); - m_mods->startWatching(); - auto smodel = ui->loaderModTreeView->selectionModel(); - connect(smodel, SIGNAL(currentChanged(QModelIndex, QModelIndex)), - SLOT(loaderCurrent(QModelIndex,QModelIndex))); - } - // resource packs - { - ensureFolderPathExists(m_inst->resourcePacksDir()); - m_resourcepacks = m_inst->resourcePackList(); - ui->resPackTreeView->setModel(m_resourcepacks.get()); - ui->resPackTreeView->installEventFilter(this); - m_resourcepacks->startWatching(); - } -} - -OneSixModEditDialog::~OneSixModEditDialog() -{ - m_mods->stopWatching(); - m_resourcepacks->stopWatching(); - delete ui; -} - -void OneSixModEditDialog::updateVersionControls() -{ - bool customVersion = m_inst->versionIsCustom(); - ui->customizeBtn->setEnabled(!customVersion); - ui->revertBtn->setEnabled(customVersion); - ui->forgeBtn->setEnabled(true); -} - -void OneSixModEditDialog::disableVersionControls() -{ - ui->customizeBtn->setEnabled(false); - ui->revertBtn->setEnabled(false); - ui->forgeBtn->setEnabled(false); -} - -void OneSixModEditDialog::on_customizeBtn_clicked() -{ - if (m_inst->customizeVersion()) - { - m_version = m_inst->getFullVersion(); - main_model->setSourceModel(m_version.get()); - updateVersionControls(); - } -} - -void OneSixModEditDialog::on_revertBtn_clicked() -{ - auto response = CustomMessageBox::selectable(this, tr("Revert?"), - tr("Do you want to revert the " - "version of this instance to its original configuration?"), - QMessageBox::Question, QMessageBox::Yes | QMessageBox::No)->exec(); - if (response == QMessageBox::Yes) - { - if (m_inst->revertCustomVersion()) - { - m_version = m_inst->getFullVersion(); - main_model->setSourceModel(m_version.get()); - updateVersionControls(); - } - } -} - -void OneSixModEditDialog::on_forgeBtn_clicked() -{ - VersionSelectDialog vselect(MMC->forgelist().get(), tr("Select Forge version"), this); - vselect.setFilter(1, m_inst->currentVersionId()); - if (vselect.exec() && vselect.selectedVersion()) - { - if (m_inst->versionIsCustom()) - { - auto reply = QMessageBox::question( - this, tr("Revert?"), - tr("This will revert any " - "changes you did to the version up to this point. Is that " - "OK?"), - QMessageBox::Yes | QMessageBox::No); - if (reply == QMessageBox::Yes) - { - m_inst->revertCustomVersion(); - m_inst->customizeVersion(); - { - m_version = m_inst->getFullVersion(); - main_model->setSourceModel(m_version.get()); - updateVersionControls(); - } - } - else - return; - } - else - { - m_inst->customizeVersion(); - m_version = m_inst->getFullVersion(); - main_model->setSourceModel(m_version.get()); - updateVersionControls(); - } - ForgeVersionPtr forgeVersion = - std::dynamic_pointer_cast(vselect.selectedVersion()); - if (!forgeVersion) - return; - auto entry = MMC->metacache()->resolveEntry("minecraftforge", forgeVersion->filename); - if (entry->stale) - { - NetJob *fjob = new NetJob("Forge download"); - fjob->addNetAction(CacheDownload::make(forgeVersion->installer_url, entry)); - ProgressDialog dlg(this); - dlg.exec(fjob); - if (dlg.result() == QDialog::Accepted) - { - // install - QString forgePath = entry->getFullPath(); - ForgeInstaller forge(forgePath, forgeVersion->universal_url); - if (!forge.apply(m_version)) - { - // failure notice - } - } - else - { - // failed to download forge :/ - } - } - else - { - // install - QString forgePath = entry->getFullPath(); - ForgeInstaller forge(forgePath, forgeVersion->universal_url); - if (!forge.apply(m_version)) - { - // failure notice - } - } - } -} - -bool OneSixModEditDialog::loaderListFilter(QKeyEvent *keyEvent) -{ - switch (keyEvent->key()) - { - case Qt::Key_Delete: - on_rmModBtn_clicked(); - return true; - case Qt::Key_Plus: - on_addModBtn_clicked(); - return true; - default: - break; - } - return QDialog::eventFilter(ui->loaderModTreeView, keyEvent); -} - -bool OneSixModEditDialog::resourcePackListFilter(QKeyEvent *keyEvent) -{ - switch (keyEvent->key()) - { - case Qt::Key_Delete: - on_rmResPackBtn_clicked(); - return true; - case Qt::Key_Plus: - on_addResPackBtn_clicked(); - return true; - default: - break; - } - return QDialog::eventFilter(ui->resPackTreeView, keyEvent); -} - -bool OneSixModEditDialog::eventFilter(QObject *obj, QEvent *ev) -{ - if (ev->type() != QEvent::KeyPress) - { - return QDialog::eventFilter(obj, ev); - } - QKeyEvent *keyEvent = static_cast(ev); - if (obj == ui->loaderModTreeView) - return loaderListFilter(keyEvent); - if (obj == ui->resPackTreeView) - return resourcePackListFilter(keyEvent); - return QDialog::eventFilter(obj, ev); -} - -void OneSixModEditDialog::on_buttonBox_rejected() -{ - close(); -} - -void OneSixModEditDialog::on_addModBtn_clicked() -{ - QStringList fileNames = QFileDialog::getOpenFileNames( - this, QApplication::translate("LegacyModEditDialog", "Select Loader Mods")); - for (auto filename : fileNames) - { - m_mods->stopWatching(); - m_mods->installMod(QFileInfo(filename)); - m_mods->startWatching(); - } -} -void OneSixModEditDialog::on_rmModBtn_clicked() -{ - int first, last; - auto list = ui->loaderModTreeView->selectionModel()->selectedRows(); - - if (!lastfirst(list, first, last)) - return; - m_mods->stopWatching(); - m_mods->deleteMods(first, last); - m_mods->startWatching(); -} -void OneSixModEditDialog::on_viewModBtn_clicked() -{ - openDirInDefaultProgram(m_inst->loaderModsDir(), true); -} - -void OneSixModEditDialog::on_addResPackBtn_clicked() -{ - QStringList fileNames = QFileDialog::getOpenFileNames( - this, QApplication::translate("LegacyModEditDialog", "Select Resource Packs")); - for (auto filename : fileNames) - { - m_resourcepacks->stopWatching(); - m_resourcepacks->installMod(QFileInfo(filename)); - m_resourcepacks->startWatching(); - } -} -void OneSixModEditDialog::on_rmResPackBtn_clicked() -{ - int first, last; - auto list = ui->resPackTreeView->selectionModel()->selectedRows(); - - if (!lastfirst(list, first, last)) - return; - m_resourcepacks->stopWatching(); - m_resourcepacks->deleteMods(first, last); - m_resourcepacks->startWatching(); -} -void OneSixModEditDialog::on_viewResPackBtn_clicked() -{ - openDirInDefaultProgram(m_inst->resourcePacksDir(), true); -} - -void OneSixModEditDialog::loaderCurrent(QModelIndex current, QModelIndex previous) -{ - if(!current.isValid()) - { - ui->frame->clear(); - return; - } - int row = current.row(); - Mod &m = m_mods->operator[](row); - ui->frame->updateWithMod(m); -} diff --git a/gui/OneSixModEditDialog.h b/gui/OneSixModEditDialog.h deleted file mode 100644 index 5376e526..00000000 --- a/gui/OneSixModEditDialog.h +++ /dev/null @@ -1,67 +0,0 @@ -/* Copyright 2013 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 - -#include - -class EnabledItemFilter; -namespace Ui -{ -class OneSixModEditDialog; -} - -class OneSixModEditDialog : public QDialog -{ - Q_OBJECT - -public: - explicit OneSixModEditDialog(OneSixInstance *inst, QWidget *parent = 0); - virtual ~OneSixModEditDialog(); - -private -slots: - void on_addModBtn_clicked(); - void on_rmModBtn_clicked(); - void on_viewModBtn_clicked(); - - void on_addResPackBtn_clicked(); - void on_rmResPackBtn_clicked(); - void on_viewResPackBtn_clicked(); - // Questionable: SettingsDialog doesn't need this for some reason? - void on_buttonBox_rejected(); - void on_forgeBtn_clicked(); - void on_customizeBtn_clicked(); - void on_revertBtn_clicked(); - void updateVersionControls(); - void disableVersionControls(); - -protected: - bool eventFilter(QObject *obj, QEvent *ev); - bool loaderListFilter(QKeyEvent *ev); - bool resourcePackListFilter(QKeyEvent *ev); - -private: - Ui::OneSixModEditDialog *ui; - std::shared_ptr m_version; - std::shared_ptr m_mods; - std::shared_ptr m_resourcepacks; - EnabledItemFilter *main_model; - OneSixInstance *m_inst; -public -slots: - void loaderCurrent(QModelIndex current, QModelIndex previous); -}; diff --git a/gui/OneSixModEditDialog.ui b/gui/OneSixModEditDialog.ui deleted file mode 100644 index 6d70200a..00000000 --- a/gui/OneSixModEditDialog.ui +++ /dev/null @@ -1,319 +0,0 @@ - - - OneSixModEditDialog - - - - 0 - 0 - 555 - 463 - - - - Dialog - - - - - - true - - - - 0 - 0 - - - - 1 - - - - Version - - - - - - - - Qt::ScrollBarAlwaysOn - - - Qt::ScrollBarAlwaysOff - - - - - - - - - Main Class: - - - - - - - false - - - - - - - - - - - - - Replace any current custom version with Minecraft Forge - - - Install Forge - - - - - - - Create an customized copy of the base version - - - Customize - - - - - - - false - - - Revert to original base version - - - Revert - - - - - - - QFrame::Sunken - - - Qt::Horizontal - - - - - - - false - - - Add new libraries - - - &Add - - - - - - - false - - - Remove selected libraries - - - &Remove - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - - - - Loader Mods - - - - - - - - - - - 0 - 0 - - - - true - - - QAbstractItemView::DropOnly - - - - - - - - - - - &Add - - - - - - - &Remove - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - &View Folder - - - - - - - - - - - - 0 - 0 - - - - - - - - - Resource Packs - - - - - - true - - - QAbstractItemView::DropOnly - - - - - - - - - &Add - - - - - - - &Remove - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - &View Folder - - - - - - - - - - - - - false - - - QDialogButtonBox::Close - - - - - - - - ModListView - QTreeView -
gui/ModListView.h
-
- - MCModInfoFrame - QFrame -
gui/MCModInfoFrame.h
- 1 -
-
- - -
diff --git a/gui/Platform.h b/gui/Platform.h new file mode 100644 index 00000000..5cde9505 --- /dev/null +++ b/gui/Platform.h @@ -0,0 +1,32 @@ +/* Copyright 2013 MultiMC Contributors + * + * Authors: Orochimarufan + * + * 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 + +/** + * @file Platform.h + * This file contains platform-specific functions, tweaks and fixes. + */ + +#include + +class MultiMCPlatform +{ +public: + // X11 WM_CLASS + static void fixWM_CLASS(QWidget *widget); +}; diff --git a/gui/Platform_Other.cpp b/gui/Platform_Other.cpp new file mode 100644 index 00000000..e02bd921 --- /dev/null +++ b/gui/Platform_Other.cpp @@ -0,0 +1,27 @@ +/* Copyright 2013 MultiMC Contributors + * + * Authors: Orochimarufan + * + * 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 +/** + * Stub for non-X11 platforms + * @brief MultiMCPlatform::fixWM_CLASS + * @param widget + */ +void MultiMCPlatform::fixWM_CLASS(QWidget *widget) +{ + Q_UNUSED(widget); +} diff --git a/gui/Platform_X11.cpp b/gui/Platform_X11.cpp new file mode 100644 index 00000000..bcd26f53 --- /dev/null +++ b/gui/Platform_X11.cpp @@ -0,0 +1,62 @@ +/* Copyright 2013 MultiMC Contributors + * + * Authors: Orochimarufan + * + * 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 +#include +#include + +static QByteArray WM_CLASS = "MultiMC5\0MultiMC5"; + +template +static inline unsigned int XcbCallVoid(xcb_void_cookie_t (*func)(xcb_connection_t *, ArgTypes...), ArgTypes2... args...) +{ + return func(QX11Info::connection(), args...).sequence; +} + +static void getAtoms(size_t n, xcb_atom_t *atoms, const char *const names[], bool create) +{ + xcb_connection_t *conn = QX11Info::connection(); + xcb_intern_atom_cookie_t *cookies = (xcb_intern_atom_cookie_t *)malloc(sizeof(xcb_intern_atom_cookie_t) * 2); + for (size_t i = 0; i < n; ++i) + cookies[i] = xcb_intern_atom(conn, create, strlen(names[i]), names[i]); + memset(atoms, 0, sizeof(xcb_atom_t) * n); + for (size_t i = 0; i < n; ++i) + { + xcb_intern_atom_reply_t *r = xcb_intern_atom_reply(conn, cookies[i], 0); + if (r) + { + atoms[i] = r->atom; + free(r); + } + } + free(cookies); +} + +static inline xcb_atom_t getAtom(const char *name, bool create=false) +{ + xcb_atom_t atom; + getAtoms(1, &atom, &name, create); + return atom; +} + +void MultiMCPlatform::fixWM_CLASS(QWidget *widget) +{ + static const xcb_atom_t atom = getAtom("WM_CLASS"); + XcbCallVoid(xcb_change_property, XCB_PROP_MODE_REPLACE, + widget->winId(), atom, XCB_ATOM_STRING, 8, WM_CLASS.count(), + WM_CLASS.constData()); +} diff --git a/gui/ProgressDialog.cpp b/gui/ProgressDialog.cpp deleted file mode 100644 index 2e5251a0..00000000 --- a/gui/ProgressDialog.cpp +++ /dev/null @@ -1,110 +0,0 @@ -/* Copyright 2013 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 "ProgressDialog.h" -#include "ui_ProgressDialog.h" - -#include - -#include "logic/tasks/Task.h" -#include "gui/platform.h" - -ProgressDialog::ProgressDialog(QWidget *parent) : - QDialog(parent), - ui(new Ui::ProgressDialog) -{ - MultiMCPlatform::fixWM_CLASS(this); - ui->setupUi(this); - updateSize(); - - changeProgress(0,100); -} - -ProgressDialog::~ProgressDialog() -{ - delete ui; -} - -void ProgressDialog::updateSize() -{ - resize(QSize(480, minimumSizeHint().height())); -} - -int ProgressDialog::exec(ProgressProvider *task) -{ - this->task = task; - - // Connect signals. - connect(task, SIGNAL(started()), SLOT(onTaskStarted())); - connect(task, SIGNAL(failed(QString)), SLOT(onTaskFailed(QString))); - connect(task, SIGNAL(succeeded()), SLOT(onTaskSucceeded())); - connect(task, SIGNAL(status(QString)), SLOT(changeStatus(const QString&))); - connect(task, SIGNAL(progress(qint64,qint64)), SLOT(changeProgress(qint64,qint64))); - - // this makes sure that the task is started after the dialog is created - QMetaObject::invokeMethod(task, "start", Qt::QueuedConnection); - return QDialog::exec(); -} - -ProgressProvider* ProgressDialog::getTask() -{ - return task; -} - -void ProgressDialog::onTaskStarted() -{ - -} - -void ProgressDialog::onTaskFailed(QString failure) -{ - reject(); -} - -void ProgressDialog::onTaskSucceeded() -{ - accept(); -} - -void ProgressDialog::changeStatus(const QString &status) -{ - ui->statusLabel->setText(status); - updateSize(); -} - -void ProgressDialog::changeProgress(qint64 current, qint64 total) -{ - ui->taskProgressBar->setMaximum(total); - ui->taskProgressBar->setValue(current); -} - -void ProgressDialog::keyPressEvent(QKeyEvent* e) -{ - if (e->key() == Qt::Key_Escape) - return; - QDialog::keyPressEvent(e); -} - -void ProgressDialog::closeEvent(QCloseEvent* e) -{ - if (task && task->isRunning()) - { - e->ignore(); - } - else - { - QDialog::closeEvent(e); - } -} diff --git a/gui/ProgressDialog.h b/gui/ProgressDialog.h deleted file mode 100644 index ac6bb412..00000000 --- a/gui/ProgressDialog.h +++ /dev/null @@ -1,62 +0,0 @@ -/* Copyright 2013 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. - */ - -#ifndef TASKDIALOG_H -#define TASKDIALOG_H - -#include - -class ProgressProvider; - -namespace Ui { -class ProgressDialog; -} - -class ProgressDialog : public QDialog -{ - Q_OBJECT - -public: - explicit ProgressDialog(QWidget *parent = 0); - ~ProgressDialog(); - - void updateSize(); - - int exec(ProgressProvider* task); - - ProgressProvider* getTask(); - -public slots: - void onTaskStarted(); - void onTaskFailed(QString failure); - void onTaskSucceeded(); - - void changeStatus(const QString& status); - void changeProgress(qint64 current, qint64 total); - -signals: - - -protected: - virtual void keyPressEvent(QKeyEvent* e); - virtual void closeEvent(QCloseEvent* e); - -private: - Ui::ProgressDialog *ui; - - ProgressProvider* task; -}; - -#endif // TASKDIALOG_H diff --git a/gui/ProgressDialog.ui b/gui/ProgressDialog.ui deleted file mode 100644 index a56d2a92..00000000 --- a/gui/ProgressDialog.ui +++ /dev/null @@ -1,53 +0,0 @@ - - - ProgressDialog - - - - 0 - 0 - 400 - 68 - - - - - 400 - 0 - - - - - 600 - 16777215 - - - - Please wait... - - - - - - Task Status... - - - true - - - - - - - 24 - - - false - - - - - - - - diff --git a/gui/aboutdialog.cpp b/gui/aboutdialog.cpp deleted file mode 100644 index 7105446c..00000000 --- a/gui/aboutdialog.cpp +++ /dev/null @@ -1,24 +0,0 @@ -#include "aboutdialog.h" -#include "ui_aboutdialog.h" -#include -#include -#include "gui/platform.h" - -AboutDialog::AboutDialog(QWidget *parent) : - QDialog(parent), - ui(new Ui::AboutDialog) -{ - MultiMCPlatform::fixWM_CLASS(this); - ui->setupUi(this); - - ui->icon->setPixmap(QIcon(":/icons/multimc/scalable/apps/multimc.svg").pixmap(64)); - ui->title->setText("MultiMC " + MMC->version().toString()); - connect(ui->closeButton, SIGNAL(clicked()), SLOT(close())); - - MMC->connect(ui->aboutQt, SIGNAL(clicked()), SLOT(aboutQt())); -} - -AboutDialog::~AboutDialog() -{ - delete ui; -} diff --git a/gui/aboutdialog.h b/gui/aboutdialog.h deleted file mode 100644 index d462de28..00000000 --- a/gui/aboutdialog.h +++ /dev/null @@ -1,22 +0,0 @@ -#ifndef ABOUTDIALOG_H -#define ABOUTDIALOG_H - -#include - -namespace Ui { -class AboutDialog; -} - -class AboutDialog : public QDialog -{ - Q_OBJECT - -public: - explicit AboutDialog(QWidget *parent = 0); - ~AboutDialog(); - -private: - Ui::AboutDialog *ui; -}; - -#endif // ABOUTDIALOG_H diff --git a/gui/aboutdialog.ui b/gui/aboutdialog.ui deleted file mode 100644 index c075f895..00000000 --- a/gui/aboutdialog.ui +++ /dev/null @@ -1,315 +0,0 @@ - - - AboutDialog - - - - 0 - 0 - 450 - 429 - - - - - 450 - 400 - - - - Dialog - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - 0 - 0 - - - - - 64 - 64 - - - - - 64 - 64 - - - - - - - :/icons/multimc/scalable/apps/multimc.svg - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - - 15 - - - - MultiMC - - - Qt::AlignCenter - - - - - - - - - 0 - 0 - 432 - 197 - - - - About - - - - - - <html><head/><body><p>MultiMC is a custom launcher that makes managing Minecraft easier by allowing you to have multiple instances of Minecraft at once.</p></body></html> - - - Qt::AlignCenter - - - true - - - - - - - - 8 - true - - - - © 2013 MultiMC Contributors - - - Qt::AlignCenter - - - - - - - - 10 - - - - <html><head/><body><p><a href="http://github.com/Forkk/MultiMC5"><span style=" text-decoration: underline; color:#0000ff;">http://github.com/MultiMC/MultiMC5</span></a></p></body></html> - - - Qt::AlignCenter - - - - - - - - - 0 - 0 - 432 - 197 - - - - Credits - - - - - - true - - - <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> -<html><head><meta name="qrichtext" content="1" /><style type="text/css"> -p, li { white-space: pre-wrap; } -</style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:11pt;">Andrew Okin &lt;</span><a href="mailto:forkk@forkk.net"><span style=" font-family:'Ubuntu'; font-size:11pt; text-decoration: underline; color:#0000ff;">forkk@forkk.net</span></a><span style=" font-family:'Ubuntu'; font-size:11pt;">&gt;</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:11pt;">Petr Mrázek &lt;</span><a href="mailto:peterix@gmail.com"><span style=" font-family:'Ubuntu'; font-size:11pt; text-decoration: underline; color:#0000ff;">peterix@gmail.com</span></a><span style=" font-family:'Ubuntu'; font-size:11pt;">&gt;</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:11pt;">Orochimarufan &lt;</span><a href="mailto:orochimarufan.x3@gmail.com"><span style=" font-family:'Ubuntu'; font-size:11pt; text-decoration: underline; color:#0000ff;">orochimarufan.x3@gmail.com</span></a><span style=" font-family:'Ubuntu'; font-size:11pt;">&gt;</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:11pt;">TakSuyu &lt;</span><a href="mailto:taksuyu@gmail.com"><span style=" font-family:'Ubuntu'; font-size:11pt; text-decoration: underline; color:#0000ff;">taksuyu@gmail.com</span></a><span style=" font-family:'Ubuntu'; font-size:11pt;">&gt;</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:11pt;">Sky (Drayshak) &lt;</span><span style=" font-family:'Ubuntu'; font-size:11pt; text-decoration: underline; color:#0000ff;">multimc@bunnies.cc</span><span style=" font-family:'Ubuntu'; font-size:11pt;">&gt;</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:11pt;">Kilobyte &lt;</span><a href="mailto:stiepen22@gmx.de"><span style=" font-family:'Ubuntu'; font-size:11pt; text-decoration: underline; color:#0000ff;">stiepen22@gmx.de</span></a><span style=" font-family:'Ubuntu'; font-size:11pt;">&gt;</span></p></body></html> - - - - - - - No Language file loaded. - - - true - - - - - - - - - 0 - 0 - 432 - 197 - - - - License - - - - - - - 0 - 0 - - - - true - - - <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> -<html><head><meta name="qrichtext" content="1" /><style type="text/css"> -p, li { white-space: pre-wrap; } -</style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;">Copyright 2012 MultiMC Contributors</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;">Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;">you may not use this file except in compliance with the License.</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;">You may obtain a copy of the License at</span></p> -<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Ubuntu'; font-size:10pt;"><br /></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;"> http://www.apache.org/licenses/LICENSE-2.0</span></p> -<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Ubuntu'; font-size:10pt;"><br /></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;">Unless required by applicable law or agreed to in writing, software</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;">distributed under the License is distributed on an &quot;AS IS&quot; BASIS,</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;">WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;">See the License for the specific language governing permissions and</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;">limitations under the License.</span></p> -<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Ubuntu'; font-size:10pt;"><br /></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;">MultiMC uses QSLog, </span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;">Copyright (c) 2010, Razvan Petru</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;">All rights reserved.</span></p> -<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Ubuntu'; font-size:10pt;"><br /></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;">Redistribution and use in source and binary forms, with or without modification,</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;">are permitted provided that the following conditions are met:</span></p> -<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Ubuntu'; font-size:10pt;"><br /></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;">* Redistributions of source code must retain the above copyright notice, this</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;"> list of conditions and the following disclaimer.</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;">* Redistributions in binary form must reproduce the above copyright notice, this</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;"> list of conditions and the following disclaimer in the documentation and/or other</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;"> materials provided with the distribution.</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;">* The name of the contributors may not be used to endorse or promote products</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;"> derived from this software without specific prior written permission.</span></p> -<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Ubuntu'; font-size:10pt;"><br /></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;">THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS &quot;AS IS&quot; AND</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;">ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;">WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;">IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;">INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;">BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;">DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;">LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;">OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;">OF THE POSSIBILITY OF SUCH DAMAGE.</span></p></body></html> - - - - - - - - - - - - - false - - - About Qt - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - Close - - - - - - - - - - - - diff --git a/gui/consolewindow.cpp b/gui/consolewindow.cpp deleted file mode 100644 index 49e12339..00000000 --- a/gui/consolewindow.cpp +++ /dev/null @@ -1,120 +0,0 @@ -#include "consolewindow.h" -#include "ui_consolewindow.h" - -#include -#include - -#include -#include - -ConsoleWindow::ConsoleWindow(MinecraftProcess *mcproc, QWidget *parent) : - QDialog(parent), - ui(new Ui::ConsoleWindow), - m_mayclose(true), - proc(mcproc) -{ - MultiMCPlatform::fixWM_CLASS(this); - ui->setupUi(this); - this->setWindowFlags(Qt::Window); - connect(mcproc, SIGNAL(ended(BaseInstance*)), this, SLOT(onEnded(BaseInstance*))); -} - -ConsoleWindow::~ConsoleWindow() -{ - delete ui; -} - -void ConsoleWindow::writeColor(QString text, const char *color) -{ - // append a paragraph - if (color != nullptr) - ui->text->appendHtml(QString("%2").arg(color).arg(text)); - else - ui->text->appendPlainText(text); - // scroll down - QScrollBar *bar = ui->text->verticalScrollBar(); - bar->setValue(bar->maximum()); -} - -void ConsoleWindow::write(QString data, MessageLevel::Enum mode) -{ - if (data.endsWith('\n')) - data = data.left(data.length()-1); - QStringList paragraphs = data.split('\n'); - for(QString ¶graph : paragraphs) - { - paragraph = paragraph.trimmed(); - } - - QListIterator iter(paragraphs); - if (mode == MessageLevel::MultiMC) - while(iter.hasNext()) - writeColor(iter.next(), "blue"); - else if (mode == MessageLevel::Error) - while(iter.hasNext()) - writeColor(iter.next(), "red"); - else if (mode == MessageLevel::Warning) - while(iter.hasNext()) - writeColor(iter.next(), "orange"); - else if (mode == MessageLevel::Fatal) - while(iter.hasNext()) - writeColor(iter.next(), "pink"); - else if (mode == MessageLevel::Debug) - while(iter.hasNext()) - writeColor(iter.next(), "green"); - // TODO: implement other MessageLevels - else - while(iter.hasNext()) - writeColor(iter.next()); -} - -void ConsoleWindow::clear() -{ - ui->text->clear(); -} - -void ConsoleWindow::on_closeButton_clicked() -{ - close(); -} - -void ConsoleWindow::setMayClose(bool mayclose) -{ - m_mayclose = mayclose; - if (mayclose) - ui->closeButton->setEnabled(true); - else - ui->closeButton->setEnabled(false); -} - -void ConsoleWindow::closeEvent(QCloseEvent * event) -{ - if(!m_mayclose) - event->ignore(); - else - QDialog::closeEvent(event); -} - -void ConsoleWindow::on_btnKillMinecraft_clicked() -{ - ui->btnKillMinecraft->setEnabled(false); - auto response = CustomMessageBox::selectable(this, tr("Kill Minecraft?"), - tr("This can cause the instance to get corrupted and should only be used if Minecraft is frozen for some reason"), - QMessageBox::Question, QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes)->exec(); - if (response == QMessageBox::Yes) - proc->killMinecraft(); - else - ui->btnKillMinecraft->setEnabled(true); -} - -void ConsoleWindow::onEnded(BaseInstance *instance) -{ - ui->btnKillMinecraft->setEnabled(false); - - // TODO: Might need an option to forcefully close, even on an error - if(instance->settings().get("AutoCloseConsole").toBool()) - { - // TODO: Check why this doesn't work - if (!proc->exitCode()) this->close(); - } -} diff --git a/gui/consolewindow.h b/gui/consolewindow.h deleted file mode 100644 index e8790c92..00000000 --- a/gui/consolewindow.h +++ /dev/null @@ -1,63 +0,0 @@ -#ifndef CONSOLEWINDOW_H -#define CONSOLEWINDOW_H - -#include -#include "logic/MinecraftProcess.h" - -namespace Ui { -class ConsoleWindow; -} - -class ConsoleWindow : public QDialog -{ - Q_OBJECT - -public: - explicit ConsoleWindow(MinecraftProcess *proc, QWidget *parent = 0); - ~ConsoleWindow(); - - /** - * @brief specify if the window is allowed to close - * @param mayclose - * used to keep it alive while MC runs - */ - void setMayClose(bool mayclose); - -public slots: - /** - * @brief write a string - * @param data the string - * @param mode the WriteMode - * lines have to be put through this as a whole! - */ - void write(QString data, MessageLevel::Enum level=MessageLevel::MultiMC); - - /** - * @brief write a colored paragraph - * @param data the string - * @param color the css color name - * this will only insert a single paragraph. - * \n are ignored. a real \n is always appended. - */ - void writeColor(QString data, const char *color=nullptr); - - /** - * @brief clear the text widget - */ - void clear(); - -private slots: - void on_closeButton_clicked(); - void on_btnKillMinecraft_clicked(); - void onEnded(BaseInstance *instance); - -protected: - void closeEvent(QCloseEvent *); - -private: - Ui::ConsoleWindow *ui; - MinecraftProcess *proc; - bool m_mayclose; -}; - -#endif // CONSOLEWINDOW_H diff --git a/gui/consolewindow.ui b/gui/consolewindow.ui deleted file mode 100644 index 8dc80015..00000000 --- a/gui/consolewindow.ui +++ /dev/null @@ -1,85 +0,0 @@ - - - ConsoleWindow - - - - 0 - 0 - 600 - 400 - - - - MultiMC Console - - - - 0 - - - 0 - - - 0 - - - - - - 10 - - - - false - - - true - - - - - - Qt::LinksAccessibleByKeyboard|Qt::LinksAccessibleByMouse|Qt::TextBrowserInteraction|Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse - - - false - - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - Kill Minecraft - - - - - - - Close - - - - - - - - - - diff --git a/gui/dialogs/AboutDialog.cpp b/gui/dialogs/AboutDialog.cpp new file mode 100644 index 00000000..58d61dd0 --- /dev/null +++ b/gui/dialogs/AboutDialog.cpp @@ -0,0 +1,37 @@ +/* Copyright 2013 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 "AboutDialog.h" +#include "ui_AboutDialog.h" +#include +#include "MultiMC.h" +#include "gui/Platform.h" + +AboutDialog::AboutDialog(QWidget *parent) : QDialog(parent), ui(new Ui::AboutDialog) +{ + MultiMCPlatform::fixWM_CLASS(this); + ui->setupUi(this); + + ui->icon->setPixmap(QIcon(":/icons/multimc/scalable/apps/multimc.svg").pixmap(64)); + ui->title->setText("MultiMC " + MMC->version().toString()); + connect(ui->closeButton, SIGNAL(clicked()), SLOT(close())); + + MMC->connect(ui->aboutQt, SIGNAL(clicked()), SLOT(aboutQt())); +} + +AboutDialog::~AboutDialog() +{ + delete ui; +} diff --git a/gui/dialogs/AboutDialog.h b/gui/dialogs/AboutDialog.h new file mode 100644 index 00000000..9d747bac --- /dev/null +++ b/gui/dialogs/AboutDialog.h @@ -0,0 +1,35 @@ +/* Copyright 2013 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 + +namespace Ui +{ +class AboutDialog; +} + +class AboutDialog : public QDialog +{ + Q_OBJECT + +public: + explicit AboutDialog(QWidget *parent = 0); + ~AboutDialog(); + +private: + Ui::AboutDialog *ui; +}; diff --git a/gui/dialogs/AboutDialog.ui b/gui/dialogs/AboutDialog.ui new file mode 100644 index 00000000..0a189d9c --- /dev/null +++ b/gui/dialogs/AboutDialog.ui @@ -0,0 +1,316 @@ + + + AboutDialog + + + + 0 + 0 + 450 + 429 + + + + + 450 + 400 + + + + Dialog + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 0 + 0 + + + + + 64 + 64 + + + + + 64 + 64 + + + + + + + :/icons/multimc/scalable/apps/multimc.svg + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + 15 + + + + MultiMC + + + Qt::AlignCenter + + + + + + + + + 0 + 0 + 432 + 179 + + + + About + + + + + + <html><head/><body><p>MultiMC is a custom launcher that makes managing Minecraft easier by allowing you to have multiple instances of Minecraft at once.</p></body></html> + + + Qt::AlignCenter + + + true + + + + + + + + 8 + true + + + + © 2013 MultiMC Contributors + + + Qt::AlignCenter + + + + + + + + 10 + + + + <html><head/><body><p><a href="http://github.com/Forkk/MultiMC5"><span style=" text-decoration: underline; color:#0000ff;">http://github.com/MultiMC/MultiMC5</span></a></p></body></html> + + + Qt::AlignCenter + + + + + + + + + 0 + 0 + 98 + 120 + + + + Credits + + + + + + true + + + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Bitstream Vera Sans'; font-size:11pt; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu';">Andrew Okin &lt;</span><a href="mailto:forkk@forkk.net"><span style=" font-family:'Ubuntu'; text-decoration: underline; color:#0000ff;">forkk@forkk.net</span></a><span style=" font-family:'Ubuntu';">&gt;</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu';">Petr Mrázek &lt;</span><a href="mailto:peterix@gmail.com"><span style=" font-family:'Ubuntu'; text-decoration: underline; color:#0000ff;">peterix@gmail.com</span></a><span style=" font-family:'Ubuntu';">&gt;</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu';">Orochimarufan &lt;</span><a href="mailto:orochimarufan.x3@gmail.com"><span style=" font-family:'Ubuntu'; text-decoration: underline; color:#0000ff;">orochimarufan.x3@gmail.com</span></a><span style=" font-family:'Ubuntu';">&gt;</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu';">TakSuyu &lt;</span><a href="mailto:taksuyu@gmail.com"><span style=" font-family:'Ubuntu'; text-decoration: underline; color:#0000ff;">taksuyu@gmail.com</span></a><span style=" font-family:'Ubuntu';">&gt;</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu';">Sky (Drayshak) &lt;</span><span style=" font-family:'Ubuntu'; text-decoration: underline; color:#0000ff;">multimc@bunnies.cc</span><span style=" font-family:'Ubuntu';">&gt;</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu';">Kilobyte &lt;</span><a href="mailto:stiepen22@gmx.de"><span style=" font-family:'Ubuntu'; text-decoration: underline; color:#0000ff;">stiepen22@gmx.de</span></a><span style=" font-family:'Ubuntu';">&gt;</span></p></body></html> + + + + + + + No Language file loaded. + + + true + + + + + + + + + 0 + 0 + 98 + 88 + + + + License + + + + + + + 0 + 0 + + + + true + + + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Bitstream Vera Sans'; font-size:11pt; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;">Copyright 2012 MultiMC Contributors</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;">Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;">you may not use this file except in compliance with the License.</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;">You may obtain a copy of the License at</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Ubuntu'; font-size:10pt;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;"> http://www.apache.org/licenses/LICENSE-2.0</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Ubuntu'; font-size:10pt;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;">Unless required by applicable law or agreed to in writing, software</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;">distributed under the License is distributed on an &quot;AS IS&quot; BASIS,</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;">WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;">See the License for the specific language governing permissions and</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;">limitations under the License.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Ubuntu'; font-size:10pt;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;">MultiMC uses QSLog, </span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;">Copyright (c) 2010, Razvan Petru</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;">All rights reserved.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Ubuntu'; font-size:10pt;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;">Redistribution and use in source and binary forms, with or without modification,</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;">are permitted provided that the following conditions are met:</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Ubuntu'; font-size:10pt;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;">* Redistributions of source code must retain the above copyright notice, this</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;"> list of conditions and the following disclaimer.</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;">* Redistributions in binary form must reproduce the above copyright notice, this</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;"> list of conditions and the following disclaimer in the documentation and/or other</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;"> materials provided with the distribution.</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;">* The name of the contributors may not be used to endorse or promote products</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;"> derived from this software without specific prior written permission.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Ubuntu'; font-size:10pt;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;">THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS &quot;AS IS&quot; AND</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;">ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;">WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;">IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;">INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;">BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;">DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;">LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;">OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:10pt;">OF THE POSSIBILITY OF SUCH DAMAGE.</span></p></body></html> + + + + + + + + + + + + + false + + + About Qt + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Close + + + + + + + + + + + + + diff --git a/gui/dialogs/CopyInstanceDialog.cpp b/gui/dialogs/CopyInstanceDialog.cpp new file mode 100644 index 00000000..4d588a1e --- /dev/null +++ b/gui/dialogs/CopyInstanceDialog.cpp @@ -0,0 +1,84 @@ +/* Copyright 2013 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 +#include + +#include "MultiMC.h" +#include "CopyInstanceDialog.h" +#include "ui_CopyInstanceDialog.h" + +#include "gui/Platform.h" +#include "gui/dialogs/VersionSelectDialog.h" +#include "gui/dialogs/ProgressDialog.h" +#include "gui/dialogs/IconPickerDialog.h" + +#include "logic/InstanceFactory.h" +#include "logic/BaseVersion.h" +#include "logic/lists/IconList.h" +#include "logic/lists/MinecraftVersionList.h" +#include "logic/tasks/Task.h" +#include "logic/BaseInstance.h" + +CopyInstanceDialog::CopyInstanceDialog(BaseInstance *original, QWidget *parent) + : m_original(original), QDialog(parent), ui(new Ui::CopyInstanceDialog) +{ + MultiMCPlatform::fixWM_CLASS(this); + ui->setupUi(this); + resize(minimumSizeHint()); + layout()->setSizeConstraint(QLayout::SetFixedSize); + + InstIconKey = original->iconKey(); + ui->iconButton->setIcon(MMC->icons()->getIcon(InstIconKey)); + ui->instNameTextBox->setText(original->name()); + ui->instNameTextBox->setFocus(); +} + +CopyInstanceDialog::~CopyInstanceDialog() +{ + delete ui; +} + +void CopyInstanceDialog::updateDialogState() +{ + ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(!instName().isEmpty()); +} + +QString CopyInstanceDialog::instName() const +{ + return ui->instNameTextBox->text(); +} + +QString CopyInstanceDialog::iconKey() const +{ + return InstIconKey; +} + +void CopyInstanceDialog::on_iconButton_clicked() +{ + IconPickerDialog dlg(this); + dlg.exec(InstIconKey); + + if (dlg.result() == QDialog::Accepted) + { + InstIconKey = dlg.selectedIconKey; + ui->iconButton->setIcon(MMC->icons()->getIcon(InstIconKey)); + } +} + +void CopyInstanceDialog::on_instNameTextBox_textChanged(const QString &arg1) +{ + updateDialogState(); +} diff --git a/gui/dialogs/CopyInstanceDialog.h b/gui/dialogs/CopyInstanceDialog.h new file mode 100644 index 00000000..7ab366e2 --- /dev/null +++ b/gui/dialogs/CopyInstanceDialog.h @@ -0,0 +1,50 @@ +/* Copyright 2013 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 +#include "logic/BaseVersion.h" + +class BaseInstance; + +namespace Ui +{ +class CopyInstanceDialog; +} + +class CopyInstanceDialog : public QDialog +{ + Q_OBJECT + +public: + explicit CopyInstanceDialog(BaseInstance *original, QWidget *parent = 0); + ~CopyInstanceDialog(); + + void updateDialogState(); + + QString instName() const; + QString iconKey() const; + +private +slots: + void on_iconButton_clicked(); + void on_instNameTextBox_textChanged(const QString &arg1); + +private: + Ui::CopyInstanceDialog *ui; + QString InstIconKey; + BaseInstance *m_original; +}; diff --git a/gui/dialogs/CopyInstanceDialog.ui b/gui/dialogs/CopyInstanceDialog.ui new file mode 100644 index 00000000..dd7ce641 --- /dev/null +++ b/gui/dialogs/CopyInstanceDialog.ui @@ -0,0 +1,134 @@ + + + CopyInstanceDialog + + + Qt::ApplicationModal + + + + 0 + 0 + 345 + 205 + + + + Copy Instance + + + + :/icons/toolbar/copy:/icons/toolbar/copy + + + true + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + :/icons/instances/infinity:/icons/instances/infinity + + + + 80 + 80 + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + Name + + + + + + + Qt::Horizontal + + + + + + + Qt::Horizontal + + + QDialogButtonBox::Cancel|QDialogButtonBox::Ok + + + + + + + + + + + buttonBox + accepted() + CopyInstanceDialog + accept() + + + 248 + 254 + + + 157 + 274 + + + + + buttonBox + rejected() + CopyInstanceDialog + reject() + + + 316 + 260 + + + 286 + 274 + + + + + diff --git a/gui/dialogs/CustomMessageBox.cpp b/gui/dialogs/CustomMessageBox.cpp new file mode 100644 index 00000000..1d2ab58a --- /dev/null +++ b/gui/dialogs/CustomMessageBox.cpp @@ -0,0 +1,34 @@ +/* Copyright 2013 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 "CustomMessageBox.h" + +namespace CustomMessageBox +{ +QMessageBox *selectable(QWidget *parent, const QString &title, const QString &text, + QMessageBox::Icon icon, QMessageBox::StandardButtons buttons, + QMessageBox::StandardButton defaultButton) +{ + QMessageBox *messageBox = new QMessageBox(parent); + messageBox->setWindowTitle(title); + messageBox->setText(text); + messageBox->setStandardButtons(buttons); + messageBox->setDefaultButton(defaultButton); + messageBox->setTextInteractionFlags(Qt::TextSelectableByMouse); + messageBox->setIcon(icon); + + return messageBox; +} +} diff --git a/gui/dialogs/CustomMessageBox.h b/gui/dialogs/CustomMessageBox.h new file mode 100644 index 00000000..b08b9f57 --- /dev/null +++ b/gui/dialogs/CustomMessageBox.h @@ -0,0 +1,26 @@ +/* Copyright 2013 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 + +namespace CustomMessageBox +{ +QMessageBox *selectable(QWidget *parent, const QString &title, const QString &text, + QMessageBox::Icon icon = QMessageBox::NoIcon, + QMessageBox::StandardButtons buttons = QMessageBox::Ok, + QMessageBox::StandardButton defaultButton = QMessageBox::NoButton); +} diff --git a/gui/dialogs/EditNotesDialog.cpp b/gui/dialogs/EditNotesDialog.cpp new file mode 100644 index 00000000..cd52e694 --- /dev/null +++ b/gui/dialogs/EditNotesDialog.cpp @@ -0,0 +1,42 @@ +/* Copyright 2013 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 "EditNotesDialog.h" +#include "ui_EditNotesDialog.h" +#include "gui/Platform.h" + +#include +#include + +EditNotesDialog::EditNotesDialog(QString notes, QString name, QWidget *parent) + : m_instance_notes(notes), m_instance_name(name), QDialog(parent), + ui(new Ui::EditNotesDialog) +{ + MultiMCPlatform::fixWM_CLASS(this); + ui->setupUi(this); + ui->noteEditor->setText(notes); + setWindowTitle(tr("Edit notes of %1").arg(m_instance_name)); + // connect(ui->closeButton, SIGNAL(clicked()), SLOT(close())); +} + +EditNotesDialog::~EditNotesDialog() +{ + delete ui; +} + +QString EditNotesDialog::getText() +{ + return ui->noteEditor->toPlainText(); +} diff --git a/gui/dialogs/EditNotesDialog.h b/gui/dialogs/EditNotesDialog.h new file mode 100644 index 00000000..b74558c4 --- /dev/null +++ b/gui/dialogs/EditNotesDialog.h @@ -0,0 +1,38 @@ +/* Copyright 2013 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 + +namespace Ui +{ +class EditNotesDialog; +} + +class EditNotesDialog : public QDialog +{ + Q_OBJECT + +public: + explicit EditNotesDialog(QString notes, QString name, QWidget *parent = 0); + ~EditNotesDialog(); + QString getText(); + +private: + Ui::EditNotesDialog *ui; + QString m_instance_name; + QString m_instance_notes; +}; diff --git a/gui/dialogs/EditNotesDialog.ui b/gui/dialogs/EditNotesDialog.ui new file mode 100644 index 00000000..487dfb84 --- /dev/null +++ b/gui/dialogs/EditNotesDialog.ui @@ -0,0 +1,77 @@ + + + EditNotesDialog + + + + 0 + 0 + 459 + 399 + + + + Edit Notes + + + + + + Qt::ScrollBarAlwaysOn + + + false + + + Qt::LinksAccessibleByKeyboard|Qt::LinksAccessibleByMouse|Qt::TextBrowserInteraction|Qt::TextEditable|Qt::TextEditorInteraction|Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse + + + + + + + Qt::Horizontal + + + QDialogButtonBox::Cancel|QDialogButtonBox::Ok + + + + + + + + + buttonBox + accepted() + EditNotesDialog + accept() + + + 248 + 254 + + + 157 + 274 + + + + + buttonBox + rejected() + EditNotesDialog + reject() + + + 316 + 260 + + + 286 + 274 + + + + + diff --git a/gui/dialogs/IconPickerDialog.cpp b/gui/dialogs/IconPickerDialog.cpp new file mode 100644 index 00000000..99d6dc9a --- /dev/null +++ b/gui/dialogs/IconPickerDialog.cpp @@ -0,0 +1,156 @@ +/* Copyright 2013 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 +#include +#include + +#include "MultiMC.h" + +#include "IconPickerDialog.h" +#include "ui_IconPickerDialog.h" + +#include "gui/Platform.h" +#include "gui/widgets/InstanceDelegate.h" + +#include "logic/lists/IconList.h" + +IconPickerDialog::IconPickerDialog(QWidget *parent) + : QDialog(parent), ui(new Ui::IconPickerDialog) +{ + MultiMCPlatform::fixWM_CLASS(this); + ui->setupUi(this); + setWindowModality(Qt::WindowModal); + + auto contentsWidget = ui->iconView; + contentsWidget->setViewMode(QListView::IconMode); + contentsWidget->setFlow(QListView::LeftToRight); + contentsWidget->setIconSize(QSize(48, 48)); + contentsWidget->setMovement(QListView::Static); + contentsWidget->setResizeMode(QListView::Adjust); + contentsWidget->setSelectionMode(QAbstractItemView::SingleSelection); + contentsWidget->setSpacing(5); + contentsWidget->setWordWrap(false); + contentsWidget->setWrapping(true); + contentsWidget->setUniformItemSizes(true); + contentsWidget->setTextElideMode(Qt::ElideRight); + contentsWidget->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel); + contentsWidget->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn); + contentsWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + contentsWidget->setItemDelegate(new ListViewDelegate()); + + // contentsWidget->setAcceptDrops(true); + contentsWidget->setDropIndicatorShown(true); + contentsWidget->viewport()->setAcceptDrops(true); + contentsWidget->setDragDropMode(QAbstractItemView::DropOnly); + contentsWidget->setDefaultDropAction(Qt::CopyAction); + + contentsWidget->installEventFilter(this); + + contentsWidget->setModel(MMC->icons().get()); + + auto buttonAdd = ui->buttonBox->addButton(tr("Add Icon"), QDialogButtonBox::ResetRole); + auto buttonRemove = + ui->buttonBox->addButton(tr("Remove Icon"), QDialogButtonBox::ResetRole); + + connect(buttonAdd, SIGNAL(clicked(bool)), SLOT(addNewIcon())); + connect(buttonRemove, SIGNAL(clicked(bool)), SLOT(removeSelectedIcon())); + + connect(contentsWidget, SIGNAL(doubleClicked(QModelIndex)), SLOT(activated(QModelIndex))); + + connect(contentsWidget->selectionModel(), + SIGNAL(selectionChanged(QItemSelection, QItemSelection)), + SLOT(selectionChanged(QItemSelection, QItemSelection))); +} +bool IconPickerDialog::eventFilter(QObject *obj, QEvent *evt) +{ + if (obj != ui->iconView) + return QDialog::eventFilter(obj, evt); + if (evt->type() != QEvent::KeyPress) + { + return QDialog::eventFilter(obj, evt); + } + QKeyEvent *keyEvent = static_cast(evt); + switch (keyEvent->key()) + { + case Qt::Key_Delete: + removeSelectedIcon(); + return true; + case Qt::Key_Plus: + addNewIcon(); + return true; + default: + break; + } + return QDialog::eventFilter(obj, evt); +} + +void IconPickerDialog::addNewIcon() +{ + //: The title of the select icons open file dialog + QString selectIcons = tr("Select Icons"); + //: The type of icon files + QStringList fileNames = QFileDialog::getOpenFileNames(this, selectIcons, QString(), + tr("Icons") + "(*.png *.jpg *.jpeg)"); + MMC->icons()->installIcons(fileNames); +} + +void IconPickerDialog::removeSelectedIcon() +{ + MMC->icons()->deleteIcon(selectedIconKey); +} + +void IconPickerDialog::activated(QModelIndex index) +{ + selectedIconKey = index.data(Qt::UserRole).toString(); + accept(); +} + +void IconPickerDialog::selectionChanged(QItemSelection selected, QItemSelection deselected) +{ + if (selected.empty()) + return; + + QString key = selected.first().indexes().first().data(Qt::UserRole).toString(); + if (!key.isEmpty()) + selectedIconKey = key; +} + +int IconPickerDialog::exec(QString selection) +{ + auto list = MMC->icons(); + auto contentsWidget = ui->iconView; + selectedIconKey = selection; + + int index_nr = list->getIconIndex(selection); + auto model_index = list->index(index_nr); + contentsWidget->selectionModel()->select( + model_index, QItemSelectionModel::Current | QItemSelectionModel::Select); + + QMetaObject::invokeMethod(this, "delayed_scroll", Qt::QueuedConnection, + Q_ARG(QModelIndex, model_index)); + return QDialog::exec(); +} + +void IconPickerDialog::delayed_scroll(QModelIndex model_index) +{ + auto contentsWidget = ui->iconView; + contentsWidget->scrollTo(model_index); +} + +IconPickerDialog::~IconPickerDialog() +{ + delete ui; +} diff --git a/gui/dialogs/IconPickerDialog.h b/gui/dialogs/IconPickerDialog.h new file mode 100644 index 00000000..f00c2388 --- /dev/null +++ b/gui/dialogs/IconPickerDialog.h @@ -0,0 +1,48 @@ +/* Copyright 2013 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 +#include + +namespace Ui +{ +class IconPickerDialog; +} + +class IconPickerDialog : public QDialog +{ + Q_OBJECT + +public: + explicit IconPickerDialog(QWidget *parent = 0); + ~IconPickerDialog(); + int exec(QString selection); + QString selectedIconKey; + +protected: + virtual bool eventFilter(QObject *, QEvent *); + +private: + Ui::IconPickerDialog *ui; + +private +slots: + void selectionChanged(QItemSelection, QItemSelection); + void activated(QModelIndex); + void delayed_scroll(QModelIndex); + void addNewIcon(); + void removeSelectedIcon(); +}; diff --git a/gui/dialogs/IconPickerDialog.ui b/gui/dialogs/IconPickerDialog.ui new file mode 100644 index 00000000..c548edfb --- /dev/null +++ b/gui/dialogs/IconPickerDialog.ui @@ -0,0 +1,67 @@ + + + IconPickerDialog + + + + 0 + 0 + 676 + 555 + + + + Pick icon + + + + + + + + + Qt::Horizontal + + + QDialogButtonBox::Cancel|QDialogButtonBox::Ok + + + + + + + + + buttonBox + accepted() + IconPickerDialog + accept() + + + 248 + 254 + + + 157 + 274 + + + + + buttonBox + rejected() + IconPickerDialog + reject() + + + 316 + 260 + + + 286 + 274 + + + + + diff --git a/gui/dialogs/InstanceSettings.cpp b/gui/dialogs/InstanceSettings.cpp new file mode 100644 index 00000000..57dd6a81 --- /dev/null +++ b/gui/dialogs/InstanceSettings.cpp @@ -0,0 +1,180 @@ +/* Copyright 2013 MultiMC Contributors + * + * Authors: Andrew Okin + * Peterix + * Orochimarufan + * + * 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 "InstanceSettings.h" +#include "ui_InstanceSettings.h" +#include "gui/Platform.h" + +InstanceSettings::InstanceSettings(SettingsObject *obj, QWidget *parent) + : m_obj(obj), QDialog(parent), ui(new Ui::InstanceSettings) +{ + MultiMCPlatform::fixWM_CLASS(this); + ui->setupUi(this); + loadSettings(); +} + +InstanceSettings::~InstanceSettings() +{ + delete ui; +} + +void InstanceSettings::showEvent(QShowEvent *ev) +{ + QDialog::showEvent(ev); + adjustSize(); +} + +void InstanceSettings::on_customCommandsGroupBox_toggled(bool state) +{ + ui->labelCustomCmdsDescription->setEnabled(state); +} + +void InstanceSettings::on_buttonBox_accepted() +{ + applySettings(); + accept(); +} + +void InstanceSettings::on_buttonBox_rejected() +{ + reject(); +} + +void InstanceSettings::applySettings() +{ + // Console + bool console = ui->consoleSettingsBox->isChecked(); + m_obj->set("OverrideConsole", console); + if (console) + { + m_obj->set("ShowConsole", ui->showConsoleCheck->isChecked()); + m_obj->set("AutoCloseConsole", ui->autoCloseConsoleCheck->isChecked()); + } + else + { + m_obj->reset("ShowConsole"); + m_obj->reset("AutoCloseConsole"); + } + + // Window Size + bool window = ui->windowSizeGroupBox->isChecked(); + m_obj->set("OverrideWindow", window); + if (window) + { + m_obj->set("LaunchMaximized", ui->maximizedCheckBox->isChecked()); + m_obj->set("MinecraftWinWidth", ui->windowWidthSpinBox->value()); + m_obj->set("MinecraftWinHeight", ui->windowHeightSpinBox->value()); + } + else + { + m_obj->reset("LaunchMaximized"); + m_obj->reset("MinecraftWinWidth"); + m_obj->reset("MinecraftWinHeight"); + } + + // Auto Login + bool login = ui->accountSettingsGroupBox->isChecked(); + m_obj->set("OverrideLogin", login); + if (login) + { + m_obj->set("AutoLogin", ui->autoLoginChecBox->isChecked()); + } + else + { + m_obj->reset("AutoLogin"); + } + + // Memory + bool memory = ui->memoryGroupBox->isChecked(); + m_obj->set("OverrideMemory", memory); + if (memory) + { + m_obj->set("MinMemAlloc", ui->minMemSpinBox->value()); + m_obj->set("MaxMemAlloc", ui->maxMemSpinBox->value()); + m_obj->set("PermGen", ui->permGenSpinBox->value()); + } + else + { + m_obj->reset("MinMemAlloc"); + m_obj->reset("MaxMemAlloc"); + m_obj->reset("PermGen"); + } + + // Java Settings + bool java = ui->javaSettingsGroupBox->isChecked(); + m_obj->set("OverrideJava", java); + if (java) + { + m_obj->set("JavaPath", ui->javaPathTextBox->text()); + m_obj->set("JvmArgs", ui->jvmArgsTextBox->text()); + } + else + { + m_obj->reset("JavaPath"); + m_obj->reset("JvmArgs"); + } + + // Custom Commands + bool custcmd = ui->customCommandsGroupBox->isChecked(); + m_obj->set("OverrideCommands", custcmd); + if (custcmd) + { + m_obj->set("PreLaunchCommand", ui->preLaunchCmdTextBox->text()); + m_obj->set("PostExitCommand", ui->postExitCmdTextBox->text()); + } + else + { + m_obj->reset("PreLaunchCommand"); + m_obj->reset("PostExitCommand"); + } +} + +void InstanceSettings::loadSettings() +{ + // Console + ui->consoleSettingsBox->setChecked(m_obj->get("OverrideConsole").toBool()); + ui->showConsoleCheck->setChecked(m_obj->get("ShowConsole").toBool()); + ui->autoCloseConsoleCheck->setChecked(m_obj->get("AutoCloseConsole").toBool()); + + // Window Size + ui->windowSizeGroupBox->setChecked(m_obj->get("OverrideWindow").toBool()); + ui->maximizedCheckBox->setChecked(m_obj->get("LaunchMaximized").toBool()); + ui->windowWidthSpinBox->setValue(m_obj->get("MinecraftWinWidth").toInt()); + ui->windowHeightSpinBox->setValue(m_obj->get("MinecraftWinHeight").toInt()); + + // Auto Login + ui->accountSettingsGroupBox->setChecked(m_obj->get("OverrideLogin").toBool()); + ui->autoLoginChecBox->setChecked(m_obj->get("AutoLogin").toBool()); + + // Memory + ui->memoryGroupBox->setChecked(m_obj->get("OverrideMemory").toBool()); + ui->minMemSpinBox->setValue(m_obj->get("MinMemAlloc").toInt()); + ui->maxMemSpinBox->setValue(m_obj->get("MaxMemAlloc").toInt()); + ui->permGenSpinBox->setValue(m_obj->get("PermGen").toInt()); + + // Java Settings + ui->javaSettingsGroupBox->setChecked(m_obj->get("OverrideJava").toBool()); + ui->javaPathTextBox->setText(m_obj->get("JavaPath").toString()); + ui->jvmArgsTextBox->setText(m_obj->get("JvmArgs").toString()); + + // Custom Commands + ui->customCommandsGroupBox->setChecked(m_obj->get("OverrideCommands").toBool()); + ui->preLaunchCmdTextBox->setText(m_obj->get("PreLaunchCommand").toString()); + ui->postExitCmdTextBox->setText(m_obj->get("PostExitCommand").toString()); +} diff --git a/gui/dialogs/InstanceSettings.h b/gui/dialogs/InstanceSettings.h new file mode 100644 index 00000000..452e7a58 --- /dev/null +++ b/gui/dialogs/InstanceSettings.h @@ -0,0 +1,50 @@ +/* Copyright 2013 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 +#include "settingsobject.h" + +namespace Ui +{ +class InstanceSettings; +} + +class InstanceSettings : public QDialog +{ + Q_OBJECT + +public: + explicit InstanceSettings(SettingsObject *s, QWidget *parent = 0); + ~InstanceSettings(); + + void updateCheckboxStuff(); + + void applySettings(); + void loadSettings(); + +protected: + virtual void showEvent(QShowEvent *); +private +slots: + void on_customCommandsGroupBox_toggled(bool arg1); + void on_buttonBox_accepted(); + void on_buttonBox_rejected(); + +private: + Ui::InstanceSettings *ui; + SettingsObject *m_obj; +}; diff --git a/gui/dialogs/InstanceSettings.ui b/gui/dialogs/InstanceSettings.ui new file mode 100644 index 00000000..b536e9ff --- /dev/null +++ b/gui/dialogs/InstanceSettings.ui @@ -0,0 +1,422 @@ + + + InstanceSettings + + + + 0 + 0 + 526 + 590 + + + + + + + + + + QTabWidget::Rounded + + + 0 + + + + Minecraft + + + + + + true + + + Window Size + + + true + + + false + + + + + + Start Minecraft maximized? + + + + + + + + + Window height: + + + + + + + Window width: + + + + + + + 854 + + + 65536 + + + 1 + + + 854 + + + + + + + 480 + + + 65536 + + + 480 + + + + + + + + + + + + true + + + Console Settings + + + true + + + false + + + + + + Show console while the game is running? + + + + + + + Automatically close console when the game quits? + + + + + + + + + + true + + + Account Settings + + + true + + + false + + + + + + false + + + Login automatically when an instance icon is double clicked? + + + false + + + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + Java + + + + + + true + + + Memory + + + true + + + false + + + + + + 512 + + + 65536 + + + 128 + + + 1024 + + + + + + + Minimum memory allocation: + + + + + + + Maximum memory allocation: + + + + + + + 256 + + + 65536 + + + 128 + + + 256 + + + + + + + 64 + + + 999999999 + + + 8 + + + 64 + + + + + + + PermGen: + + + + + + + + + + true + + + Java Settings + + + true + + + false + + + + + + Java path: + + + + + + + + + + JVM arguments: + + + + + + + Auto-detect + + + + + + + + + + + + + true + + + Custom Commands + + + true + + + false + + + + + + + + + Post-exit command: + + + + + + + Pre-launch command: + + + + + + + + + + + + + false + + + + 0 + 0 + + + + Pre-launch command runs before the instance launches and post-exit command runs after it exits. Both will be run in MultiMC's working directory with INST_ID, INST_DIR, and INST_NAME as environment variables. + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop + + + true + + + Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse + + + + + + + + + + + Qt::Horizontal + + + QDialogButtonBox::Cancel|QDialogButtonBox::Ok + + + + + + + settingsTabs + buttonBox + windowSizeGroupBox + maximizedCheckBox + windowWidthSpinBox + windowHeightSpinBox + consoleSettingsBox + showConsoleCheck + autoCloseConsoleCheck + accountSettingsGroupBox + autoLoginChecBox + memoryGroupBox + minMemSpinBox + maxMemSpinBox + permGenSpinBox + javaSettingsGroupBox + javaPathTextBox + pushButton + jvmArgsTextBox + customCommandsGroupBox + preLaunchCmdTextBox + postExitCmdTextBox + + + + diff --git a/gui/dialogs/LegacyModEditDialog.cpp b/gui/dialogs/LegacyModEditDialog.cpp new file mode 100644 index 00000000..25a1c616 --- /dev/null +++ b/gui/dialogs/LegacyModEditDialog.cpp @@ -0,0 +1,393 @@ +/* Copyright 2013 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 "MultiMC.h" +#include "LegacyModEditDialog.h" +#include "ModEditDialogCommon.h" +#include "VersionSelectDialog.h" +#include "ProgressDialog.h" +#include "ui_LegacyModEditDialog.h" +#include "logic/ModList.h" +#include "logic/lists/ForgeVersionList.h" +#include "gui/Platform.h" + +#include +#include +//#include +#include +#include +#include + +LegacyModEditDialog::LegacyModEditDialog(LegacyInstance *inst, QWidget *parent) + : m_inst(inst), QDialog(parent), ui(new Ui::LegacyModEditDialog) +{ + MultiMCPlatform::fixWM_CLASS(this); + ui->setupUi(this); + + // Jar mods + { + ensureFolderPathExists(m_inst->jarModsDir()); + m_jarmods = m_inst->jarModList(); + ui->jarModsTreeView->setModel(m_jarmods.get()); +#ifndef Q_OS_LINUX + // FIXME: internal DnD causes segfaults later + ui->jarModsTreeView->setDragDropMode(QAbstractItemView::DragDrop); + // FIXME: DnD is glitched with contiguous (we move only first item in selection) + ui->jarModsTreeView->setSelectionMode(QAbstractItemView::SingleSelection); +#endif + ui->jarModsTreeView->installEventFilter(this); + m_jarmods->startWatching(); + auto smodel = ui->jarModsTreeView->selectionModel(); + connect(smodel, SIGNAL(currentChanged(QModelIndex, QModelIndex)), + SLOT(jarCurrent(QModelIndex, QModelIndex))); + } + // Core mods + { + ensureFolderPathExists(m_inst->coreModsDir()); + m_coremods = m_inst->coreModList(); + ui->coreModsTreeView->setModel(m_coremods.get()); + ui->coreModsTreeView->installEventFilter(this); + m_coremods->startWatching(); + auto smodel = ui->coreModsTreeView->selectionModel(); + connect(smodel, SIGNAL(currentChanged(QModelIndex, QModelIndex)), + SLOT(coreCurrent(QModelIndex, QModelIndex))); + } + // Loader mods + { + ensureFolderPathExists(m_inst->loaderModsDir()); + m_mods = m_inst->loaderModList(); + ui->loaderModTreeView->setModel(m_mods.get()); + ui->loaderModTreeView->installEventFilter(this); + m_mods->startWatching(); + auto smodel = ui->loaderModTreeView->selectionModel(); + connect(smodel, SIGNAL(currentChanged(QModelIndex, QModelIndex)), + SLOT(loaderCurrent(QModelIndex, QModelIndex))); + } + // texture packs + { + ensureFolderPathExists(m_inst->texturePacksDir()); + m_texturepacks = m_inst->texturePackList(); + ui->texPackTreeView->setModel(m_texturepacks.get()); + ui->texPackTreeView->installEventFilter(this); + m_texturepacks->startWatching(); + } +} + +LegacyModEditDialog::~LegacyModEditDialog() +{ + m_mods->stopWatching(); + m_coremods->stopWatching(); + m_jarmods->stopWatching(); + m_texturepacks->stopWatching(); + delete ui; +} + +bool LegacyModEditDialog::coreListFilter(QKeyEvent *keyEvent) +{ + switch (keyEvent->key()) + { + case Qt::Key_Delete: + on_rmCoreBtn_clicked(); + return true; + case Qt::Key_Plus: + on_addCoreBtn_clicked(); + return true; + default: + break; + } + return QDialog::eventFilter(ui->coreModsTreeView, keyEvent); +} + +bool LegacyModEditDialog::jarListFilter(QKeyEvent *keyEvent) +{ + switch (keyEvent->key()) + { + case Qt::Key_Up: + { + if (keyEvent->modifiers() & Qt::ControlModifier) + { + on_moveJarUpBtn_clicked(); + return true; + } + break; + } + case Qt::Key_Down: + { + if (keyEvent->modifiers() & Qt::ControlModifier) + { + on_moveJarDownBtn_clicked(); + return true; + } + break; + } + case Qt::Key_Delete: + on_rmJarBtn_clicked(); + return true; + case Qt::Key_Plus: + on_addJarBtn_clicked(); + return true; + default: + break; + } + return QDialog::eventFilter(ui->jarModsTreeView, keyEvent); +} + +bool LegacyModEditDialog::loaderListFilter(QKeyEvent *keyEvent) +{ + switch (keyEvent->key()) + { + case Qt::Key_Delete: + on_rmModBtn_clicked(); + return true; + case Qt::Key_Plus: + on_addModBtn_clicked(); + return true; + default: + break; + } + return QDialog::eventFilter(ui->loaderModTreeView, keyEvent); +} + +bool LegacyModEditDialog::texturePackListFilter(QKeyEvent *keyEvent) +{ + switch (keyEvent->key()) + { + case Qt::Key_Delete: + on_rmTexPackBtn_clicked(); + return true; + case Qt::Key_Plus: + on_addTexPackBtn_clicked(); + return true; + default: + break; + } + return QDialog::eventFilter(ui->texPackTreeView, keyEvent); +} + +bool LegacyModEditDialog::eventFilter(QObject *obj, QEvent *ev) +{ + if (ev->type() != QEvent::KeyPress) + { + return QDialog::eventFilter(obj, ev); + } + QKeyEvent *keyEvent = static_cast(ev); + if (obj == ui->jarModsTreeView) + return jarListFilter(keyEvent); + if (obj == ui->coreModsTreeView) + return coreListFilter(keyEvent); + if (obj == ui->loaderModTreeView) + return loaderListFilter(keyEvent); + if (obj == ui->texPackTreeView) + return texturePackListFilter(keyEvent); + return QDialog::eventFilter(obj, ev); +} + +void LegacyModEditDialog::on_addCoreBtn_clicked() +{ + //: Title of core mod selection dialog + QStringList fileNames = QFileDialog::getOpenFileNames(this, tr("Select Core Mods")); + for (auto filename : fileNames) + { + m_coremods->stopWatching(); + m_coremods->installMod(QFileInfo(filename)); + m_coremods->startWatching(); + } +} +void LegacyModEditDialog::on_addForgeBtn_clicked() +{ + VersionSelectDialog vselect(MMC->forgelist().get(), tr("Select Forge version"), this); + vselect.setFilter(1, m_inst->intendedVersionId()); + if (vselect.exec() && vselect.selectedVersion()) + { + ForgeVersionPtr forge = + std::dynamic_pointer_cast(vselect.selectedVersion()); + if (!forge) + return; + auto entry = MMC->metacache()->resolveEntry("minecraftforge", forge->filename); + if (entry->stale) + { + NetJob *fjob = new NetJob("Forge download"); + fjob->addNetAction(CacheDownload::make(forge->universal_url, entry)); + ProgressDialog dlg(this); + dlg.exec(fjob); + if (dlg.result() == QDialog::Accepted) + { + m_jarmods->stopWatching(); + m_jarmods->installMod(QFileInfo(entry->getFullPath())); + m_jarmods->startWatching(); + } + else + { + // failed to download forge :/ + } + } + else + { + m_jarmods->stopWatching(); + m_jarmods->installMod(QFileInfo(entry->getFullPath())); + m_jarmods->startWatching(); + } + } +} +void LegacyModEditDialog::on_addJarBtn_clicked() +{ + //: Title of jar mod selection dialog + QStringList fileNames = QFileDialog::getOpenFileNames(this, tr("Select Jar Mods")); + for (auto filename : fileNames) + { + m_jarmods->stopWatching(); + m_jarmods->installMod(QFileInfo(filename)); + m_jarmods->startWatching(); + } +} +void LegacyModEditDialog::on_addModBtn_clicked() +{ + //: Title of regular mod selection dialog + QStringList fileNames = QFileDialog::getOpenFileNames(this, tr("Select Loader Mods")); + for (auto filename : fileNames) + { + m_mods->stopWatching(); + m_mods->installMod(QFileInfo(filename)); + m_mods->startWatching(); + } +} +void LegacyModEditDialog::on_addTexPackBtn_clicked() +{ + //: Title of texture pack selection dialog + QStringList fileNames = QFileDialog::getOpenFileNames(this, tr("Select Texture Packs")); + for (auto filename : fileNames) + { + m_texturepacks->stopWatching(); + m_texturepacks->installMod(QFileInfo(filename)); + m_texturepacks->startWatching(); + } +} + +void LegacyModEditDialog::on_moveJarDownBtn_clicked() +{ + int first, last; + auto list = ui->jarModsTreeView->selectionModel()->selectedRows(); + + if (!lastfirst(list, first, last)) + return; + + m_jarmods->moveModsDown(first, last); +} +void LegacyModEditDialog::on_moveJarUpBtn_clicked() +{ + int first, last; + auto list = ui->jarModsTreeView->selectionModel()->selectedRows(); + + if (!lastfirst(list, first, last)) + return; + m_jarmods->moveModsUp(first, last); +} +void LegacyModEditDialog::on_rmCoreBtn_clicked() +{ + int first, last; + auto list = ui->coreModsTreeView->selectionModel()->selectedRows(); + + if (!lastfirst(list, first, last)) + return; + m_coremods->stopWatching(); + m_coremods->deleteMods(first, last); + m_coremods->startWatching(); +} +void LegacyModEditDialog::on_rmJarBtn_clicked() +{ + int first, last; + auto list = ui->jarModsTreeView->selectionModel()->selectedRows(); + + if (!lastfirst(list, first, last)) + return; + m_jarmods->stopWatching(); + m_jarmods->deleteMods(first, last); + m_jarmods->startWatching(); +} +void LegacyModEditDialog::on_rmModBtn_clicked() +{ + int first, last; + auto list = ui->loaderModTreeView->selectionModel()->selectedRows(); + + if (!lastfirst(list, first, last)) + return; + m_mods->stopWatching(); + m_mods->deleteMods(first, last); + m_mods->startWatching(); +} +void LegacyModEditDialog::on_rmTexPackBtn_clicked() +{ + int first, last; + auto list = ui->texPackTreeView->selectionModel()->selectedRows(); + + if (!lastfirst(list, first, last)) + return; + m_texturepacks->stopWatching(); + m_texturepacks->deleteMods(first, last); + m_texturepacks->startWatching(); +} +void LegacyModEditDialog::on_viewCoreBtn_clicked() +{ + openDirInDefaultProgram(m_inst->coreModsDir(), true); +} +void LegacyModEditDialog::on_viewModBtn_clicked() +{ + openDirInDefaultProgram(m_inst->loaderModsDir(), true); +} +void LegacyModEditDialog::on_viewTexPackBtn_clicked() +{ + openDirInDefaultProgram(m_inst->texturePacksDir(), true); +} + +void LegacyModEditDialog::on_buttonBox_rejected() +{ + close(); +} + +void LegacyModEditDialog::jarCurrent(QModelIndex current, QModelIndex previous) +{ + if (!current.isValid()) + { + ui->jarMIFrame->clear(); + return; + } + int row = current.row(); + Mod &m = m_jarmods->operator[](row); + ui->jarMIFrame->updateWithMod(m); +} + +void LegacyModEditDialog::coreCurrent(QModelIndex current, QModelIndex previous) +{ + if (!current.isValid()) + { + ui->coreMIFrame->clear(); + return; + } + int row = current.row(); + Mod &m = m_coremods->operator[](row); + ui->coreMIFrame->updateWithMod(m); +} + +void LegacyModEditDialog::loaderCurrent(QModelIndex current, QModelIndex previous) +{ + if (!current.isValid()) + { + ui->loaderMIFrame->clear(); + return; + } + int row = current.row(); + Mod &m = m_mods->operator[](row); + ui->loaderMIFrame->updateWithMod(m); +} diff --git a/gui/dialogs/LegacyModEditDialog.h b/gui/dialogs/LegacyModEditDialog.h new file mode 100644 index 00000000..d5582aef --- /dev/null +++ b/gui/dialogs/LegacyModEditDialog.h @@ -0,0 +1,78 @@ +/* Copyright 2013 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 +#include "logic/LegacyInstance.h" +#include + +namespace Ui +{ +class LegacyModEditDialog; +} + +class LegacyModEditDialog : public QDialog +{ + Q_OBJECT + +public: + explicit LegacyModEditDialog(LegacyInstance *inst, QWidget *parent = 0); + ~LegacyModEditDialog(); + +private +slots: + + void on_addJarBtn_clicked(); + void on_rmJarBtn_clicked(); + void on_addForgeBtn_clicked(); + void on_moveJarUpBtn_clicked(); + void on_moveJarDownBtn_clicked(); + + void on_addCoreBtn_clicked(); + void on_rmCoreBtn_clicked(); + void on_viewCoreBtn_clicked(); + + void on_addModBtn_clicked(); + void on_rmModBtn_clicked(); + void on_viewModBtn_clicked(); + + void on_addTexPackBtn_clicked(); + void on_rmTexPackBtn_clicked(); + void on_viewTexPackBtn_clicked(); + + // Questionable: SettingsDialog doesn't need this for some reason? + void on_buttonBox_rejected(); + + void jarCurrent(QModelIndex current, QModelIndex previous); + void coreCurrent(QModelIndex current, QModelIndex previous); + void loaderCurrent(QModelIndex current, QModelIndex previous); + +protected: + bool eventFilter(QObject *obj, QEvent *ev); + bool jarListFilter(QKeyEvent *ev); + bool coreListFilter(QKeyEvent *ev); + bool loaderListFilter(QKeyEvent *ev); + bool texturePackListFilter(QKeyEvent *ev); + +private: + Ui::LegacyModEditDialog *ui; + std::shared_ptr m_mods; + std::shared_ptr m_coremods; + std::shared_ptr m_jarmods; + std::shared_ptr m_texturepacks; + LegacyInstance *m_inst; + NetJobPtr forgeJob; +}; diff --git a/gui/dialogs/LegacyModEditDialog.ui b/gui/dialogs/LegacyModEditDialog.ui new file mode 100644 index 00000000..47db0079 --- /dev/null +++ b/gui/dialogs/LegacyModEditDialog.ui @@ -0,0 +1,321 @@ + + + LegacyModEditDialog + + + + 0 + 0 + 540 + 420 + + + + Dialog + + + + + + 0 + + + + Jar Mods + + + + + + + + Qt::ScrollBarAlwaysOn + + + Qt::ScrollBarAlwaysOff + + + + + + + + + &Add + + + + + + + &Remove + + + + + + + MCForge + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + Move &Up + + + + + + + Move &Down + + + + + + + + + + + QFrame::Plain + + + + + + + + Core Mods + + + + + + + + QAbstractItemView::DropOnly + + + + + + + + + &Add + + + + + + + &Remove + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + &View Folder + + + + + + + + + + + QFrame::StyledPanel + + + QFrame::Raised + + + + + + + + Loader Mods + + + + + + + + true + + + QAbstractItemView::DropOnly + + + + + + + + + &Add + + + + + + + &Remove + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + &View Folder + + + + + + + + + + + QFrame::StyledPanel + + + QFrame::Raised + + + + + + + + false + + + Texture Packs + + + + + + true + + + QAbstractItemView::DropOnly + + + + + + + + + &Add + + + + + + + &Remove + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + &View Folder + + + + + + + + + + + + + QDialogButtonBox::Close + + + + + + + + ModListView + QTreeView +
gui/widgets/ModListView.h
+
+ + MCModInfoFrame + QFrame +
gui/widgets/MCModInfoFrame.h
+ 1 +
+
+ + +
diff --git a/gui/dialogs/LoginDialog.cpp b/gui/dialogs/LoginDialog.cpp new file mode 100644 index 00000000..19c6437d --- /dev/null +++ b/gui/dialogs/LoginDialog.cpp @@ -0,0 +1,252 @@ +/* Copyright 2013 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 "LoginDialog.h" +#include "ui_LoginDialog.h" +#include "keyring.h" +#include "gui/Platform.h" +#include "MultiMC.h" + +#include +#include +#include +#include +#include "logic/net/HttpMetaCache.h" +#include "logger/QsLog.h" + +LoginDialog::LoginDialog(QWidget *parent, const QString &loginErrMsg) + : QDialog(parent), ui(new Ui::LoginDialog) +{ + MultiMCPlatform::fixWM_CLASS(this); + ui->setupUi(this); + + //: Use offline mode one time + offlineButton = new QPushButton(tr("Offline Once")); + + ui->loginButtonBox->addButton(offlineButton, QDialogButtonBox::ActionRole); + + blockToggles = false; + isOnline_ = true; + onlineForced = false; + + //: The username during login (placeholder) + ui->usernameTextBox->lineEdit()->setPlaceholderText(tr("Name")); + + connect(ui->usernameTextBox, SIGNAL(currentTextChanged(QString)), this, + SLOT(userTextChanged(QString))); + connect(ui->forgetButton, SIGNAL(clicked(bool)), this, SLOT(forgetCurrentUser())); + connect(offlineButton, SIGNAL(clicked(bool)), this, SLOT(launchOffline())); + + if (loginErrMsg.isEmpty()) + ui->loginErrorLabel->setVisible(false); + else + { + ui->loginErrorLabel->setVisible(true); + ui->loginErrorLabel->setText( + QString("%1").arg(loginErrMsg)); + } + + ui->lblFace->setVisible(false); + + resize(minimumSizeHint()); + layout()->setSizeConstraint(QLayout::SetFixedSize); + Keyring *k = Keyring::instance(); + QStringList accounts = k->getStoredAccounts("minecraft"); + ui->usernameTextBox->addItems(accounts); + + // TODO: restore last selected account here, if applicable + + int index = ui->usernameTextBox->currentIndex(); + if (index != -1) + { + ui->passwordTextBox->setFocus(Qt::OtherFocusReason); + } + + connect(ui->rememberUsernameCheckbox, SIGNAL(toggled(bool)), SLOT(usernameToggled(bool))); + connect(ui->rememberPasswordCheckbox, SIGNAL(toggled(bool)), SLOT(passwordToggled(bool))); +} + +LoginDialog::~LoginDialog() +{ + delete offlineButton; + delete ui; +} + +QString LoginDialog::getUsername() const +{ + return ui->usernameTextBox->currentText(); +} + +QString LoginDialog::getPassword() const +{ + return ui->passwordTextBox->text(); +} + +void LoginDialog::forgetCurrentUser() +{ + Keyring *k = Keyring::instance(); + QString acct = ui->usernameTextBox->currentText(); + k->removeStoredAccount("minecraft", acct); + ui->passwordTextBox->clear(); + int index = ui->usernameTextBox->findText(acct); + if (index != -1) + ui->usernameTextBox->removeItem(index); + if (!ui->usernameTextBox->count()) + { + blockToggles = true; + ui->rememberUsernameCheckbox->setChecked(false); + ui->rememberPasswordCheckbox->setChecked(false); + blockToggles = false; + } +} + +void LoginDialog::passwordToggled(bool state) +{ + // if toggled off + if (blockToggles) + return; + blockToggles = true; + if (!state) + { + QLOG_DEBUG() << "password disabled"; + } + else + { + if (!ui->rememberUsernameCheckbox->isChecked()) + { + ui->rememberUsernameCheckbox->setChecked(true); + } + QLOG_DEBUG() << "password enabled"; + } + blockToggles = false; +} + +void LoginDialog::usernameToggled(bool state) +{ + // if toggled off + if (blockToggles) + return; + blockToggles = true; + if (!state) + { + if (ui->rememberPasswordCheckbox->isChecked()) + { + ui->rememberPasswordCheckbox->setChecked(false); + } + QLOG_DEBUG() << "username disabled"; + } + else + { + QLOG_DEBUG() << "username enabled"; + } + blockToggles = false; +} + +void LoginDialog::userTextChanged(const QString &user) +{ + blockToggles = true; + Keyring *k = Keyring::instance(); + QStringList sl = k->getStoredAccounts("minecraft"); + bool gotFace = false; + + if (sl.contains(user)) + { + ui->rememberUsernameCheckbox->setChecked(true); + QString passwd = k->getPassword("minecraft", user); + ui->rememberPasswordCheckbox->setChecked(!passwd.isEmpty()); + ui->passwordTextBox->setText(passwd); + + QByteArray data; + { + auto filename = + MMC->metacache()->resolveEntry("skins", "skins.json")->getFullPath(); + QFile listFile(filename); + if (!listFile.open(QIODevice::ReadOnly)) + return; + data = listFile.readAll(); + } + + QJsonParseError jsonError; + QJsonDocument jsonDoc = QJsonDocument::fromJson(data, &jsonError); + QJsonObject root = jsonDoc.object(); + QJsonObject mappings = root.value("mappings").toObject(); + + if (!mappings[user].isUndefined()) + { + QJsonArray usernames = mappings.value(user).toArray(); + if (!usernames.isEmpty()) + { + QString mapped_username = usernames[0].toString(); + + if (!mapped_username.isEmpty()) + { + QFile fskin(MMC->metacache() + ->resolveEntry("skins", mapped_username + ".png") + ->getFullPath()); + if (fskin.exists()) + { + QPixmap skin(MMC->metacache() + ->resolveEntry("skins", mapped_username + ".png") + ->getFullPath()); + QPixmap face = + skin.copy(8, 8, 8, 8).scaled(48, 48, Qt::KeepAspectRatio); + + ui->lblFace->setPixmap(face); + gotFace = true; + } + } + } + } + } + + ui->lblFace->setVisible(gotFace); + blockToggles = false; +} + +void LoginDialog::accept() +{ + bool saveName = ui->rememberUsernameCheckbox->isChecked(); + bool savePass = ui->rememberPasswordCheckbox->isChecked(); + Keyring *k = Keyring::instance(); + if (saveName) + { + if (savePass) + { + k->storePassword("minecraft", getUsername(), getPassword()); + } + else + { + k->storePassword("minecraft", getUsername(), QString()); + } + } + else + { + QString acct = ui->usernameTextBox->currentText(); + k->removeStoredAccount("minecraft", acct); + } + QDialog::accept(); +} + +void LoginDialog::launchOffline() +{ + isOnline_ = false; + QDialog::accept(); +} + +void LoginDialog::forceOnline() +{ + onlineForced = true; + offlineButton->setEnabled(false); +} diff --git a/gui/dialogs/LoginDialog.h b/gui/dialogs/LoginDialog.h new file mode 100644 index 00000000..73a92aab --- /dev/null +++ b/gui/dialogs/LoginDialog.h @@ -0,0 +1,61 @@ +/* Copyright 2013 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 +#include + +namespace Ui +{ +class LoginDialog; +} + +class LoginDialog : public QDialog +{ + Q_OBJECT + +public: + explicit LoginDialog(QWidget *parent = 0, const QString &loginErrMsg = ""); + ~LoginDialog(); + + QString getUsername() const; + QString getPassword() const; + + inline bool isOnline() + { + return isOnline_; + } + + void forceOnline(); + +public +slots: + virtual void accept(); + virtual void userTextChanged(const QString &user); + virtual void forgetCurrentUser(); +private +slots: + void usernameToggled(bool); + void passwordToggled(bool); + void launchOffline(); + +private: + Ui::LoginDialog *ui; + bool blockToggles; + QPushButton *offlineButton; + bool isOnline_; + bool onlineForced; +}; diff --git a/gui/dialogs/LoginDialog.ui b/gui/dialogs/LoginDialog.ui new file mode 100644 index 00000000..d15679dd --- /dev/null +++ b/gui/dialogs/LoginDialog.ui @@ -0,0 +1,186 @@ + + + LoginDialog + + + + 0 + 0 + 496 + 168 + + + + Login + + + + + + <span style=" color:#ff0000;">Error</span> + + + Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse + + + + + + + + + + 48 + 48 + + + + + 48 + 48 + + + + + 1 + 1 + + + + + + + :/icons/instances/steve + + + true + + + + + + + true + + + + + + + Username: + + + + + + + Password: + + + + + + + QLineEdit::Password + + + Password + + + + + + + + + + + + 1 + 0 + + + + &Remember Username? + + + + + + + + 1 + 0 + + + + R&emember Password? + + + + + + + + 0 + 0 + + + + Forget + + + + + + + + + Qt::Horizontal + + + QDialogButtonBox::Cancel|QDialogButtonBox::Ok + + + + + + + + + + + + loginButtonBox + accepted() + LoginDialog + accept() + + + 248 + 254 + + + 157 + 274 + + + + + loginButtonBox + rejected() + LoginDialog + reject() + + + 316 + 260 + + + 286 + 274 + + + + + diff --git a/gui/dialogs/LwjglSelectDialog.cpp b/gui/dialogs/LwjglSelectDialog.cpp new file mode 100644 index 00000000..046a4e2e --- /dev/null +++ b/gui/dialogs/LwjglSelectDialog.cpp @@ -0,0 +1,72 @@ +/* Copyright 2013 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 "MultiMC.h" +#include "LwjglSelectDialog.h" +#include "ui_LwjglSelectDialog.h" +#include "gui/Platform.h" + +#include "logic/lists/LwjglVersionList.h" + +LWJGLSelectDialog::LWJGLSelectDialog(QWidget *parent) + : QDialog(parent), ui(new Ui::LWJGLSelectDialog) +{ + MultiMCPlatform::fixWM_CLASS(this); + ui->setupUi(this); + ui->labelStatus->setVisible(false); + auto lwjgllist = MMC->lwjgllist(); + ui->lwjglListView->setModel(lwjgllist.get()); + + connect(lwjgllist.get(), SIGNAL(loadingStateUpdated(bool)), + SLOT(loadingStateUpdated(bool))); + connect(lwjgllist.get(), SIGNAL(loadListFailed(QString)), SLOT(loadingFailed(QString))); + loadingStateUpdated(lwjgllist->isLoading()); +} + +LWJGLSelectDialog::~LWJGLSelectDialog() +{ + delete ui; +} + +QString LWJGLSelectDialog::selectedVersion() const +{ + return MMC->lwjgllist() + ->data(ui->lwjglListView->selectionModel()->currentIndex(), Qt::DisplayRole) + .toString(); +} + +void LWJGLSelectDialog::on_refreshButton_clicked() +{ + if (!MMC->lwjgllist()->isLoading()) + MMC->lwjgllist()->loadList(); +} + +void LWJGLSelectDialog::loadingStateUpdated(bool loading) +{ + setEnabled(!loading); + if (loading) + { + ui->labelStatus->setText(tr("Loading LWJGL version list...")); + ui->labelStatus->setStyleSheet("QLabel { color: black; }"); + } + ui->labelStatus->setVisible(loading); +} + +void LWJGLSelectDialog::loadingFailed(QString error) +{ + ui->labelStatus->setText(error); + ui->labelStatus->setStyleSheet("QLabel { color: red; }"); + ui->labelStatus->setVisible(true); +} diff --git a/gui/dialogs/LwjglSelectDialog.h b/gui/dialogs/LwjglSelectDialog.h new file mode 100644 index 00000000..2724cbe8 --- /dev/null +++ b/gui/dialogs/LwjglSelectDialog.h @@ -0,0 +1,44 @@ +/* Copyright 2013 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 + +namespace Ui +{ +class LWJGLSelectDialog; +} + +class LWJGLSelectDialog : public QDialog +{ + Q_OBJECT + +public: + explicit LWJGLSelectDialog(QWidget *parent = 0); + ~LWJGLSelectDialog(); + + QString selectedVersion() const; + +private +slots: + void on_refreshButton_clicked(); + + void loadingStateUpdated(bool loading); + void loadingFailed(QString error); + +private: + Ui::LWJGLSelectDialog *ui; +}; diff --git a/gui/dialogs/LwjglSelectDialog.ui b/gui/dialogs/LwjglSelectDialog.ui new file mode 100644 index 00000000..c715cc07 --- /dev/null +++ b/gui/dialogs/LwjglSelectDialog.ui @@ -0,0 +1,85 @@ + + + LWJGLSelectDialog + + + + 0 + 0 + 400 + 300 + + + + Dialog + + + + + + Status label... + + + + + + + + + + + + &Refresh + + + + + + + Qt::Horizontal + + + QDialogButtonBox::Cancel|QDialogButtonBox::Ok + + + + + + + + + + + buttonBox + accepted() + LWJGLSelectDialog + accept() + + + 248 + 254 + + + 157 + 274 + + + + + buttonBox + rejected() + LWJGLSelectDialog + reject() + + + 316 + 260 + + + 286 + 274 + + + + + diff --git a/gui/dialogs/ModEditDialogCommon.cpp b/gui/dialogs/ModEditDialogCommon.cpp new file mode 100644 index 00000000..9a15d92d --- /dev/null +++ b/gui/dialogs/ModEditDialogCommon.cpp @@ -0,0 +1,57 @@ +/* Copyright 2013 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 "ModEditDialogCommon.h" +#include "CustomMessageBox.h" +#include +#include +#include +#include +bool lastfirst(QModelIndexList &list, int &first, int &last) +{ + if (!list.size()) + return false; + first = last = list[0].row(); + for (auto item : list) + { + int row = item.row(); + if (row < first) + first = row; + if (row > last) + last = row; + } + return true; +} + +void showWebsiteForMod(QWidget *parentDlg, Mod &m) +{ + QString url = m.homeurl(); + if (url.size()) + { + // catch the cases where the protocol is missing + if (!url.startsWith("http")) + { + url = "http://" + url; + } + QDesktopServices::openUrl(url); + } + else + { + CustomMessageBox::selectable( + parentDlg, parentDlg->tr("How sad!"), + parentDlg->tr("The mod author didn't provide a website link for this mod."), + QMessageBox::Warning); + } +} diff --git a/gui/dialogs/ModEditDialogCommon.h b/gui/dialogs/ModEditDialogCommon.h new file mode 100644 index 00000000..a226d5a9 --- /dev/null +++ b/gui/dialogs/ModEditDialogCommon.h @@ -0,0 +1,22 @@ +/* Copyright 2013 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 +#include + +bool lastfirst(QModelIndexList &list, int &first, int &last); + +void showWebsiteForMod(QWidget *parentDlg, Mod &m); \ No newline at end of file diff --git a/gui/dialogs/NewInstanceDialog.cpp b/gui/dialogs/NewInstanceDialog.cpp new file mode 100644 index 00000000..5b2cd086 --- /dev/null +++ b/gui/dialogs/NewInstanceDialog.cpp @@ -0,0 +1,125 @@ +/* Copyright 2013 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 "MultiMC.h" +#include "NewInstanceDialog.h" +#include "ui_NewInstanceDialog.h" + +#include "logic/InstanceFactory.h" +#include "logic/BaseVersion.h" +#include "logic/lists/IconList.h" +#include "logic/lists/MinecraftVersionList.h" +#include "logic/tasks/Task.h" + +#include "gui/Platform.h" +#include "VersionSelectDialog.h" +#include "ProgressDialog.h" +#include "IconPickerDialog.h" + +#include +#include + +NewInstanceDialog::NewInstanceDialog(QWidget *parent) + : QDialog(parent), ui(new Ui::NewInstanceDialog) +{ + MultiMCPlatform::fixWM_CLASS(this); + ui->setupUi(this); + resize(minimumSizeHint()); + layout()->setSizeConstraint(QLayout::SetFixedSize); + /* + if (!MinecraftVersionList::getMainList().isLoaded()) + { + TaskDialog *taskDlg = new TaskDialog(this); + Task *loadTask = MinecraftVersionList::getMainList().getLoadTask(); + loadTask->setParent(taskDlg); + taskDlg->exec(loadTask); + } + */ + setSelectedVersion(MMC->minecraftlist()->getLatestStable()); + InstIconKey = "infinity"; + ui->iconButton->setIcon(MMC->icons()->getIcon(InstIconKey)); +} + +NewInstanceDialog::~NewInstanceDialog() +{ + delete ui; +} + +void NewInstanceDialog::updateDialogState() +{ + ui->buttonBox->button(QDialogButtonBox::Ok) + ->setEnabled(!instName().isEmpty() && m_selectedVersion); +} + +void NewInstanceDialog::setSelectedVersion(BaseVersionPtr version) +{ + m_selectedVersion = version; + + if (m_selectedVersion) + { + ui->versionTextBox->setText(version->name()); + } + else + { + ui->versionTextBox->setText(""); + } + + updateDialogState(); +} + +QString NewInstanceDialog::instName() const +{ + return ui->instNameTextBox->text(); +} + +QString NewInstanceDialog::iconKey() const +{ + return InstIconKey; +} + +BaseVersionPtr NewInstanceDialog::selectedVersion() const +{ + return m_selectedVersion; +} + +void NewInstanceDialog::on_btnChangeVersion_clicked() +{ + VersionSelectDialog vselect(MMC->minecraftlist().get(), tr("Change Minecraft version"), + this); + vselect.exec(); + if (vselect.result() == QDialog::Accepted) + { + BaseVersionPtr version = vselect.selectedVersion(); + if (version) + setSelectedVersion(version); + } +} + +void NewInstanceDialog::on_iconButton_clicked() +{ + IconPickerDialog dlg(this); + dlg.exec(InstIconKey); + + if (dlg.result() == QDialog::Accepted) + { + InstIconKey = dlg.selectedIconKey; + ui->iconButton->setIcon(MMC->icons()->getIcon(InstIconKey)); + } +} + +void NewInstanceDialog::on_instNameTextBox_textChanged(const QString &arg1) +{ + updateDialogState(); +} diff --git a/gui/dialogs/NewInstanceDialog.h b/gui/dialogs/NewInstanceDialog.h new file mode 100644 index 00000000..4357c28d --- /dev/null +++ b/gui/dialogs/NewInstanceDialog.h @@ -0,0 +1,55 @@ +/* Copyright 2013 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 +#include "logic/BaseVersion.h" + +namespace Ui +{ +class NewInstanceDialog; +} + +class NewInstanceDialog : public QDialog +{ + Q_OBJECT + +public: + explicit NewInstanceDialog(QWidget *parent = 0); + ~NewInstanceDialog(); + + void updateDialogState(); + + void setSelectedVersion(BaseVersionPtr version); + + void loadVersionList(); + + QString instName() const; + QString iconKey() const; + BaseVersionPtr selectedVersion() const; + +private +slots: + void on_btnChangeVersion_clicked(); + void on_iconButton_clicked(); + void on_instNameTextBox_textChanged(const QString &arg1); + +private: + Ui::NewInstanceDialog *ui; + + BaseVersionPtr m_selectedVersion; + QString InstIconKey; +}; diff --git a/gui/dialogs/NewInstanceDialog.ui b/gui/dialogs/NewInstanceDialog.ui new file mode 100644 index 00000000..b4b8723e --- /dev/null +++ b/gui/dialogs/NewInstanceDialog.ui @@ -0,0 +1,179 @@ + + + NewInstanceDialog + + + Qt::ApplicationModal + + + + 0 + 0 + 220 + 234 + + + + New Instance + + + + :/icons/toolbar/new:/icons/toolbar/new + + + true + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + :/icons/instances/infinity:/icons/instances/infinity + + + + 80 + 80 + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + Name + + + + + + + Qt::Horizontal + + + + + + + + + Version: + + + + + + + true + + + + + + + ... + + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + Qt::Horizontal + + + + + + + Qt::Horizontal + + + QDialogButtonBox::Cancel|QDialogButtonBox::Ok + + + + + + + + + + + buttonBox + accepted() + NewInstanceDialog + accept() + + + 248 + 254 + + + 157 + 274 + + + + + buttonBox + rejected() + NewInstanceDialog + reject() + + + 316 + 260 + + + 286 + 274 + + + + + diff --git a/gui/dialogs/OneSixModEditDialog.cpp b/gui/dialogs/OneSixModEditDialog.cpp new file mode 100644 index 00000000..dea1b86b --- /dev/null +++ b/gui/dialogs/OneSixModEditDialog.cpp @@ -0,0 +1,322 @@ +/* Copyright 2013 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 "MultiMC.h" + +#include +#include +#include +#include +#include +#include +#include + +#include "OneSixModEditDialog.h" +#include "ModEditDialogCommon.h" +#include "ui_OneSixModEditDialog.h" + +#include "gui/Platform.h" +#include "gui/dialogs/CustomMessageBox.h" +#include "gui/dialogs/VersionSelectDialog.h" + +#include "gui/dialogs/ProgressDialog.h" + +#include "logic/ModList.h" +#include "logic/OneSixVersion.h" +#include "logic/EnabledItemFilter.h" +#include "logic/lists/ForgeVersionList.h" +#include "logic/ForgeInstaller.h" + +OneSixModEditDialog::OneSixModEditDialog(OneSixInstance *inst, QWidget *parent) + : m_inst(inst), QDialog(parent), ui(new Ui::OneSixModEditDialog) +{ + MultiMCPlatform::fixWM_CLASS(this); + ui->setupUi(this); + // libraries! + + m_version = m_inst->getFullVersion(); + if (m_version) + { + main_model = new EnabledItemFilter(this); + main_model->setActive(true); + main_model->setSourceModel(m_version.get()); + ui->libraryTreeView->setModel(main_model); + ui->libraryTreeView->installEventFilter(this); + ui->mainClassEdit->setText(m_version->mainClass); + updateVersionControls(); + } + else + { + disableVersionControls(); + } + // Loader mods + { + ensureFolderPathExists(m_inst->loaderModsDir()); + m_mods = m_inst->loaderModList(); + ui->loaderModTreeView->setModel(m_mods.get()); + ui->loaderModTreeView->installEventFilter(this); + m_mods->startWatching(); + auto smodel = ui->loaderModTreeView->selectionModel(); + connect(smodel, SIGNAL(currentChanged(QModelIndex, QModelIndex)), + SLOT(loaderCurrent(QModelIndex, QModelIndex))); + } + // resource packs + { + ensureFolderPathExists(m_inst->resourcePacksDir()); + m_resourcepacks = m_inst->resourcePackList(); + ui->resPackTreeView->setModel(m_resourcepacks.get()); + ui->resPackTreeView->installEventFilter(this); + m_resourcepacks->startWatching(); + } +} + +OneSixModEditDialog::~OneSixModEditDialog() +{ + m_mods->stopWatching(); + m_resourcepacks->stopWatching(); + delete ui; +} + +void OneSixModEditDialog::updateVersionControls() +{ + bool customVersion = m_inst->versionIsCustom(); + ui->customizeBtn->setEnabled(!customVersion); + ui->revertBtn->setEnabled(customVersion); + ui->forgeBtn->setEnabled(true); +} + +void OneSixModEditDialog::disableVersionControls() +{ + ui->customizeBtn->setEnabled(false); + ui->revertBtn->setEnabled(false); + ui->forgeBtn->setEnabled(false); +} + +void OneSixModEditDialog::on_customizeBtn_clicked() +{ + if (m_inst->customizeVersion()) + { + m_version = m_inst->getFullVersion(); + main_model->setSourceModel(m_version.get()); + updateVersionControls(); + } +} + +void OneSixModEditDialog::on_revertBtn_clicked() +{ + auto response = CustomMessageBox::selectable( + this, tr("Revert?"), tr("Do you want to revert the " + "version of this instance to its original configuration?"), + QMessageBox::Question, QMessageBox::Yes | QMessageBox::No)->exec(); + if (response == QMessageBox::Yes) + { + if (m_inst->revertCustomVersion()) + { + m_version = m_inst->getFullVersion(); + main_model->setSourceModel(m_version.get()); + updateVersionControls(); + } + } +} + +void OneSixModEditDialog::on_forgeBtn_clicked() +{ + VersionSelectDialog vselect(MMC->forgelist().get(), tr("Select Forge version"), this); + vselect.setFilter(1, m_inst->currentVersionId()); + if (vselect.exec() && vselect.selectedVersion()) + { + if (m_inst->versionIsCustom()) + { + auto reply = QMessageBox::question( + this, tr("Revert?"), + tr("This will revert any " + "changes you did to the version up to this point. Is that " + "OK?"), + QMessageBox::Yes | QMessageBox::No); + if (reply == QMessageBox::Yes) + { + m_inst->revertCustomVersion(); + m_inst->customizeVersion(); + { + m_version = m_inst->getFullVersion(); + main_model->setSourceModel(m_version.get()); + updateVersionControls(); + } + } + else + return; + } + else + { + m_inst->customizeVersion(); + m_version = m_inst->getFullVersion(); + main_model->setSourceModel(m_version.get()); + updateVersionControls(); + } + ForgeVersionPtr forgeVersion = + std::dynamic_pointer_cast(vselect.selectedVersion()); + if (!forgeVersion) + return; + auto entry = MMC->metacache()->resolveEntry("minecraftforge", forgeVersion->filename); + if (entry->stale) + { + NetJob *fjob = new NetJob("Forge download"); + fjob->addNetAction(CacheDownload::make(forgeVersion->installer_url, entry)); + ProgressDialog dlg(this); + dlg.exec(fjob); + if (dlg.result() == QDialog::Accepted) + { + // install + QString forgePath = entry->getFullPath(); + ForgeInstaller forge(forgePath, forgeVersion->universal_url); + if (!forge.apply(m_version)) + { + // failure notice + } + } + else + { + // failed to download forge :/ + } + } + else + { + // install + QString forgePath = entry->getFullPath(); + ForgeInstaller forge(forgePath, forgeVersion->universal_url); + if (!forge.apply(m_version)) + { + // failure notice + } + } + } +} + +bool OneSixModEditDialog::loaderListFilter(QKeyEvent *keyEvent) +{ + switch (keyEvent->key()) + { + case Qt::Key_Delete: + on_rmModBtn_clicked(); + return true; + case Qt::Key_Plus: + on_addModBtn_clicked(); + return true; + default: + break; + } + return QDialog::eventFilter(ui->loaderModTreeView, keyEvent); +} + +bool OneSixModEditDialog::resourcePackListFilter(QKeyEvent *keyEvent) +{ + switch (keyEvent->key()) + { + case Qt::Key_Delete: + on_rmResPackBtn_clicked(); + return true; + case Qt::Key_Plus: + on_addResPackBtn_clicked(); + return true; + default: + break; + } + return QDialog::eventFilter(ui->resPackTreeView, keyEvent); +} + +bool OneSixModEditDialog::eventFilter(QObject *obj, QEvent *ev) +{ + if (ev->type() != QEvent::KeyPress) + { + return QDialog::eventFilter(obj, ev); + } + QKeyEvent *keyEvent = static_cast(ev); + if (obj == ui->loaderModTreeView) + return loaderListFilter(keyEvent); + if (obj == ui->resPackTreeView) + return resourcePackListFilter(keyEvent); + return QDialog::eventFilter(obj, ev); +} + +void OneSixModEditDialog::on_buttonBox_rejected() +{ + close(); +} + +void OneSixModEditDialog::on_addModBtn_clicked() +{ + QStringList fileNames = QFileDialog::getOpenFileNames( + this, QApplication::translate("LegacyModEditDialog", "Select Loader Mods")); + for (auto filename : fileNames) + { + m_mods->stopWatching(); + m_mods->installMod(QFileInfo(filename)); + m_mods->startWatching(); + } +} +void OneSixModEditDialog::on_rmModBtn_clicked() +{ + int first, last; + auto list = ui->loaderModTreeView->selectionModel()->selectedRows(); + + if (!lastfirst(list, first, last)) + return; + m_mods->stopWatching(); + m_mods->deleteMods(first, last); + m_mods->startWatching(); +} +void OneSixModEditDialog::on_viewModBtn_clicked() +{ + openDirInDefaultProgram(m_inst->loaderModsDir(), true); +} + +void OneSixModEditDialog::on_addResPackBtn_clicked() +{ + QStringList fileNames = QFileDialog::getOpenFileNames( + this, QApplication::translate("LegacyModEditDialog", "Select Resource Packs")); + for (auto filename : fileNames) + { + m_resourcepacks->stopWatching(); + m_resourcepacks->installMod(QFileInfo(filename)); + m_resourcepacks->startWatching(); + } +} +void OneSixModEditDialog::on_rmResPackBtn_clicked() +{ + int first, last; + auto list = ui->resPackTreeView->selectionModel()->selectedRows(); + + if (!lastfirst(list, first, last)) + return; + m_resourcepacks->stopWatching(); + m_resourcepacks->deleteMods(first, last); + m_resourcepacks->startWatching(); +} +void OneSixModEditDialog::on_viewResPackBtn_clicked() +{ + openDirInDefaultProgram(m_inst->resourcePacksDir(), true); +} + +void OneSixModEditDialog::loaderCurrent(QModelIndex current, QModelIndex previous) +{ + if (!current.isValid()) + { + ui->frame->clear(); + return; + } + int row = current.row(); + Mod &m = m_mods->operator[](row); + ui->frame->updateWithMod(m); +} diff --git a/gui/dialogs/OneSixModEditDialog.h b/gui/dialogs/OneSixModEditDialog.h new file mode 100644 index 00000000..5376e526 --- /dev/null +++ b/gui/dialogs/OneSixModEditDialog.h @@ -0,0 +1,67 @@ +/* Copyright 2013 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 + +#include + +class EnabledItemFilter; +namespace Ui +{ +class OneSixModEditDialog; +} + +class OneSixModEditDialog : public QDialog +{ + Q_OBJECT + +public: + explicit OneSixModEditDialog(OneSixInstance *inst, QWidget *parent = 0); + virtual ~OneSixModEditDialog(); + +private +slots: + void on_addModBtn_clicked(); + void on_rmModBtn_clicked(); + void on_viewModBtn_clicked(); + + void on_addResPackBtn_clicked(); + void on_rmResPackBtn_clicked(); + void on_viewResPackBtn_clicked(); + // Questionable: SettingsDialog doesn't need this for some reason? + void on_buttonBox_rejected(); + void on_forgeBtn_clicked(); + void on_customizeBtn_clicked(); + void on_revertBtn_clicked(); + void updateVersionControls(); + void disableVersionControls(); + +protected: + bool eventFilter(QObject *obj, QEvent *ev); + bool loaderListFilter(QKeyEvent *ev); + bool resourcePackListFilter(QKeyEvent *ev); + +private: + Ui::OneSixModEditDialog *ui; + std::shared_ptr m_version; + std::shared_ptr m_mods; + std::shared_ptr m_resourcepacks; + EnabledItemFilter *main_model; + OneSixInstance *m_inst; +public +slots: + void loaderCurrent(QModelIndex current, QModelIndex previous); +}; diff --git a/gui/dialogs/OneSixModEditDialog.ui b/gui/dialogs/OneSixModEditDialog.ui new file mode 100644 index 00000000..8f301438 --- /dev/null +++ b/gui/dialogs/OneSixModEditDialog.ui @@ -0,0 +1,319 @@ + + + OneSixModEditDialog + + + + 0 + 0 + 555 + 463 + + + + Dialog + + + + + + true + + + + 0 + 0 + + + + 1 + + + + Version + + + + + + + + Qt::ScrollBarAlwaysOn + + + Qt::ScrollBarAlwaysOff + + + + + + + + + Main Class: + + + + + + + false + + + + + + + + + + + + + Replace any current custom version with Minecraft Forge + + + Install Forge + + + + + + + Create an customized copy of the base version + + + Customize + + + + + + + false + + + Revert to original base version + + + Revert + + + + + + + QFrame::Sunken + + + Qt::Horizontal + + + + + + + false + + + Add new libraries + + + &Add + + + + + + + false + + + Remove selected libraries + + + &Remove + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + + + Loader Mods + + + + + + + + + + + 0 + 0 + + + + true + + + QAbstractItemView::DropOnly + + + + + + + + + + + &Add + + + + + + + &Remove + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + &View Folder + + + + + + + + + + + + 0 + 0 + + + + + + + + + Resource Packs + + + + + + true + + + QAbstractItemView::DropOnly + + + + + + + + + &Add + + + + + + + &Remove + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + &View Folder + + + + + + + + + + + + + false + + + QDialogButtonBox::Close + + + + + + + + ModListView + QTreeView +
gui/widgets/ModListView.h
+
+ + MCModInfoFrame + QFrame +
gui/widgets/MCModInfoFrame.h
+ 1 +
+
+ + +
diff --git a/gui/dialogs/ProgressDialog.cpp b/gui/dialogs/ProgressDialog.cpp new file mode 100644 index 00000000..ca433dab --- /dev/null +++ b/gui/dialogs/ProgressDialog.cpp @@ -0,0 +1,107 @@ +/* Copyright 2013 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 "ProgressDialog.h" +#include "ui_ProgressDialog.h" + +#include + +#include "logic/tasks/Task.h" +#include "gui/Platform.h" + +ProgressDialog::ProgressDialog(QWidget *parent) : QDialog(parent), ui(new Ui::ProgressDialog) +{ + MultiMCPlatform::fixWM_CLASS(this); + ui->setupUi(this); + updateSize(); + + changeProgress(0, 100); +} + +ProgressDialog::~ProgressDialog() +{ + delete ui; +} + +void ProgressDialog::updateSize() +{ + resize(QSize(480, minimumSizeHint().height())); +} + +int ProgressDialog::exec(ProgressProvider *task) +{ + this->task = task; + + // Connect signals. + connect(task, SIGNAL(started()), SLOT(onTaskStarted())); + connect(task, SIGNAL(failed(QString)), SLOT(onTaskFailed(QString))); + connect(task, SIGNAL(succeeded()), SLOT(onTaskSucceeded())); + connect(task, SIGNAL(status(QString)), SLOT(changeStatus(const QString &))); + connect(task, SIGNAL(progress(qint64, qint64)), SLOT(changeProgress(qint64, qint64))); + + // this makes sure that the task is started after the dialog is created + QMetaObject::invokeMethod(task, "start", Qt::QueuedConnection); + return QDialog::exec(); +} + +ProgressProvider *ProgressDialog::getTask() +{ + return task; +} + +void ProgressDialog::onTaskStarted() +{ +} + +void ProgressDialog::onTaskFailed(QString failure) +{ + reject(); +} + +void ProgressDialog::onTaskSucceeded() +{ + accept(); +} + +void ProgressDialog::changeStatus(const QString &status) +{ + ui->statusLabel->setText(status); + updateSize(); +} + +void ProgressDialog::changeProgress(qint64 current, qint64 total) +{ + ui->taskProgressBar->setMaximum(total); + ui->taskProgressBar->setValue(current); +} + +void ProgressDialog::keyPressEvent(QKeyEvent *e) +{ + if (e->key() == Qt::Key_Escape) + return; + QDialog::keyPressEvent(e); +} + +void ProgressDialog::closeEvent(QCloseEvent *e) +{ + if (task && task->isRunning()) + { + e->ignore(); + } + else + { + QDialog::closeEvent(e); + } +} diff --git a/gui/dialogs/ProgressDialog.h b/gui/dialogs/ProgressDialog.h new file mode 100644 index 00000000..0029d3ec --- /dev/null +++ b/gui/dialogs/ProgressDialog.h @@ -0,0 +1,60 @@ +/* Copyright 2013 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 + +class ProgressProvider; + +namespace Ui +{ +class ProgressDialog; +} + +class ProgressDialog : public QDialog +{ + Q_OBJECT + +public: + explicit ProgressDialog(QWidget *parent = 0); + ~ProgressDialog(); + + void updateSize(); + + int exec(ProgressProvider *task); + + ProgressProvider *getTask(); + +public +slots: + void onTaskStarted(); + void onTaskFailed(QString failure); + void onTaskSucceeded(); + + void changeStatus(const QString &status); + void changeProgress(qint64 current, qint64 total); + +signals: + +protected: + virtual void keyPressEvent(QKeyEvent *e); + virtual void closeEvent(QCloseEvent *e); + +private: + Ui::ProgressDialog *ui; + + ProgressProvider *task; +}; diff --git a/gui/dialogs/ProgressDialog.ui b/gui/dialogs/ProgressDialog.ui new file mode 100644 index 00000000..a56d2a92 --- /dev/null +++ b/gui/dialogs/ProgressDialog.ui @@ -0,0 +1,53 @@ + + + ProgressDialog + + + + 0 + 0 + 400 + 68 + + + + + 400 + 0 + + + + + 600 + 16777215 + + + + Please wait... + + + + + + Task Status... + + + true + + + + + + + 24 + + + false + + + + + + + + diff --git a/gui/dialogs/SettingsDialog.cpp b/gui/dialogs/SettingsDialog.cpp new file mode 100644 index 00000000..e4f22d83 --- /dev/null +++ b/gui/dialogs/SettingsDialog.cpp @@ -0,0 +1,260 @@ +/* Copyright 2013 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 "MultiMC.h" + +#include "gui/dialogs/SettingsDialog.h" +#include "ui_SettingsDialog.h" + +#include "gui/Platform.h" +#include "gui/dialogs/VersionSelectDialog.h" +#include "gui/dialogs/CustomMessageBox.h" + +#include "logic/JavaUtils.h" +#include "logic/NagUtils.h" +#include "logic/lists/JavaVersionList.h" + +#include +#include +#include +#include +#include + +SettingsDialog::SettingsDialog(QWidget *parent) : QDialog(parent), ui(new Ui::SettingsDialog) +{ + MultiMCPlatform::fixWM_CLASS(this); + ui->setupUi(this); + ui->sortingModeGroup->setId(ui->sortByNameBtn, Sort_Name); + ui->sortingModeGroup->setId(ui->sortLastLaunchedBtn, Sort_LastLaunch); + + loadSettings(MMC->settings().get()); + updateCheckboxStuff(); +} + +SettingsDialog::~SettingsDialog() +{ + delete ui; +} +void SettingsDialog::showEvent(QShowEvent *ev) +{ + QDialog::showEvent(ev); + adjustSize(); +} + +void SettingsDialog::updateCheckboxStuff() +{ + ui->windowWidthSpinBox->setEnabled(!ui->maximizedCheckBox->isChecked()); + ui->windowHeightSpinBox->setEnabled(!ui->maximizedCheckBox->isChecked()); +} + +void SettingsDialog::on_instDirBrowseBtn_clicked() +{ + QString raw_dir = QFileDialog::getExistingDirectory(this, tr("Instance Directory"), + ui->instDirTextBox->text()); + QString cooked_dir = NormalizePath(raw_dir); + + // do not allow current dir - it's dirty. Do not allow dirs that don't exist + if (!cooked_dir.isEmpty() && QDir(cooked_dir).exists()) + { + ui->instDirTextBox->setText(cooked_dir); + } +} + +void SettingsDialog::on_modsDirBrowseBtn_clicked() +{ + QString raw_dir = QFileDialog::getExistingDirectory(this, tr("Mods Directory"), + ui->modsDirTextBox->text()); + QString cooked_dir = NormalizePath(raw_dir); + + // do not allow current dir - it's dirty. Do not allow dirs that don't exist + if (!cooked_dir.isEmpty() && QDir(cooked_dir).exists()) + { + ui->modsDirTextBox->setText(cooked_dir); + } +} + +void SettingsDialog::on_lwjglDirBrowseBtn_clicked() +{ + QString raw_dir = QFileDialog::getExistingDirectory(this, tr("LWJGL Directory"), + ui->lwjglDirTextBox->text()); + QString cooked_dir = NormalizePath(raw_dir); + + // do not allow current dir - it's dirty. Do not allow dirs that don't exist + if (!cooked_dir.isEmpty() && QDir(cooked_dir).exists()) + { + ui->lwjglDirTextBox->setText(cooked_dir); + } +} + +void SettingsDialog::on_compatModeCheckBox_clicked(bool checked) +{ + Q_UNUSED(checked); + updateCheckboxStuff(); +} + +void SettingsDialog::on_maximizedCheckBox_clicked(bool checked) +{ + Q_UNUSED(checked); + updateCheckboxStuff(); +} + +void SettingsDialog::on_buttonBox_accepted() +{ + applySettings(MMC->settings().get()); +} + +void SettingsDialog::applySettings(SettingsObject *s) +{ + // Special cases + + // Warn about dev builds. + if (!ui->devBuildsCheckBox->isChecked()) + { + s->set("UseDevBuilds", false); + } + else if (!s->get("UseDevBuilds").toBool()) + { + auto response = CustomMessageBox::selectable( + this, tr("Development builds"), + tr("Development builds contain experimental features " + "and may be unstable. Are you sure you want to enable them?"), + QMessageBox::Question, QMessageBox::Yes | QMessageBox::No)->exec(); + if (response == QMessageBox::Yes) + { + s->set("UseDevBuilds", true); + } + } + + // Updates + s->set("AutoUpdate", ui->autoUpdateCheckBox->isChecked()); + + // Folders + // TODO: Offer to move instances to new instance folder. + s->set("InstanceDir", ui->instDirTextBox->text()); + s->set("CentralModsDir", ui->modsDirTextBox->text()); + s->set("LWJGLDir", ui->lwjglDirTextBox->text()); + + // Console + s->set("ShowConsole", ui->showConsoleCheck->isChecked()); + s->set("AutoCloseConsole", ui->autoCloseConsoleCheck->isChecked()); + + // Window Size + s->set("LaunchMaximized", ui->maximizedCheckBox->isChecked()); + s->set("MinecraftWinWidth", ui->windowWidthSpinBox->value()); + s->set("MinecraftWinHeight", ui->windowHeightSpinBox->value()); + + // Auto Login + s->set("AutoLogin", ui->autoLoginCheckBox->isChecked()); + + // Memory + s->set("MinMemAlloc", ui->minMemSpinBox->value()); + s->set("MaxMemAlloc", ui->maxMemSpinBox->value()); + s->set("PermGen", ui->permGenSpinBox->value()); + + // Java Settings + s->set("JavaPath", ui->javaPathTextBox->text()); + s->set("JvmArgs", ui->jvmArgsTextBox->text()); + NagUtils::checkJVMArgs(s->get("JvmArgs").toString(), this->parentWidget()); + + // Custom Commands + s->set("PreLaunchCommand", ui->preLaunchCmdTextBox->text()); + s->set("PostExitCommand", ui->postExitCmdTextBox->text()); + + auto sortMode = (InstSortMode)ui->sortingModeGroup->checkedId(); + switch (sortMode) + { + case Sort_LastLaunch: + s->set("InstSortMode", "LastLaunch"); + break; + case Sort_Name: + default: + s->set("InstSortMode", "Name"); + break; + } + + s->set("PostExitCommand", ui->postExitCmdTextBox->text()); +} + +void SettingsDialog::loadSettings(SettingsObject *s) +{ + // Updates + ui->autoUpdateCheckBox->setChecked(s->get("AutoUpdate").toBool()); + ui->devBuildsCheckBox->setChecked(s->get("UseDevBuilds").toBool()); + + // Folders + ui->instDirTextBox->setText(s->get("InstanceDir").toString()); + ui->modsDirTextBox->setText(s->get("CentralModsDir").toString()); + ui->lwjglDirTextBox->setText(s->get("LWJGLDir").toString()); + + // Console + ui->showConsoleCheck->setChecked(s->get("ShowConsole").toBool()); + ui->autoCloseConsoleCheck->setChecked(s->get("AutoCloseConsole").toBool()); + + // Window Size + ui->maximizedCheckBox->setChecked(s->get("LaunchMaximized").toBool()); + ui->windowWidthSpinBox->setValue(s->get("MinecraftWinWidth").toInt()); + ui->windowHeightSpinBox->setValue(s->get("MinecraftWinHeight").toInt()); + + // Auto Login + ui->autoLoginCheckBox->setChecked(s->get("AutoLogin").toBool()); + + // Memory + ui->minMemSpinBox->setValue(s->get("MinMemAlloc").toInt()); + ui->maxMemSpinBox->setValue(s->get("MaxMemAlloc").toInt()); + ui->permGenSpinBox->setValue(s->get("PermGen").toInt()); + + QString sortMode = s->get("InstSortMode").toString(); + + if (sortMode == "LastLaunch") + { + ui->sortLastLaunchedBtn->setChecked(true); + } + else + { + ui->sortByNameBtn->setChecked(true); + } + + // Java Settings + ui->javaPathTextBox->setText(s->get("JavaPath").toString()); + ui->jvmArgsTextBox->setText(s->get("JvmArgs").toString()); + + // Custom Commands + ui->preLaunchCmdTextBox->setText(s->get("PreLaunchCommand").toString()); + ui->postExitCmdTextBox->setText(s->get("PostExitCommand").toString()); +} + +void SettingsDialog::on_pushButton_clicked() +{ + JavaVersionPtr java; + + VersionSelectDialog vselect(MMC->javalist().get(), tr("Select a Java version"), this, true); + vselect.setResizeOn(2); + vselect.exec(); + + if (vselect.result() == QDialog::Accepted && vselect.selectedVersion()) + { + java = std::dynamic_pointer_cast(vselect.selectedVersion()); + ui->javaPathTextBox->setText(java->path); + } +} + +void SettingsDialog::on_btnBrowse_clicked() +{ + QString dir = QFileDialog::getOpenFileName(this, tr("Find Java executable")); + if (!dir.isNull()) + { + ui->javaPathTextBox->setText(dir); + } +} diff --git a/gui/dialogs/SettingsDialog.h b/gui/dialogs/SettingsDialog.h new file mode 100644 index 00000000..e24047c3 --- /dev/null +++ b/gui/dialogs/SettingsDialog.h @@ -0,0 +1,63 @@ +/* Copyright 2013 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 + +class SettingsObject; + +namespace Ui +{ +class SettingsDialog; +} + +class SettingsDialog : public QDialog +{ + Q_OBJECT + +public: + explicit SettingsDialog(QWidget *parent = 0); + ~SettingsDialog(); + + void updateCheckboxStuff(); + + void applySettings(SettingsObject *s); + void loadSettings(SettingsObject *s); + +protected: + virtual void showEvent(QShowEvent *); + +private +slots: + void on_instDirBrowseBtn_clicked(); + + void on_modsDirBrowseBtn_clicked(); + + void on_lwjglDirBrowseBtn_clicked(); + + void on_compatModeCheckBox_clicked(bool checked); + + void on_maximizedCheckBox_clicked(bool checked); + + void on_buttonBox_accepted(); + + void on_pushButton_clicked(); + + void on_btnBrowse_clicked(); + +private: + Ui::SettingsDialog *ui; +}; diff --git a/gui/dialogs/SettingsDialog.ui b/gui/dialogs/SettingsDialog.ui new file mode 100644 index 00000000..6da9420e --- /dev/null +++ b/gui/dialogs/SettingsDialog.ui @@ -0,0 +1,569 @@ + + + SettingsDialog + + + + 0 + 0 + 502 + 599 + + + + + 0 + 0 + + + + Settings + + + + :/icons/toolbar/settings:/icons/toolbar/settings + + + true + + + + + + QTabWidget::Rounded + + + 0 + + + + General + + + + + + true + + + Sorting Mode + + + + + + By last launched + + + sortingModeGroup + + + + + + + By name + + + sortingModeGroup + + + + + + + + + + Update Settings + + + + + + Use development builds? + + + + + + + Check for updates when MultiMC starts? + + + + + + + + + + Folders + + + + + + Instances: + + + + + + + + + + ... + + + + + + + Mods: + + + + + + + + + + ... + + + + + + + LWJGL: + + + + + + + + + + ... + + + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + Minecraft + + + + + + Window Size + + + + + + Start Minecraft maximized? + + + + + + + + + Window height: + + + + + + + Window width: + + + + + + + 854 + + + 65536 + + + 1 + + + 854 + + + + + + + 480 + + + 65536 + + + 480 + + + + + + + + + + + + Console Settings + + + + + + Show console while the game is running? + + + + + + + Automatically close console when the game quits? + + + + + + + + + + Login automatically when an instance icon is double clicked? + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + Java + + + + + + Memory + + + + + + 512 + + + 65536 + + + 128 + + + 1024 + + + + + + + Minimum memory allocation: + + + + + + + Maximum memory allocation: + + + + + + + 256 + + + 65536 + + + 128 + + + 256 + + + + + + + PermGen: + + + + + + + 64 + + + 999999999 + + + 8 + + + 64 + + + + + + + + + + Java Settings + + + + + + + 0 + 0 + + + + Java path: + + + + + + + + 0 + 0 + + + + JVM arguments: + + + + + + + + 0 + 0 + + + + Browse... + + + + + + + + + + + 0 + 0 + + + + Auto-detect... + + + + + + + + + + + + + Custom Commands + + + + + + Post-exit command: + + + + + + + Pre-launch command: + + + + + + + + + + + + + + + + + 0 + 0 + + + + Pre-launch command runs before the instance launches and post-exit command runs after it exits. Both will be run in MultiMC's working directory with INST_ID, INST_DIR, and INST_NAME as environment variables. + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop + + + true + + + + + + + + + + + Qt::Horizontal + + + QDialogButtonBox::Cancel|QDialogButtonBox::Ok + + + + + + + settingsTabs + buttonBox + sortLastLaunchedBtn + sortByNameBtn + devBuildsCheckBox + autoUpdateCheckBox + instDirTextBox + modsDirTextBox + lwjglDirTextBox + instDirBrowseBtn + modsDirBrowseBtn + lwjglDirBrowseBtn + maximizedCheckBox + windowWidthSpinBox + windowHeightSpinBox + showConsoleCheck + autoCloseConsoleCheck + autoLoginCheckBox + minMemSpinBox + maxMemSpinBox + permGenSpinBox + javaPathTextBox + pushButton + btnBrowse + jvmArgsTextBox + preLaunchCmdTextBox + postExitCmdTextBox + + + + + + + buttonBox + accepted() + SettingsDialog + accept() + + + 257 + 410 + + + 157 + 274 + + + + + buttonBox + rejected() + SettingsDialog + reject() + + + 325 + 410 + + + 286 + 274 + + + + + + + + diff --git a/gui/dialogs/VersionSelectDialog.cpp b/gui/dialogs/VersionSelectDialog.cpp new file mode 100644 index 00000000..d6efe3c0 --- /dev/null +++ b/gui/dialogs/VersionSelectDialog.cpp @@ -0,0 +1,111 @@ +/* Copyright 2013 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 "VersionSelectDialog.h" +#include "ui_VersionSelectDialog.h" + +#include + +#include + +#include +#include "gui/Platform.h" + +#include +#include +#include + +VersionSelectDialog::VersionSelectDialog(BaseVersionList *vlist, QString title, QWidget *parent, + bool cancelable) + : QDialog(parent), ui(new Ui::VersionSelectDialog) +{ + MultiMCPlatform::fixWM_CLASS(this); + ui->setupUi(this); + setWindowModality(Qt::WindowModal); + setWindowTitle(title); + + m_vlist = vlist; + + m_proxyModel = new QSortFilterProxyModel(this); + m_proxyModel->setSourceModel(vlist); + + ui->listView->setModel(m_proxyModel); + ui->listView->header()->setSectionResizeMode(QHeaderView::ResizeToContents); + ui->listView->header()->setSectionResizeMode(resizeOnColumn, QHeaderView::Stretch); + + if (!cancelable) + { + ui->buttonBox->button(QDialogButtonBox::Cancel)->setEnabled(false); + } +} + +VersionSelectDialog::~VersionSelectDialog() +{ + delete ui; +} + +void VersionSelectDialog::setResizeOn(int column) +{ + ui->listView->header()->setSectionResizeMode(resizeOnColumn, QHeaderView::ResizeToContents); + resizeOnColumn = column; + ui->listView->header()->setSectionResizeMode(resizeOnColumn, QHeaderView::Stretch); +} + +int VersionSelectDialog::exec() +{ + QDialog::open(); + if (!m_vlist->isLoaded()) + loadList(); + return QDialog::exec(); +} + +void VersionSelectDialog::loadList() +{ + ProgressDialog *taskDlg = new ProgressDialog(this); + Task *loadTask = m_vlist->getLoadTask(); + loadTask->setParent(taskDlg); + taskDlg->exec(loadTask); +} + +BaseVersionPtr VersionSelectDialog::selectedVersion() const +{ + auto currentIndex = ui->listView->selectionModel()->currentIndex(); + auto variant = m_proxyModel->data(currentIndex, BaseVersionList::VersionPointerRole); + return variant.value(); +} + +void VersionSelectDialog::on_refreshButton_clicked() +{ + loadList(); +} + +void VersionSelectDialog::setFilter(int column, QString filter) +{ + m_proxyModel->setFilterKeyColumn(column); + m_proxyModel->setFilterFixedString(filter); + /* + QStringList filteredTypes; + if (!ui->filterSnapshotsCheckbox->isChecked()) + filteredTypes += "Snapshot"; + if (!ui->filterMCNostalgiaCheckbox->isChecked()) + filteredTypes += "Nostalgia"; + + QString regexStr = "^.*$"; + if (filteredTypes.length() > 0) + regexStr = QString("^((?!%1).)*$").arg(filteredTypes.join('|')); + + QLOG_DEBUG() << "Filter:" << regexStr; + */ +} diff --git a/gui/dialogs/VersionSelectDialog.h b/gui/dialogs/VersionSelectDialog.h new file mode 100644 index 00000000..e36341db --- /dev/null +++ b/gui/dialogs/VersionSelectDialog.h @@ -0,0 +1,61 @@ +/* Copyright 2013 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 +#include + +#include "logic/BaseVersion.h" + +class BaseVersionList; + +namespace Ui +{ +class VersionSelectDialog; +} + +class VersionSelectDialog : public QDialog +{ + Q_OBJECT + +public: + explicit VersionSelectDialog(BaseVersionList *vlist, QString title, QWidget *parent = 0, + bool cancelable = true); + ~VersionSelectDialog(); + + virtual int exec(); + + //! Starts a task that loads the list. + void loadList(); + + BaseVersionPtr selectedVersion() const; + + void setFilter(int column, QString filter); + void setResizeOn(int column); + +private +slots: + void on_refreshButton_clicked(); + +private: + Ui::VersionSelectDialog *ui; + + BaseVersionList *m_vlist; + + QSortFilterProxyModel *m_proxyModel; + + int resizeOnColumn = 0; +}; diff --git a/gui/dialogs/VersionSelectDialog.ui b/gui/dialogs/VersionSelectDialog.ui new file mode 100644 index 00000000..222f29cf --- /dev/null +++ b/gui/dialogs/VersionSelectDialog.ui @@ -0,0 +1,103 @@ + + + VersionSelectDialog + + + + 0 + 0 + 400 + 347 + + + + Dialog + + + + + + Qt::ScrollBarAlwaysOff + + + true + + + false + + + false + + + true + + + true + + + false + + + + + + + + + Reloads the version list. + + + &Refresh + + + + + + + Qt::Horizontal + + + QDialogButtonBox::Cancel|QDialogButtonBox::Ok + + + + + + + + + + + buttonBox + accepted() + VersionSelectDialog + accept() + + + 257 + 290 + + + 157 + 274 + + + + + buttonBox + rejected() + VersionSelectDialog + reject() + + + 325 + 290 + + + 286 + 274 + + + + + diff --git a/gui/instancedelegate.cpp b/gui/instancedelegate.cpp deleted file mode 100644 index 4c7a3a3a..00000000 --- a/gui/instancedelegate.cpp +++ /dev/null @@ -1,231 +0,0 @@ -#include "instancedelegate.h" -#include -#include -#include -#include -#include - -// Origin: Qt -static void viewItemTextLayout ( QTextLayout &textLayout, int lineWidth, qreal &height, qreal &widthUsed ) -{ - height = 0; - widthUsed = 0; - textLayout.beginLayout(); - QString str = textLayout.text(); - while ( true ) - { - QTextLine line = textLayout.createLine(); - if ( !line.isValid() ) - break; - if(line.textLength() == 0) - break; - line.setLineWidth ( lineWidth ); - line.setPosition ( QPointF ( 0, height ) ); - height += line.height(); - widthUsed = qMax ( widthUsed, line.naturalTextWidth() ); - } - textLayout.endLayout(); -} - -#define QFIXED_MAX (INT_MAX/256) - -ListViewDelegate::ListViewDelegate ( QObject* parent ) : QStyledItemDelegate ( parent ) -{ - -} - -void drawSelectionRect(QPainter *painter, const QStyleOptionViewItemV4 &option, const QRect &rect) -{ - if ((option.state & QStyle::State_Selected)) - painter->fillRect ( rect, option.palette.brush ( QPalette::Highlight ) ); - else - { - QColor backgroundColor = option.palette.color(QPalette::Background); - backgroundColor.setAlpha(160); - painter->fillRect ( rect, QBrush(backgroundColor) ); - } - -} - -void drawFocusRect(QPainter *painter, const QStyleOptionViewItemV4 &option, const QRect &rect) -{ - if (!(option.state & QStyle::State_HasFocus)) - return; - QStyleOptionFocusRect opt; - opt.direction = option.direction; - opt.fontMetrics = option.fontMetrics; - opt.palette = option.palette; - opt.rect = rect; - //opt.state = option.state | QStyle::State_KeyboardFocusChange | QStyle::State_Item; - auto col = option.state & QStyle::State_Selected ? QPalette::Highlight : QPalette::Base; - opt.backgroundColor = option.palette.color(col); - // Apparently some widget styles expect this hint to not be set - painter->setRenderHint(QPainter::Antialiasing, false); - - QStyle *style = option.widget ? option.widget->style() : QApplication::style(); - - style->drawPrimitive(QStyle::PE_FrameFocusRect, &opt, painter, option.widget); - - painter->setRenderHint(QPainter::Antialiasing); -} - -static QSize viewItemTextSize ( const QStyleOptionViewItemV4 *option ) -{ - QStyle *style = option->widget ? option->widget->style() : QApplication::style(); - QTextOption textOption; - textOption.setWrapMode ( QTextOption::WrapAtWordBoundaryOrAnywhere ); - QTextLayout textLayout; - textLayout.setTextOption ( textOption ); - textLayout.setFont ( option->font ); - textLayout.setText ( option->text ); - const int textMargin = style->pixelMetric ( QStyle::PM_FocusFrameHMargin, option, option->widget ) + 1; - QRect bounds ( 0,0,100 - 2*textMargin,600 ); - qreal height = 0, widthUsed = 0; - viewItemTextLayout ( textLayout, bounds.width(), height, widthUsed ); - const QSize size ( qCeil ( widthUsed ), qCeil ( height ) ); - return QSize ( size.width() + 2 * textMargin, size.height() ); -} - -void ListViewDelegate::paint ( QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index ) const -{ - QStyleOptionViewItemV4 opt = option; - initStyleOption ( &opt, index ); - painter->save(); - painter->setClipRect ( opt.rect ); - - opt.features |= QStyleOptionViewItem::WrapText; - opt.text = index.data().toString(); - opt.textElideMode = Qt::ElideRight; - opt.displayAlignment = Qt::AlignTop | Qt::AlignHCenter; - - QStyle *style = opt.widget ? opt.widget->style() : QApplication::style(); - - //const int iconSize = style->pixelMetric(QStyle::PM_IconViewIconSize); - const int iconSize = 48; - QRect iconbox = opt.rect; - const int textMargin = style->pixelMetric ( QStyle::PM_FocusFrameHMargin, 0, opt.widget ) + 1; - QRect textRect = opt.rect; - QRect textHighlightRect = textRect; - // clip the decoration on top, remove width padding - textRect.adjust ( textMargin,iconSize + textMargin + 5,-textMargin,0 ); - - textHighlightRect.adjust ( 0,iconSize + 5,0,0 ); - - // draw background - { - QSize textSize = viewItemTextSize ( &opt ); - QPalette::ColorGroup cg; - QStyleOptionViewItemV4 opt2(opt); - - if((opt.widget && opt.widget->isEnabled()) || (opt.state & QStyle::State_Enabled)) - { - if(! ( opt.state & QStyle::State_Active )) - cg = QPalette::Inactive; - else - cg = QPalette::Normal; - } - else - { - cg = QPalette::Disabled; - } - opt2.palette.setCurrentColorGroup(cg); - - // fill in background, if any - if ( opt.backgroundBrush.style() != Qt::NoBrush ) - { - QPointF oldBO = painter->brushOrigin(); - painter->setBrushOrigin ( opt.rect.topLeft() ); - painter->fillRect ( opt.rect, opt.backgroundBrush ); - painter->setBrushOrigin ( oldBO ); - } - - if ( opt.showDecorationSelected ) - { - drawSelectionRect(painter,opt2, opt.rect); - drawFocusRect(painter,opt2, opt.rect); - //painter->fillRect ( opt.rect, opt.palette.brush ( cg, QPalette::Highlight ) ); - } - else - { - - //if ( opt.state & QStyle::State_Selected ) - { - //QRect textRect = subElementRect ( QStyle::SE_ItemViewItemText, opt, opt.widget ); - //painter->fillRect ( textHighlightRect, opt.palette.brush ( cg, QPalette::Highlight ) ); - drawSelectionRect(painter,opt2, textHighlightRect); - drawFocusRect(painter,opt2, textHighlightRect); - } - } - } - - // draw the icon - { - QIcon::Mode mode = QIcon::Normal; - if ( ! ( opt.state & QStyle::State_Enabled ) ) - mode = QIcon::Disabled; - else if ( opt.state & QStyle::State_Selected ) - mode = QIcon::Selected; - QIcon::State state = opt.state & QStyle::State_Open ? QIcon::On : QIcon::Off; - - iconbox.setHeight ( iconSize ); - opt.icon.paint ( painter, iconbox, Qt::AlignCenter, mode, state ); - } - // set the text colors - QPalette::ColorGroup cg = opt.state & QStyle::State_Enabled ? QPalette::Normal : QPalette::Disabled; - if ( cg == QPalette::Normal && ! ( opt.state & QStyle::State_Active ) ) - cg = QPalette::Inactive; - if ( opt.state & QStyle::State_Selected ) - { - painter->setPen ( opt.palette.color ( cg, QPalette::HighlightedText ) ); - } - else - { - painter->setPen ( opt.palette.color ( cg, QPalette::Text ) ); - } - - // draw the text - QTextOption textOption; - textOption.setWrapMode ( QTextOption::WrapAtWordBoundaryOrAnywhere ); - textOption.setTextDirection ( opt.direction ); - textOption.setAlignment ( QStyle::visualAlignment ( opt.direction, opt.displayAlignment ) ); - QTextLayout textLayout; - textLayout.setTextOption ( textOption ); - textLayout.setFont ( opt.font ); - textLayout.setText ( opt.text ); - - qreal width, height; - viewItemTextLayout ( textLayout, textRect.width(), height, width ); - - const int lineCount = textLayout.lineCount(); - - const QRect layoutRect = QStyle::alignedRect ( opt.direction, opt.displayAlignment, QSize ( textRect.width(), int ( height ) ), textRect ); - const QPointF position = layoutRect.topLeft(); - for ( int i = 0; i < lineCount; ++i ) - { - const QTextLine line = textLayout.lineAt ( i ); - line.draw ( painter, position ); - } - - painter->restore(); -} - - -QSize ListViewDelegate::sizeHint ( const QStyleOptionViewItem & option, const QModelIndex & index ) const -{ - QStyleOptionViewItemV4 opt = option; - initStyleOption ( &opt, index ); - opt.features |= QStyleOptionViewItem::WrapText; - opt.text = index.data().toString(); - opt.textElideMode = Qt::ElideRight; - opt.displayAlignment = Qt::AlignTop | Qt::AlignHCenter; - - QStyle *style = opt.widget ? opt.widget->style() : QApplication::style(); - const int textMargin = style->pixelMetric ( QStyle::PM_FocusFrameHMargin, &option, opt.widget ) + 1; - int height = 48 + textMargin * 2 + 5; // TODO: turn constants into variables - QSize szz = viewItemTextSize ( &opt ); - height += szz.height(); - // FIXME: maybe the icon items could scale and keep proportions? - QSize sz ( 100,height ); - return sz; -} - diff --git a/gui/instancedelegate.h b/gui/instancedelegate.h deleted file mode 100644 index 56bc34ba..00000000 --- a/gui/instancedelegate.h +++ /dev/null @@ -1,12 +0,0 @@ -#pragma once - -#include - -class ListViewDelegate : public QStyledItemDelegate -{ -public: - explicit ListViewDelegate ( QObject* parent = 0 ); -protected: - void paint ( QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index ) const; - QSize sizeHint ( const QStyleOptionViewItem & option, const QModelIndex & index ) const; -}; diff --git a/gui/instancesettings.cpp b/gui/instancesettings.cpp deleted file mode 100644 index 73eb6627..00000000 --- a/gui/instancesettings.cpp +++ /dev/null @@ -1,189 +0,0 @@ -/* Copyright 2013 MultiMC Contributors - * - * Authors: Andrew Okin - * Peterix - * Orochimarufan - * - * 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 "instancesettings.h" -#include "ui_instancesettings.h" -#include "gui/platform.h" - -InstanceSettings::InstanceSettings( SettingsObject * obj, QWidget *parent) : - m_obj(obj), - QDialog(parent), - ui(new Ui::InstanceSettings) -{ - MultiMCPlatform::fixWM_CLASS(this); - ui->setupUi(this); - loadSettings(); -} - -InstanceSettings::~InstanceSettings() -{ - delete ui; -} - -void InstanceSettings::showEvent ( QShowEvent* ev ) -{ - QDialog::showEvent(ev); - adjustSize(); -} - -void InstanceSettings::on_customCommandsGroupBox_toggled(bool state) -{ - ui->labelCustomCmdsDescription->setEnabled(state); -} - -void InstanceSettings::on_buttonBox_accepted() -{ - applySettings(); - accept(); -} - -void InstanceSettings::on_buttonBox_rejected() -{ - reject(); -} - - -void InstanceSettings::applySettings() -{ - // Console - bool console = ui->consoleSettingsBox->isChecked(); - m_obj->set("OverrideConsole", console); - if(console) - { - m_obj->set("ShowConsole", ui->showConsoleCheck->isChecked()); - m_obj->set("AutoCloseConsole", ui->autoCloseConsoleCheck->isChecked()); - } - else - { - m_obj->reset("ShowConsole"); - m_obj->reset("AutoCloseConsole"); - } - - // Window Size - bool window = ui->windowSizeGroupBox->isChecked(); - m_obj->set("OverrideWindow", window); - if(window) - { - m_obj->set("LaunchMaximized", ui->maximizedCheckBox->isChecked()); - m_obj->set("MinecraftWinWidth", ui->windowWidthSpinBox->value()); - m_obj->set("MinecraftWinHeight", ui->windowHeightSpinBox->value()); - } - else - { - m_obj->reset("LaunchMaximized"); - m_obj->reset("MinecraftWinWidth"); - m_obj->reset("MinecraftWinHeight"); - } - - - // Auto Login - bool login = ui->accountSettingsGroupBox->isChecked(); - m_obj->set("OverrideLogin", login); - if(login) - { - m_obj->set("AutoLogin", ui->autoLoginChecBox->isChecked()); - } - else - { - m_obj->reset("AutoLogin"); - } - - - // Memory - bool memory = ui->memoryGroupBox->isChecked(); - m_obj->set("OverrideMemory", memory); - if(memory) - { - m_obj->set("MinMemAlloc", ui->minMemSpinBox->value()); - m_obj->set("MaxMemAlloc", ui->maxMemSpinBox->value()); - m_obj->set("PermGen", ui->permGenSpinBox->value()); - } - else - { - m_obj->reset("MinMemAlloc"); - m_obj->reset("MaxMemAlloc"); - m_obj->reset("PermGen"); - } - - - // Java Settings - bool java = ui->javaSettingsGroupBox->isChecked(); - m_obj->set("OverrideJava", java); - if(java) - { - m_obj->set("JavaPath", ui->javaPathTextBox->text()); - m_obj->set("JvmArgs", ui->jvmArgsTextBox->text()); - } - else - { - m_obj->reset("JavaPath"); - m_obj->reset("JvmArgs"); - } - - - // Custom Commands - bool custcmd = ui->customCommandsGroupBox->isChecked(); - m_obj->set("OverrideCommands", custcmd); - if(custcmd) - { - m_obj->set("PreLaunchCommand", ui->preLaunchCmdTextBox->text()); - m_obj->set("PostExitCommand", ui->postExitCmdTextBox->text()); - } - else - { - m_obj->reset("PreLaunchCommand"); - m_obj->reset("PostExitCommand"); - } - -} - -void InstanceSettings::loadSettings() -{ - // Console - ui->consoleSettingsBox->setChecked(m_obj->get("OverrideConsole").toBool()); - ui->showConsoleCheck->setChecked(m_obj->get("ShowConsole").toBool()); - ui->autoCloseConsoleCheck->setChecked(m_obj->get("AutoCloseConsole").toBool()); - - // Window Size - ui->windowSizeGroupBox->setChecked(m_obj->get("OverrideWindow").toBool()); - ui->maximizedCheckBox->setChecked(m_obj->get("LaunchMaximized").toBool()); - ui->windowWidthSpinBox->setValue(m_obj->get("MinecraftWinWidth").toInt()); - ui->windowHeightSpinBox->setValue(m_obj->get("MinecraftWinHeight").toInt()); - - - // Auto Login - ui->accountSettingsGroupBox->setChecked(m_obj->get("OverrideLogin").toBool()); - ui->autoLoginChecBox->setChecked(m_obj->get("AutoLogin").toBool()); - - // Memory - ui->memoryGroupBox->setChecked(m_obj->get("OverrideMemory").toBool()); - ui->minMemSpinBox->setValue(m_obj->get("MinMemAlloc").toInt()); - ui->maxMemSpinBox->setValue(m_obj->get("MaxMemAlloc").toInt()); - ui->permGenSpinBox->setValue(m_obj->get("PermGen").toInt()); - - // Java Settings - ui->javaSettingsGroupBox->setChecked(m_obj->get("OverrideJava").toBool()); - ui->javaPathTextBox->setText(m_obj->get("JavaPath").toString()); - ui->jvmArgsTextBox->setText(m_obj->get("JvmArgs").toString()); - - // Custom Commands - ui->customCommandsGroupBox->setChecked(m_obj->get("OverrideCommands").toBool()); - ui->preLaunchCmdTextBox->setText(m_obj->get("PreLaunchCommand").toString()); - ui->postExitCmdTextBox->setText(m_obj->get("PostExitCommand").toString()); -} diff --git a/gui/instancesettings.h b/gui/instancesettings.h deleted file mode 100644 index b6cdb92c..00000000 --- a/gui/instancesettings.h +++ /dev/null @@ -1,35 +0,0 @@ -#ifndef INSTANCESETTINGS_H -#define INSTANCESETTINGS_H - -#include -#include "settingsobject.h" - -namespace Ui { -class InstanceSettings; -} - -class InstanceSettings : public QDialog -{ - Q_OBJECT - -public: - explicit InstanceSettings(SettingsObject *s, QWidget *parent = 0); - ~InstanceSettings(); - - void updateCheckboxStuff(); - - void applySettings(); - void loadSettings(); -protected: - virtual void showEvent ( QShowEvent* ); -private slots: - void on_customCommandsGroupBox_toggled(bool arg1); - void on_buttonBox_accepted(); - void on_buttonBox_rejected(); - -private: - Ui::InstanceSettings *ui; - SettingsObject * m_obj; -}; - -#endif // INSTANCESETTINGS_H diff --git a/gui/instancesettings.ui b/gui/instancesettings.ui deleted file mode 100644 index b536e9ff..00000000 --- a/gui/instancesettings.ui +++ /dev/null @@ -1,422 +0,0 @@ - - - InstanceSettings - - - - 0 - 0 - 526 - 590 - - - - - - - - - - QTabWidget::Rounded - - - 0 - - - - Minecraft - - - - - - true - - - Window Size - - - true - - - false - - - - - - Start Minecraft maximized? - - - - - - - - - Window height: - - - - - - - Window width: - - - - - - - 854 - - - 65536 - - - 1 - - - 854 - - - - - - - 480 - - - 65536 - - - 480 - - - - - - - - - - - - true - - - Console Settings - - - true - - - false - - - - - - Show console while the game is running? - - - - - - - Automatically close console when the game quits? - - - - - - - - - - true - - - Account Settings - - - true - - - false - - - - - - false - - - Login automatically when an instance icon is double clicked? - - - false - - - - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - - Java - - - - - - true - - - Memory - - - true - - - false - - - - - - 512 - - - 65536 - - - 128 - - - 1024 - - - - - - - Minimum memory allocation: - - - - - - - Maximum memory allocation: - - - - - - - 256 - - - 65536 - - - 128 - - - 256 - - - - - - - 64 - - - 999999999 - - - 8 - - - 64 - - - - - - - PermGen: - - - - - - - - - - true - - - Java Settings - - - true - - - false - - - - - - Java path: - - - - - - - - - - JVM arguments: - - - - - - - Auto-detect - - - - - - - - - - - - - true - - - Custom Commands - - - true - - - false - - - - - - - - - Post-exit command: - - - - - - - Pre-launch command: - - - - - - - - - - - - - false - - - - 0 - 0 - - - - Pre-launch command runs before the instance launches and post-exit command runs after it exits. Both will be run in MultiMC's working directory with INST_ID, INST_DIR, and INST_NAME as environment variables. - - - Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop - - - true - - - Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse - - - - - - - - - - - Qt::Horizontal - - - QDialogButtonBox::Cancel|QDialogButtonBox::Ok - - - - - - - settingsTabs - buttonBox - windowSizeGroupBox - maximizedCheckBox - windowWidthSpinBox - windowHeightSpinBox - consoleSettingsBox - showConsoleCheck - autoCloseConsoleCheck - accountSettingsGroupBox - autoLoginChecBox - memoryGroupBox - minMemSpinBox - maxMemSpinBox - permGenSpinBox - javaSettingsGroupBox - javaPathTextBox - pushButton - jvmArgsTextBox - customCommandsGroupBox - preLaunchCmdTextBox - postExitCmdTextBox - - - - diff --git a/gui/logindialog.cpp b/gui/logindialog.cpp deleted file mode 100644 index aeaaaa9e..00000000 --- a/gui/logindialog.cpp +++ /dev/null @@ -1,248 +0,0 @@ -/* Copyright 2013 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 "logindialog.h" -#include "ui_logindialog.h" -#include "keyring.h" -#include "gui/platform.h" -#include "MultiMC.h" - -#include -#include -#include -#include -#include "logic/net/HttpMetaCache.h" -#include - -LoginDialog::LoginDialog(QWidget *parent, const QString& loginErrMsg) : - QDialog(parent), - ui(new Ui::LoginDialog) -{ - MultiMCPlatform::fixWM_CLASS(this); - ui->setupUi(this); - - //: Use offline mode one time - offlineButton = new QPushButton(tr("Offline Once")); - - ui->loginButtonBox->addButton(offlineButton, QDialogButtonBox::ActionRole); - - blockToggles = false; - isOnline_ = true; - onlineForced = false; - - //: The username during login (placeholder) - ui->usernameTextBox->lineEdit()->setPlaceholderText(tr("Name")); - - connect(ui->usernameTextBox, SIGNAL(currentTextChanged(QString)), this, SLOT(userTextChanged(QString))); - connect(ui->forgetButton, SIGNAL(clicked(bool)), this, SLOT(forgetCurrentUser())); - connect(offlineButton, SIGNAL(clicked(bool)), this, SLOT(launchOffline())); - - if (loginErrMsg.isEmpty()) - ui->loginErrorLabel->setVisible(false); - else - { - ui->loginErrorLabel->setVisible(true); - ui->loginErrorLabel->setText(QString("%1"). - arg(loginErrMsg)); - } - - ui->lblFace->setVisible(false); - - resize(minimumSizeHint()); - layout()->setSizeConstraint(QLayout::SetFixedSize); - Keyring * k = Keyring::instance(); - QStringList accounts = k->getStoredAccounts("minecraft"); - ui->usernameTextBox->addItems(accounts); - - // TODO: restore last selected account here, if applicable - - int index = ui->usernameTextBox->currentIndex(); - if(index != -1) - { - ui->passwordTextBox->setFocus(Qt::OtherFocusReason); - } - - connect(ui->rememberUsernameCheckbox,SIGNAL(toggled(bool)), SLOT(usernameToggled(bool))); - connect(ui->rememberPasswordCheckbox,SIGNAL(toggled(bool)), SLOT(passwordToggled(bool))); -} - -LoginDialog::~LoginDialog() -{ - delete offlineButton; - delete ui; -} - -QString LoginDialog::getUsername() const -{ - return ui->usernameTextBox->currentText(); -} - -QString LoginDialog::getPassword() const -{ - return ui->passwordTextBox->text(); -} - -void LoginDialog::forgetCurrentUser() -{ - Keyring * k = Keyring::instance(); - QString acct = ui->usernameTextBox->currentText(); - k->removeStoredAccount("minecraft", acct); - ui->passwordTextBox->clear(); - int index = ui->usernameTextBox->findText(acct); - if(index != -1) - ui->usernameTextBox->removeItem(index); - if(!ui->usernameTextBox->count()) - { - blockToggles = true; - ui->rememberUsernameCheckbox->setChecked(false); - ui->rememberPasswordCheckbox->setChecked(false); - blockToggles = false; - } -} - -void LoginDialog::passwordToggled ( bool state ) -{ - // if toggled off - if(blockToggles) - return; - blockToggles = true; - if(!state) - { - QLOG_DEBUG() << "password disabled"; - } - else - { - if(!ui->rememberUsernameCheckbox->isChecked()) - { - ui->rememberUsernameCheckbox->setChecked(true); - } - QLOG_DEBUG() << "password enabled"; - } - blockToggles = false; -} - -void LoginDialog::usernameToggled ( bool state ) -{ - // if toggled off - if(blockToggles) - return; - blockToggles = true; - if(!state) - { - if(ui->rememberPasswordCheckbox->isChecked()) - { - ui->rememberPasswordCheckbox->setChecked(false); - } - QLOG_DEBUG() << "username disabled"; - } - else - { - QLOG_DEBUG() << "username enabled"; - } - blockToggles = false; -} - - -void LoginDialog::userTextChanged ( const QString& user ) -{ - blockToggles = true; - Keyring * k = Keyring::instance(); - QStringList sl = k->getStoredAccounts("minecraft"); - bool gotFace = false; - - if(sl.contains(user)) - { - ui->rememberUsernameCheckbox->setChecked(true); - QString passwd = k->getPassword("minecraft",user); - ui->rememberPasswordCheckbox->setChecked(!passwd.isEmpty()); - ui->passwordTextBox->setText(passwd); - - QByteArray data; - { - auto filename = MMC->metacache()->resolveEntry("skins", "skins.json")->getFullPath(); - QFile listFile(filename); - if(!listFile.open(QIODevice::ReadOnly)) - return; - data = listFile.readAll(); - } - - QJsonParseError jsonError; - QJsonDocument jsonDoc = QJsonDocument::fromJson(data, &jsonError); - QJsonObject root = jsonDoc.object(); - QJsonObject mappings = root.value("mappings").toObject(); - - if(!mappings[user].isUndefined()) - { - QJsonArray usernames = mappings.value(user).toArray(); - if(!usernames.isEmpty()) - { - QString mapped_username = usernames[0].toString(); - - if(!mapped_username.isEmpty()) - { - QFile fskin(MMC->metacache()->resolveEntry("skins", mapped_username + ".png")->getFullPath()); - if(fskin.exists()) - { - QPixmap skin(MMC->metacache()->resolveEntry("skins", mapped_username + ".png")->getFullPath()); - QPixmap face = skin.copy(8, 8, 8, 8).scaled(48, 48, Qt::KeepAspectRatio); - - ui->lblFace->setPixmap(face); - gotFace = true; - } - } - } - } - } - - ui->lblFace->setVisible(gotFace); - blockToggles = false; -} - - -void LoginDialog::accept() -{ - bool saveName = ui->rememberUsernameCheckbox->isChecked(); - bool savePass = ui->rememberPasswordCheckbox->isChecked(); - Keyring * k = Keyring::instance(); - if(saveName) - { - if(savePass) - { - k->storePassword("minecraft",getUsername(),getPassword()); - } - else - { - k->storePassword("minecraft",getUsername(),QString()); - } - } - else - { - QString acct = ui->usernameTextBox->currentText(); - k->removeStoredAccount("minecraft", acct); - } - QDialog::accept(); -} - -void LoginDialog::launchOffline() -{ - isOnline_ = false; - QDialog::accept(); -} - -void LoginDialog::forceOnline() -{ - onlineForced = true; - offlineButton->setEnabled(false); -} diff --git a/gui/logindialog.h b/gui/logindialog.h deleted file mode 100644 index f7c0e930..00000000 --- a/gui/logindialog.h +++ /dev/null @@ -1,57 +0,0 @@ -/* Copyright 2013 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. - */ - -#ifndef LOGINDIALOG_H -#define LOGINDIALOG_H - -#include -#include - -namespace Ui { -class LoginDialog; -} - -class LoginDialog : public QDialog -{ - Q_OBJECT - -public: - explicit LoginDialog(QWidget *parent = 0, const QString& loginErrMsg = ""); - ~LoginDialog(); - - QString getUsername() const; - QString getPassword() const; - - inline bool isOnline() { return isOnline_; } - - void forceOnline(); - -public slots: - virtual void accept(); - virtual void userTextChanged(const QString& user); - virtual void forgetCurrentUser(); -private slots: - void usernameToggled ( bool ); - void passwordToggled ( bool ); - void launchOffline(); -private: - Ui::LoginDialog *ui; - bool blockToggles; - QPushButton *offlineButton; - bool isOnline_; - bool onlineForced; -}; - -#endif // LOGINDIALOG_H diff --git a/gui/logindialog.ui b/gui/logindialog.ui deleted file mode 100644 index 94900d72..00000000 --- a/gui/logindialog.ui +++ /dev/null @@ -1,185 +0,0 @@ - - - LoginDialog - - - - 0 - 0 - 476 - 168 - - - - Login - - - - - - <span style=" color:#ff0000;">Error</span> - - - Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse - - - - - - - - - - 48 - 48 - - - - - 48 - 48 - - - - - 1 - 1 - - - - - - - :/icons/instances/steve - - - true - - - - - - - true - - - - - - - Username: - - - - - - - Password: - - - - - - - QLineEdit::Password - - - Password - - - - - - - - - - - - 1 - 0 - - - - &Remember Username? - - - - - - - - 1 - 0 - - - - R&emember Password? - - - - - - - - 0 - 0 - - - - Forget - - - - - - - - - Qt::Horizontal - - - QDialogButtonBox::Cancel|QDialogButtonBox::Ok - - - - - - - - - - - loginButtonBox - accepted() - LoginDialog - accept() - - - 248 - 254 - - - 157 - 274 - - - - - loginButtonBox - rejected() - LoginDialog - reject() - - - 316 - 260 - - - 286 - 274 - - - - - diff --git a/gui/lwjglselectdialog.cpp b/gui/lwjglselectdialog.cpp deleted file mode 100644 index 09963ce0..00000000 --- a/gui/lwjglselectdialog.cpp +++ /dev/null @@ -1,72 +0,0 @@ -/* Copyright 2013 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 "MultiMC.h" -#include "lwjglselectdialog.h" -#include "ui_lwjglselectdialog.h" -#include "gui/platform.h" - -#include "logic/lists/LwjglVersionList.h" - -LWJGLSelectDialog::LWJGLSelectDialog(QWidget *parent) : - QDialog(parent), - ui(new Ui::LWJGLSelectDialog) -{ - MultiMCPlatform::fixWM_CLASS(this); - ui->setupUi(this); - ui->labelStatus->setVisible(false); - auto lwjgllist = MMC->lwjgllist(); - ui->lwjglListView->setModel(lwjgllist.get()); - - connect(lwjgllist.get(), SIGNAL(loadingStateUpdated(bool)), SLOT(loadingStateUpdated(bool))); - connect(lwjgllist.get(), SIGNAL(loadListFailed(QString)), SLOT(loadingFailed(QString))); - loadingStateUpdated(lwjgllist->isLoading()); -} - -LWJGLSelectDialog::~LWJGLSelectDialog() -{ - delete ui; -} - -QString LWJGLSelectDialog::selectedVersion() const -{ - return MMC->lwjgllist()->data( - ui->lwjglListView->selectionModel()->currentIndex(), - Qt::DisplayRole).toString(); -} - -void LWJGLSelectDialog::on_refreshButton_clicked() -{ - if (!MMC->lwjgllist()->isLoading()) - MMC->lwjgllist()->loadList(); -} - -void LWJGLSelectDialog::loadingStateUpdated(bool loading) -{ - setEnabled(!loading); - if (loading) - { - ui->labelStatus->setText(tr("Loading LWJGL version list...")); - ui->labelStatus->setStyleSheet("QLabel { color: black; }"); - } - ui->labelStatus->setVisible(loading); -} - -void LWJGLSelectDialog::loadingFailed(QString error) -{ - ui->labelStatus->setText(error); - ui->labelStatus->setStyleSheet("QLabel { color: red; }"); - ui->labelStatus->setVisible(true); -} diff --git a/gui/lwjglselectdialog.h b/gui/lwjglselectdialog.h deleted file mode 100644 index 1772904a..00000000 --- a/gui/lwjglselectdialog.h +++ /dev/null @@ -1,46 +0,0 @@ -/* Copyright 2013 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. - */ - -#ifndef LWJGLSELECTDIALOG_H -#define LWJGLSELECTDIALOG_H - -#include - -namespace Ui -{ -class LWJGLSelectDialog; -} - -class LWJGLSelectDialog : public QDialog -{ - Q_OBJECT - -public: - explicit LWJGLSelectDialog(QWidget *parent = 0); - ~LWJGLSelectDialog(); - - QString selectedVersion() const; - -private slots: - void on_refreshButton_clicked(); - - void loadingStateUpdated(bool loading); - void loadingFailed(QString error); - -private: - Ui::LWJGLSelectDialog *ui; -}; - -#endif // LWJGLSELECTDIALOG_H diff --git a/gui/lwjglselectdialog.ui b/gui/lwjglselectdialog.ui deleted file mode 100644 index c715cc07..00000000 --- a/gui/lwjglselectdialog.ui +++ /dev/null @@ -1,85 +0,0 @@ - - - LWJGLSelectDialog - - - - 0 - 0 - 400 - 300 - - - - Dialog - - - - - - Status label... - - - - - - - - - - - - &Refresh - - - - - - - Qt::Horizontal - - - QDialogButtonBox::Cancel|QDialogButtonBox::Ok - - - - - - - - - - - buttonBox - accepted() - LWJGLSelectDialog - accept() - - - 248 - 254 - - - 157 - 274 - - - - - buttonBox - rejected() - LWJGLSelectDialog - reject() - - - 316 - 260 - - - 286 - 274 - - - - - diff --git a/gui/mainwindow.cpp b/gui/mainwindow.cpp deleted file mode 100644 index 20a2b84b..00000000 --- a/gui/mainwindow.cpp +++ /dev/null @@ -1,974 +0,0 @@ -/* Copyright 2013 MultiMC Contributors - * - * Authors: Andrew Okin - * Peterix - * Orochimarufan - * - * 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 - -#include "mainwindow.h" -#include "ui_mainwindow.h" -#include "keyring.h" - -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -#include "osutils.h" -#include "userutils.h" -#include "pathutils.h" - -#include "categorizedview.h" -#include "categorydrawer.h" - -#include "gui/settingsdialog.h" -#include "gui/newinstancedialog.h" -#include "gui/logindialog.h" -#include "gui/ProgressDialog.h" -#include "gui/aboutdialog.h" -#include "gui/versionselectdialog.h" -#include "gui/lwjglselectdialog.h" -#include "gui/consolewindow.h" -#include "gui/instancesettings.h" -#include "gui/platform.h" -#include "gui/CustomMessageBox.h" - -#include "logic/lists/InstanceList.h" -#include "logic/lists/MinecraftVersionList.h" -#include "logic/lists/LwjglVersionList.h" -#include "logic/lists/IconList.h" -#include "logic/lists/JavaVersionList.h" - -#include "logic/net/LoginTask.h" - -#include "logic/BaseInstance.h" -#include "logic/InstanceFactory.h" -#include "logic/MinecraftProcess.h" -#include "logic/OneSixAssets.h" -#include "logic/OneSixUpdate.h" -#include "logic/JavaUtils.h" -#include "logic/NagUtils.h" - -#include "logic/LegacyInstance.h" - -#include "instancedelegate.h" -#include "IconPickerDialog.h" -#include "LabeledToolButton.h" -#include "EditNotesDialog.h" -#include "CopyInstanceDialog.h" - -MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) -{ - MultiMCPlatform::fixWM_CLASS(this); - ui->setupUi(this); - setWindowTitle(QString("MultiMC %1").arg(MMC->version().toString())); - - // Set the selected instance to null - m_selectedInstance = nullptr; - // Set active instance to null. - m_activeInst = nullptr; - - // OSX magic. - setUnifiedTitleAndToolBarOnMac(true); - - // The instance action toolbar customizations - { - // disabled until we have an instance selected - ui->instanceToolBar->setEnabled(false); - - // the rename label is inside the rename tool button - renameButton = new LabeledToolButton(); - renameButton->setText("Instance Name"); - renameButton->setToolTip(ui->actionRenameInstance->toolTip()); - connect(renameButton, SIGNAL(clicked(bool)), SLOT(on_actionRenameInstance_triggered())); - ui->instanceToolBar->insertWidget(ui->actionLaunchInstance, renameButton); - ui->instanceToolBar->insertSeparator(ui->actionLaunchInstance); - renameButton->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); - } - - // Create the instance list widget - { - view = new KCategorizedView(ui->centralWidget); - drawer = new KCategoryDrawer(view); - - view->setSelectionMode(QAbstractItemView::SingleSelection); - view->setCategoryDrawer(drawer); - view->setCollapsibleBlocks(true); - view->setViewMode(QListView::IconMode); - view->setFlow(QListView::LeftToRight); - view->setWordWrap(true); - view->setMouseTracking(true); - view->viewport()->setAttribute(Qt::WA_Hover); - auto delegate = new ListViewDelegate(); - view->setItemDelegate(delegate); - view->setSpacing(10); - view->setUniformItemWidths(true); - - // do not show ugly blue border on the mac - view->setAttribute(Qt::WA_MacShowFocusRect, false); - - view->installEventFilter(this); - - proxymodel = new InstanceProxyModel(this); -// proxymodel->setSortRole(KCategorizedSortFilterProxyModel::CategorySortRole); - //proxymodel->setFilterRole(KCategorizedSortFilterProxyModel::CategorySortRole); - // proxymodel->setDynamicSortFilter ( true ); - - // FIXME: instList should be global-ish, or at least not tied to the main window... - // maybe the application itself? - proxymodel->setSourceModel(MMC->instances().get()); - proxymodel->sort(0); - view->setFrameShape(QFrame::NoFrame); - view->setModel(proxymodel); - - ui->horizontalLayout->addWidget(view); - } - // The cat background - { - bool cat_enable = MMC->settings()->get("TheCat").toBool(); - ui->actionCAT->setChecked(cat_enable); - connect(ui->actionCAT, SIGNAL(toggled(bool)), SLOT(onCatToggled(bool))); - setCatBackground(cat_enable); - } - // start instance when double-clicked - connect(view, SIGNAL(doubleClicked(const QModelIndex &)), this, - SLOT(instanceActivated(const QModelIndex &))); - // track the selection -- update the instance toolbar - connect(view->selectionModel(), - SIGNAL(currentChanged(const QModelIndex &, const QModelIndex &)), this, - SLOT(instanceChanged(const QModelIndex &, const QModelIndex &))); - // model reset -> selection is invalid. All the instance pointers are wrong. - // FIXME: stop using POINTERS everywhere - connect(MMC->instances().get(), SIGNAL(dataIsInvalid()), SLOT(selectionBad())); - - m_statusLeft = new QLabel(tr("Instance type"), this); - m_statusRight = new QLabel(tr("Assets information"), this); - m_statusRight->setAlignment(Qt::AlignRight); - statusBar()->addPermanentWidget(m_statusLeft, 1); - statusBar()->addPermanentWidget(m_statusRight, 0); - - // run the things that load and download other things... FIXME: this is NOT the place - // FIXME: invisible actions in the background = NOPE. - { - if (!MMC->minecraftlist()->isLoaded()) - { - m_versionLoadTask = MMC->minecraftlist()->getLoadTask(); - startTask(m_versionLoadTask); - } - if (!MMC->lwjgllist()->isLoaded()) - { - MMC->lwjgllist()->loadList(); - } - assets_downloader = new OneSixAssets(); - connect(assets_downloader, SIGNAL(indexStarted()), SLOT(assetsIndexStarted())); - connect(assets_downloader, SIGNAL(filesStarted()), SLOT(assetsFilesStarted())); - connect(assets_downloader, SIGNAL(filesProgress(int, int, int)), - SLOT(assetsFilesProgress(int, int, int))); - connect(assets_downloader, SIGNAL(failed()), SLOT(assetsFailed())); - connect(assets_downloader, SIGNAL(finished()), SLOT(assetsFinished())); - assets_downloader->start(); - } -} - -MainWindow::~MainWindow() -{ - delete ui; - delete proxymodel; - delete drawer; - delete assets_downloader; -} - -bool MainWindow::eventFilter(QObject *obj, QEvent *ev) -{ - if (obj == view) - { - if (ev->type() == QEvent::KeyPress) - { - QKeyEvent *keyEvent = static_cast(ev); - switch (keyEvent->key()) - { - case Qt::Key_Enter: - case Qt::Key_Return: - on_actionLaunchInstance_triggered(); - return true; - case Qt::Key_Delete: - on_actionDeleteInstance_triggered(); - return true; - case Qt::Key_F5: - on_actionRefresh_triggered(); - return true; - case Qt::Key_F2: - on_actionRenameInstance_triggered(); - return true; - default: - break; - } - } - } - return QMainWindow::eventFilter(obj, ev); -} - -void MainWindow::onCatToggled(bool state) -{ - setCatBackground(state); - MMC->settings()->set("TheCat", state); -} - -void MainWindow::setCatBackground(bool enabled) -{ - if (enabled) - { - view->setStyleSheet("QListView" - "{" - "background-image: url(:/backgrounds/kitteh);" - "background-attachment: fixed;" - "background-clip: padding;" - "background-position: top right;" - "background-repeat: none;" - "background-color:palette(base);" - "}"); - } - else - { - view->setStyleSheet(QString()); - } -} - -void MainWindow::on_actionAddInstance_triggered() -{ - if (!MMC->minecraftlist()->isLoaded() && m_versionLoadTask && - m_versionLoadTask->isRunning()) - { - QEventLoop waitLoop; - waitLoop.connect(m_versionLoadTask, SIGNAL(failed(QString)), SLOT(quit())); - waitLoop.connect(m_versionLoadTask, SIGNAL(succeeded()), SLOT(quit())); - waitLoop.exec(); - } - - NewInstanceDialog newInstDlg(this); - if (!newInstDlg.exec()) - return; - - BaseInstance *newInstance = NULL; - - QString instancesDir = MMC->settings()->get("InstanceDir").toString(); - QString instDirName = DirNameFromString(newInstDlg.instName(), instancesDir); - QString instDir = PathCombine(instancesDir, instDirName); - - auto &loader = InstanceFactory::get(); - - auto error = loader.createInstance(newInstance, newInstDlg.selectedVersion(), instDir); - QString errorMsg = QString("Failed to create instance %1: ").arg(instDirName); - switch (error) - { - case InstanceFactory::NoCreateError: - newInstance->setName(newInstDlg.instName()); - newInstance->setIconKey(newInstDlg.iconKey()); - MMC->instances()->add(InstancePtr(newInstance)); - return; - - case InstanceFactory::InstExists: - { - errorMsg += "An instance with the given directory name already exists."; - CustomMessageBox::selectable(this, tr("Error"), errorMsg, QMessageBox::Warning)->show(); - break; - } - - case InstanceFactory::CantCreateDir: - { - errorMsg += "Failed to create the instance directory."; - CustomMessageBox::selectable(this, tr("Error"), errorMsg, QMessageBox::Warning)->show(); - break; - } - - default: - { - errorMsg += QString("Unknown instance loader error %1").arg(error); - CustomMessageBox::selectable(this, tr("Error"), errorMsg, QMessageBox::Warning)->show(); - break; - } - } -} - -void MainWindow::on_actionCopyInstance_triggered() -{ - if (!m_selectedInstance) - return; - - CopyInstanceDialog copyInstDlg(m_selectedInstance, this); - if (!copyInstDlg.exec()) - return; - - QString instancesDir = MMC->settings()->get("InstanceDir").toString(); - QString instDirName = DirNameFromString(copyInstDlg.instName(), instancesDir); - QString instDir = PathCombine(instancesDir, instDirName); - - auto &loader = InstanceFactory::get(); - - BaseInstance *newInstance = NULL; - auto error = loader.copyInstance(newInstance, m_selectedInstance, instDir); - - QString errorMsg = QString("Failed to create instance %1: ").arg(instDirName); - switch (error) - { - case InstanceFactory::NoCreateError: - newInstance->setName(copyInstDlg.instName()); - newInstance->setIconKey(copyInstDlg.iconKey()); - MMC->instances()->add(InstancePtr(newInstance)); - return; - - case InstanceFactory::InstExists: - { - errorMsg += "An instance with the given directory name already exists."; - CustomMessageBox::selectable(this, tr("Error"), errorMsg, QMessageBox::Warning)->show(); - break; - } - - case InstanceFactory::CantCreateDir: - { - errorMsg += "Failed to create the instance directory."; - CustomMessageBox::selectable(this, tr("Error"), errorMsg, QMessageBox::Warning)->show(); - break; - } - - default: - { - errorMsg += QString("Unknown instance loader error %1").arg(error); - CustomMessageBox::selectable(this, tr("Error"), errorMsg, QMessageBox::Warning)->show(); - break; - } - } -} - -void MainWindow::on_actionChangeInstIcon_triggered() -{ - if (!m_selectedInstance) - return; - - IconPickerDialog dlg(this); - dlg.exec(m_selectedInstance->iconKey()); - if (dlg.result() == QDialog::Accepted) - { - m_selectedInstance->setIconKey(dlg.selectedIconKey); - auto ico = MMC->icons()->getIcon(dlg.selectedIconKey); - ui->actionChangeInstIcon->setIcon(ico); - } -} - -void MainWindow::on_actionChangeInstGroup_triggered() -{ - if (!m_selectedInstance) - return; - - bool ok = false; - QString name(m_selectedInstance->group()); - name = QInputDialog::getText(this, tr("Group name"), tr("Enter a new group name."), - QLineEdit::Normal, name, &ok); - if (ok) - m_selectedInstance->setGroupPost(name); -} - -void MainWindow::on_actionViewInstanceFolder_triggered() -{ - QString str = MMC->settings()->get("InstanceDir").toString(); - openDirInDefaultProgram(str); -} - -void MainWindow::on_actionRefresh_triggered() -{ - MMC->instances()->loadList(); -} - -void MainWindow::on_actionViewCentralModsFolder_triggered() -{ - openDirInDefaultProgram(MMC->settings()->get("CentralModsDir").toString(), true); -} - -void MainWindow::on_actionConfig_Folder_triggered() -{ - if (m_selectedInstance) - { - QString str = m_selectedInstance->instanceConfigFolder(); - openDirInDefaultProgram(QDir(str).absolutePath()); - } -} - -void MainWindow::on_actionCheckUpdate_triggered() -{ -} - -void MainWindow::on_actionSettings_triggered() -{ - SettingsDialog dialog(this); - dialog.exec(); - //FIXME: quick HACK to make this work. improve, optimize. - proxymodel->invalidate(); - proxymodel->sort(0); -} - -void MainWindow::on_actionReportBug_triggered() -{ - openWebPage(QUrl("http://multimc.myjetbrains.com/youtrack/dashboard#newissue=yes")); -} - -void MainWindow::on_actionNews_triggered() -{ - openWebPage(QUrl("http://multimc.org/posts.html")); -} - -void MainWindow::on_actionAbout_triggered() -{ - AboutDialog dialog(this); - dialog.exec(); -} - -void MainWindow::on_mainToolBar_visibilityChanged(bool) -{ - // Don't allow hiding the main toolbar. - // This is the only way I could find to prevent it... :/ - ui->mainToolBar->setVisible(true); -} - -void MainWindow::on_actionDeleteInstance_triggered() -{ - if (m_selectedInstance) - { - auto response = CustomMessageBox::selectable( - this, tr("CAREFUL"), tr("This is permanent! Are you sure?\nAbout to delete: ") + - m_selectedInstance->name(), - QMessageBox::Question, QMessageBox::Yes | QMessageBox::No)->exec(); - if (response == QMessageBox::Yes) - { - m_selectedInstance->nuke(); - } - } -} - -void MainWindow::on_actionRenameInstance_triggered() -{ - if (m_selectedInstance) - { - bool ok = false; - QString name(m_selectedInstance->name()); - name = - QInputDialog::getText(this, tr("Instance name"), tr("Enter a new instance name."), - QLineEdit::Normal, name, &ok); - - if (name.length() > 0) - { - if (ok && name.length()) - { - m_selectedInstance->setName(name); - renameButton->setText(name); - } - } - } -} - -void MainWindow::on_actionViewSelectedInstFolder_triggered() -{ - if (m_selectedInstance) - { - QString str = m_selectedInstance->instanceRoot(); - openDirInDefaultProgram(QDir(str).absolutePath()); - } -} - -void MainWindow::on_actionEditInstMods_triggered() -{ - if (m_selectedInstance) - { - auto dialog = m_selectedInstance->createModEditDialog(this); - if (dialog) - dialog->exec(); - dialog->deleteLater(); - } -} - -void MainWindow::closeEvent(QCloseEvent *event) -{ - // Save the window state and geometry. - - MMC->settings()->set("MainWindowState", saveState().toBase64()); - MMC->settings()->set("MainWindowGeometry", saveGeometry().toBase64()); - - QMainWindow::closeEvent(event); - QApplication::exit(); -} -/* -void MainWindow::on_instanceView_customContextMenuRequested(const QPoint &pos) -{ - QMenu *instContextMenu = new QMenu("Instance", this); - - // Add the actions from the toolbar to the context menu. - instContextMenu->addActions(ui->instanceToolBar->actions()); - - instContextMenu->exec(view->mapToGlobal(pos)); -} -*/ -void MainWindow::instanceActivated(QModelIndex index) -{ - if (!index.isValid()) - return; - - BaseInstance *inst = - (BaseInstance *)index.data(InstanceList::InstancePointerRole).value(); - - NagUtils::checkJVMArgs(MMC->settings()->get("JvmArgs").toString(), this); - - bool autoLogin = MMC->settings()->get("AutoLogin").toBool(); - if (autoLogin) - doAutoLogin(); - else - doLogin(); -} - -void MainWindow::on_actionLaunchInstance_triggered() -{ - if (m_selectedInstance) - { - NagUtils::checkJVMArgs(MMC->settings()->get("JvmArgs").toString(), this); - doLogin(); - } -} - -void MainWindow::doAutoLogin() -{ - if (!m_selectedInstance) - return; - - Keyring *k = Keyring::instance(); - QStringList accounts = k->getStoredAccounts("minecraft"); - - if (!accounts.isEmpty()) - { - QString username = accounts[0]; - QString password = k->getPassword("minecraft", username); - - if (!password.isEmpty()) - { - QLOG_INFO() << "Automatically logging in with stored account: " << username; - m_activeInst = m_selectedInstance; - doLogin(username, password); - } - else - { - QLOG_ERROR() << "Auto login set for account, but no password was found: " - << username; - doLogin(tr("Auto login attempted, but no password is stored.")); - } - } - else - { - QLOG_ERROR() << "Auto login set but no accounts were stored."; - doLogin(tr("Auto login attempted, but no accounts are stored.")); - } -} - -void MainWindow::doLogin(QString username, QString password) -{ - UserInfo uInfo{username, password}; - - ProgressDialog *tDialog = new ProgressDialog(this); - LoginTask *loginTask = new LoginTask(uInfo, tDialog); - connect(loginTask, SIGNAL(succeeded()), SLOT(onLoginComplete()), Qt::QueuedConnection); - connect(loginTask, SIGNAL(failed(QString)), SLOT(doLogin(QString)), Qt::QueuedConnection); - - tDialog->exec(loginTask); -} - -void MainWindow::doLogin(const QString &errorMsg) -{ - if (!m_selectedInstance) - return; - - LoginDialog *loginDlg = new LoginDialog(this, errorMsg); - if (!m_selectedInstance->lastLaunch()) - loginDlg->forceOnline(); - - loginDlg->exec(); - if (loginDlg->result() == QDialog::Accepted) - { - if (loginDlg->isOnline()) - { - m_activeInst = m_selectedInstance; - doLogin(loginDlg->getUsername(), loginDlg->getPassword()); - } - else - { - QString user = loginDlg->getUsername(); - if (user.length() == 0) - user = QString("Player"); - m_activeLogin = {user, QString("Offline"), user, QString()}; - m_activeInst = m_selectedInstance; - launchInstance(m_activeInst, m_activeLogin); - } - } -} - -void MainWindow::onLoginComplete() -{ - if (!m_activeInst) - return; - LoginTask *task = (LoginTask *)QObject::sender(); - m_activeLogin = task->getResult(); - - BaseUpdate *updateTask = m_activeInst->doUpdate(); - if (!updateTask) - { - launchInstance(m_activeInst, m_activeLogin); - } - else - { - ProgressDialog tDialog(this); - connect(updateTask, SIGNAL(succeeded()), SLOT(onGameUpdateComplete())); - connect(updateTask, SIGNAL(failed(QString)), SLOT(onGameUpdateError(QString))); - tDialog.exec(updateTask); - delete updateTask; - } - - auto job = new NetJob("Player skin: " + m_activeLogin.player_name); - - auto meta = MMC->metacache()->resolveEntry("skins", m_activeLogin.player_name + ".png"); - auto action = CacheDownload::make( - QUrl("http://skins.minecraft.net/MinecraftSkins/" + m_activeLogin.player_name + ".png"), - meta); - job->addNetAction(action); - meta->stale = true; - - job->start(); - auto filename = MMC->metacache()->resolveEntry("skins", "skins.json")->getFullPath(); - QFile listFile(filename); - - // Add skin mapping - QByteArray data; - { - if (!listFile.open(QIODevice::ReadWrite)) - { - QLOG_ERROR() << "Failed to open/make skins list JSON"; - return; - } - - data = listFile.readAll(); - } - - QJsonParseError jsonError; - QJsonDocument jsonDoc = QJsonDocument::fromJson(data, &jsonError); - QJsonObject root = jsonDoc.object(); - QJsonObject mappings = root.value("mappings").toObject(); - QJsonArray usernames = mappings.value(m_activeLogin.username).toArray(); - - if (!usernames.contains(m_activeLogin.player_name)) - { - usernames.prepend(m_activeLogin.player_name); - mappings[m_activeLogin.username] = usernames; - root["mappings"] = mappings; - jsonDoc.setObject(root); - - // QJson hack - shouldn't have to clear the file every time a save happens - listFile.resize(0); - listFile.write(jsonDoc.toJson()); - } -} - -void MainWindow::onGameUpdateComplete() -{ - launchInstance(m_activeInst, m_activeLogin); -} - -void MainWindow::onGameUpdateError(QString error) -{ - CustomMessageBox::selectable(this, tr("Error updating instance"), error, - QMessageBox::Warning)->show(); -} - -void MainWindow::launchInstance(BaseInstance *instance, LoginResponse response) -{ - Q_ASSERT_X(instance != NULL, "launchInstance", "instance is NULL"); - - proc = instance->prepareForLaunch(response); - if (!proc) - return; - - // Prepare GUI: If it shall stay open disable the required parts - if (MMC->settings()->get("NoHide").toBool()) - { - ui->actionLaunchInstance->setEnabled(false); - } - else - { - this->hide(); - } - - console = new ConsoleWindow(proc); - - connect(proc, SIGNAL(log(QString, MessageLevel::Enum)), console, - SLOT(write(QString, MessageLevel::Enum))); - connect(proc, SIGNAL(ended(BaseInstance *)), this, SLOT(instanceEnded(BaseInstance *))); - - if (instance->settings().get("ShowConsole").toBool()) - { - console->show(); - } - - proc->setLogin(response.username, response.session_id); - proc->launch(); -} - -void MainWindow::taskStart() -{ - // Nothing to do here yet. -} - -void MainWindow::taskEnd() -{ - QObject *sender = QObject::sender(); - if (sender == m_versionLoadTask) - m_versionLoadTask = NULL; - - sender->deleteLater(); -} - -void MainWindow::startTask(Task *task) -{ - connect(task, SIGNAL(started()), SLOT(taskStart())); - connect(task, SIGNAL(succeeded()), SLOT(taskEnd())); - connect(task, SIGNAL(failed(QString)), SLOT(taskEnd())); - task->start(); -} - -// Create A Desktop Shortcut -void MainWindow::on_actionMakeDesktopShortcut_triggered() -{ - QString name("Test"); - name = QInputDialog::getText(this, tr("MultiMC Shortcut"), tr("Enter a Shortcut Name."), - QLineEdit::Normal, name); - - Util::createShortCut(Util::getDesktopDir(), QApplication::instance()->applicationFilePath(), - QStringList() << "-dl" << QDir::currentPath() << "test", name, - "application-x-octet-stream"); - - CustomMessageBox::selectable( - this, tr("Not useful"), - tr("A Dummy Shortcut was created. it will not do anything productive"), - QMessageBox::Warning)->show(); -} - -// BrowserDialog -void MainWindow::openWebPage(QUrl url) -{ - QDesktopServices::openUrl(url); -} - -void MainWindow::on_actionChangeInstMCVersion_triggered() -{ - if (view->selectionModel()->selectedIndexes().count() < 1) - return; - - VersionSelectDialog vselect(m_selectedInstance->versionList().get(), - tr("Change Minecraft version"), this); - vselect.setFilter(1, "OneSix"); - if (vselect.exec() && vselect.selectedVersion()) - { - if (m_selectedInstance->versionIsCustom()) - { - auto result = CustomMessageBox::selectable( - this, tr("Are you sure?"), - tr("This will remove any library/version customization you did previously. " - "This includes things like Forge install and similar."), - QMessageBox::Warning, QMessageBox::Ok, QMessageBox::Abort)->exec(); - - if (result != QMessageBox::Ok) - return; - } - m_selectedInstance->setIntendedVersionId(vselect.selectedVersion()->descriptor()); - } -} - -void MainWindow::on_actionChangeInstLWJGLVersion_triggered() -{ - if (!m_selectedInstance) - return; - - LWJGLSelectDialog lselect(this); - lselect.exec(); - if (lselect.result() == QDialog::Accepted) - { - LegacyInstance *linst = (LegacyInstance *)m_selectedInstance; - linst->setLWJGLVersion(lselect.selectedVersion()); - } -} - -void MainWindow::on_actionInstanceSettings_triggered() -{ - if (view->selectionModel()->selectedIndexes().count() < 1) - return; - - InstanceSettings settings(&m_selectedInstance->settings(), this); - settings.setWindowTitle(QString("Instance settings")); - settings.exec(); -} - -void MainWindow::instanceChanged(const QModelIndex ¤t, const QModelIndex &previous) -{ - if (current.isValid() && - nullptr != (m_selectedInstance = - (BaseInstance *)current.data(InstanceList::InstancePointerRole) - .value())) - { - ui->instanceToolBar->setEnabled(true); - QString iconKey = m_selectedInstance->iconKey(); - renameButton->setText(m_selectedInstance->name()); - ui->actionChangeInstLWJGLVersion->setEnabled( - m_selectedInstance->menuActionEnabled("actionChangeInstLWJGLVersion")); - ui->actionEditInstMods->setEnabled( - m_selectedInstance->menuActionEnabled("actionEditInstMods")); - ui->actionChangeInstMCVersion->setEnabled( - m_selectedInstance->menuActionEnabled("actionChangeInstMCVersion")); - m_statusLeft->setText(m_selectedInstance->getStatusbarDescription()); - auto ico = MMC->icons()->getIcon(iconKey); - ui->actionChangeInstIcon->setIcon(ico); - } - else - { - selectionBad(); - } -} - -void MainWindow::selectionBad() -{ - m_selectedInstance = nullptr; - QString iconKey = "infinity"; - statusBar()->clearMessage(); - ui->instanceToolBar->setEnabled(false); - renameButton->setText(tr("Rename Instance")); - auto ico = MMC->icons()->getIcon(iconKey); - ui->actionChangeInstIcon->setIcon(ico); -} - -void MainWindow::on_actionEditInstNotes_triggered() -{ - if (!m_selectedInstance) - return; - LegacyInstance *linst = (LegacyInstance *)m_selectedInstance; - - EditNotesDialog noteedit(linst->notes(), linst->name(), this); - noteedit.exec(); - if (noteedit.result() == QDialog::Accepted) - { - - linst->setNotes(noteedit.getText()); - } -} - -void MainWindow::instanceEnded(BaseInstance *instance) -{ - this->show(); - ui->actionLaunchInstance->setEnabled(m_selectedInstance); - - if (instance->settings().get("AutoCloseConsole").toBool()) - { - console->close(); - } -} - -void MainWindow::checkSetDefaultJava() -{ - bool askForJava = false; - { - QString currentHostName = QHostInfo::localHostName(); - QString oldHostName = MMC->settings()->get("LastHostname").toString(); - if (currentHostName != oldHostName) - { - MMC->settings()->set("LastHostname", currentHostName); - askForJava = true; - } - } - - { - QString currentJavaPath = MMC->settings()->get("JavaPath").toString(); - if (currentJavaPath.isEmpty()) - { - askForJava = true; - } - } - - if (askForJava) - { - QLOG_DEBUG() << "Java path needs resetting, showing Java selection dialog..."; - - JavaVersionPtr java; - - VersionSelectDialog vselect(MMC->javalist().get(), tr("Select a Java version"), this, - false); - vselect.setResizeOn(2); - vselect.exec(); - - if (vselect.selectedVersion()) - java = std::dynamic_pointer_cast(vselect.selectedVersion()); - else - { - CustomMessageBox::selectable( - this, tr("Invalid version selected"), - tr("You didn't select a valid Java version, so MultiMC will " - "select the default. " - "You can change this in the settings dialog."), - QMessageBox::Warning)->show(); - - JavaUtils ju; - java = ju.GetDefaultJava(); - } - if (java) - MMC->settings()->set("JavaPath", java->path); - else - MMC->settings()->set("JavaPath", QString("java")); - } -} - -void MainWindow::assetsIndexStarted() -{ - m_statusRight->setText(tr("Checking assets...")); -} - -void MainWindow::assetsFilesStarted() -{ - m_statusRight->setText(tr("Downloading assets...")); -} - -void MainWindow::assetsFilesProgress(int succeeded, int failed, int total) -{ - QString status = tr("Downloading assets: %1 / %2").arg(succeeded + failed).arg(total); - if (failed > 0) - status += tr(" (%1 failed)").arg(failed); - status += tr("..."); - m_statusRight->setText(status); -} - -void MainWindow::assetsFailed() -{ - m_statusRight->setText(tr("Failed to update assets.")); -} - -void MainWindow::assetsFinished() -{ - m_statusRight->setText(tr("Assets up to date.")); -} diff --git a/gui/mainwindow.h b/gui/mainwindow.h deleted file mode 100644 index 36562563..00000000 --- a/gui/mainwindow.h +++ /dev/null @@ -1,170 +0,0 @@ -/* Copyright 2013 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. - */ - -#ifndef MAINWINDOW_H -#define MAINWINDOW_H - -#include - -#include "logic/lists/InstanceList.h" -#include "logic/net/LoginTask.h" -#include "logic/BaseInstance.h" - -class QToolButton; -class LabeledToolButton; -class QLabel; -class InstanceProxyModel; -class KCategorizedView; -class KCategoryDrawer; -class MinecraftProcess; -class ConsoleWindow; -class OneSixAssets; - -namespace Ui -{ -class MainWindow; -} - -class MainWindow : public QMainWindow -{ - Q_OBJECT - -public: - explicit MainWindow(QWidget *parent = 0); - ~MainWindow(); - - void closeEvent(QCloseEvent *event); - - // Browser Dialog - void openWebPage(QUrl url); - - void checkSetDefaultJava(); - -private -slots: - void onCatToggled(bool); - - void on_actionAbout_triggered(); - - void on_actionAddInstance_triggered(); - - void on_actionCopyInstance_triggered(); - - void on_actionChangeInstGroup_triggered(); - - void on_actionChangeInstIcon_triggered(); - - void on_actionViewInstanceFolder_triggered(); - - void on_actionConfig_Folder_triggered(); - - void on_actionViewSelectedInstFolder_triggered(); - - void on_actionRefresh_triggered(); - - void on_actionViewCentralModsFolder_triggered(); - - void on_actionCheckUpdate_triggered(); - - void on_actionSettings_triggered(); - - void on_actionReportBug_triggered(); - - void on_actionNews_triggered(); - - void on_mainToolBar_visibilityChanged(bool); - - // void on_instanceView_customContextMenuRequested(const QPoint &pos); - - void on_actionLaunchInstance_triggered(); - - void on_actionDeleteInstance_triggered(); - - void on_actionRenameInstance_triggered(); - - void on_actionMakeDesktopShortcut_triggered(); - - void on_actionChangeInstMCVersion_triggered(); - - void on_actionEditInstMods_triggered(); - - void on_actionEditInstNotes_triggered(); - - void doLogin(const QString &errorMsg = ""); - void doLogin(QString username, QString password); - void doAutoLogin(); - - void onLoginComplete(); - - void onGameUpdateComplete(); - void onGameUpdateError(QString error); - - void taskStart(); - void taskEnd(); - - void on_actionChangeInstLWJGLVersion_triggered(); - - void instanceEnded(BaseInstance *instance); - - void on_actionInstanceSettings_triggered(); - - void assetsIndexStarted(); - void assetsFilesStarted(); - void assetsFilesProgress(int, int, int); - void assetsFailed(); - void assetsFinished(); - -public -slots: - void instanceActivated(QModelIndex); - - void instanceChanged(const QModelIndex ¤t, const QModelIndex &previous); - - void selectionBad(); - - void startTask(Task *task); - - void launchInstance(BaseInstance *inst, LoginResponse response); - -protected: - bool eventFilter(QObject *obj, QEvent *ev); - void setCatBackground(bool enabled); - -private: - Ui::MainWindow *ui; - KCategoryDrawer *drawer; - KCategorizedView *view; - InstanceProxyModel *proxymodel; - MinecraftProcess *proc; - ConsoleWindow *console; - OneSixAssets *assets_downloader; - LabeledToolButton *renameButton; - QToolButton *changeIconButton; - - BaseInstance *m_selectedInstance; - - // A pointer to the instance we are actively doing stuff with. - // This is set when the user launches an instance and is used to refer to that - // instance throughout the launching process. - BaseInstance *m_activeInst; - LoginResponse m_activeLogin; - - Task *m_versionLoadTask; - - QLabel *m_statusLeft; - QLabel *m_statusRight; -}; - -#endif // MAINWINDOW_H diff --git a/gui/mainwindow.ui b/gui/mainwindow.ui deleted file mode 100644 index 6f70fc98..00000000 --- a/gui/mainwindow.ui +++ /dev/null @@ -1,474 +0,0 @@ - - - MainWindow - - - - 0 - 0 - 688 - 650 - - - - MultiMC 5 - - - - :/icons/multimc/scalable/apps/multimc.svg:/icons/multimc/scalable/apps/multimc.svg - - - - - 0 - - - QLayout::SetDefaultConstraint - - - 0 - - - 0 - - - 0 - - - 0 - - - - - - Main Toolbar - - - false - - - Qt::TopToolBarArea - - - Qt::ToolButtonIconOnly - - - false - - - TopToolBarArea - - - false - - - - - - - - - - - - - - - - - - - - - true - - - Instance Toolbar - - - Qt::LeftToolBarArea|Qt::RightToolBarArea - - - - 80 - 80 - - - - Qt::ToolButtonIconOnly - - - false - - - RightToolBarArea - - - false - - - - - - - - - - - - - - - - - - - - :/icons/toolbar/new:/icons/toolbar/new - - - Add Instance - - - Add a new instance. - - - Add a new instance. - - - - - - :/icons/toolbar/viewfolder:/icons/toolbar/viewfolder - - - View Instance Folder - - - Open the instance folder in a file browser. - - - Open the instance folder in a file browser. - - - - - - :/icons/toolbar/refresh:/icons/toolbar/refresh - - - Refresh - - - Reload the instance list. - - - Reload the instance list. - - - - - - :/icons/toolbar/centralmods:/icons/toolbar/centralmods - - - View Central Mods Folder - - - Open the central mods folder in a file browser. - - - Open the central mods folder in a file browser. - - - - - - :/icons/toolbar/checkupdate:/icons/toolbar/checkupdate - - - Check for Updates - - - Check for new updates for MultiMC - - - Check for new updates for MultiMC - - - - - - :/icons/toolbar/settings:/icons/toolbar/settings - - - Settings - - - Change settings. - - - Change settings. - - - QAction::PreferencesRole - - - - - - :/icons/toolbar/bug:/icons/toolbar/bug - - - Report a Bug - - - Open the bug tracker to report a bug with MultiMC. - - - Open the bug tracker to report a bug with MultiMC. - - - - - - :/icons/toolbar/news:/icons/toolbar/news - - - News - - - Open the MultiMC dev blog to read news about MultiMC. - - - Open the MultiMC dev blog to read news about MultiMC. - - - - - - :/icons/toolbar/about:/icons/toolbar/about - - - About MultiMC - - - View information about MultiMC. - - - About MultiMC - - - QAction::AboutRole - - - - - Play - - - Launch the selected instance. - - - Launch the selected instance. - - - - - Instance Name - - - Rename the selected instance. - - - Rename the selected instance. - - - - - Change Group - - - Change the selected instance's group. - - - Change the selected instance's group. - - - - - true - - - - :/icons/instances/infinity:/icons/instances/infinity - - - Change Icon - - - Change the selected instance's icon. - - - Change the selected instance's icon. - - - true - - - - - Edit Notes - - - Edit the notes for the selected instance. - - - Edit the notes for the selected instance. - - - - - true - - - Settings - - - Change settings for the selected instance. - - - Change settings for the selected instance. - - - - - false - - - Make Shortcut - - - Make a shortcut on the desktop for the selected instance. - - - Make a shortcut on the desktop for the selected instance. - - - - - false - - - Manage Saves - - - Manage saves for the selected instance. - - - Manage saves for the selected instance. - - - - - Edit Mods - - - Edit the mods for the selected instance. - - - Edit the mods for the selected instance. - - - - - Change Version - - - Change the selected instance's Minecraft version. - - - Change the selected instance's Minecraft version. - - - - - false - - - Change LWJGL - - - Change the version of LWJGL for the selected instance to use. - - - Change the version of LWJGL for the selected instance to use. - - - - - Instance Folder - - - Open the selected instance's root folder in a file browser. - - - Open the selected instance's root folder in a file browser. - - - - - Delete - - - Delete the selected instance. - - - Delete the selected instance. - - - - - Config Folder - - - Open the instance's config folder - - - - - true - - - - :/icons/toolbar/cat:/icons/toolbar/cat - - - Meow - - - <html><head/><body><p align="center"><span style=" font-weight:600; color:#ff0004;">Catnarok!</span></p><p align="center">Or just a cat with a ball of yarn?</p><p align="center"><span style=" font-style:italic;">WHO KNOWS?!</span></p><p align="center"><img src=":/icons/instances/tnt"/></p></body></html> - - - - - - :/icons/toolbar/copy:/icons/toolbar/copy - - - Copy Instance - - - Copy the selected instance. - - - Add a new instance. - - - - - - - - - diff --git a/gui/newinstancedialog.cpp b/gui/newinstancedialog.cpp deleted file mode 100644 index c37db2ac..00000000 --- a/gui/newinstancedialog.cpp +++ /dev/null @@ -1,125 +0,0 @@ -/* Copyright 2013 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 -#include "newinstancedialog.h" -#include "ui_newinstancedialog.h" - -#include "logic/InstanceFactory.h" -#include "logic/BaseVersion.h" -#include "logic/lists/IconList.h" -#include "logic/lists/MinecraftVersionList.h" -#include "logic/tasks/Task.h" - -#include "gui/platform.h" -#include "versionselectdialog.h" -#include "ProgressDialog.h" -#include "IconPickerDialog.h" - -#include -#include - -NewInstanceDialog::NewInstanceDialog(QWidget *parent) - : QDialog(parent), ui(new Ui::NewInstanceDialog) -{ - MultiMCPlatform::fixWM_CLASS(this); - ui->setupUi(this); - resize(minimumSizeHint()); - layout()->setSizeConstraint(QLayout::SetFixedSize); - /* - if (!MinecraftVersionList::getMainList().isLoaded()) - { - TaskDialog *taskDlg = new TaskDialog(this); - Task *loadTask = MinecraftVersionList::getMainList().getLoadTask(); - loadTask->setParent(taskDlg); - taskDlg->exec(loadTask); - } - */ - setSelectedVersion(MMC->minecraftlist()->getLatestStable()); - InstIconKey = "infinity"; - ui->iconButton->setIcon(MMC->icons()->getIcon(InstIconKey)); -} - -NewInstanceDialog::~NewInstanceDialog() -{ - delete ui; -} - -void NewInstanceDialog::updateDialogState() -{ - ui->buttonBox->button(QDialogButtonBox::Ok) - ->setEnabled(!instName().isEmpty() && m_selectedVersion); -} - -void NewInstanceDialog::setSelectedVersion(BaseVersionPtr version) -{ - m_selectedVersion = version; - - if (m_selectedVersion) - { - ui->versionTextBox->setText(version->name()); - } - else - { - ui->versionTextBox->setText(""); - } - - updateDialogState(); -} - -QString NewInstanceDialog::instName() const -{ - return ui->instNameTextBox->text(); -} - -QString NewInstanceDialog::iconKey() const -{ - return InstIconKey; -} - -BaseVersionPtr NewInstanceDialog::selectedVersion() const -{ - return m_selectedVersion; -} - -void NewInstanceDialog::on_btnChangeVersion_clicked() -{ - VersionSelectDialog vselect(MMC->minecraftlist().get(), tr("Change Minecraft version"), - this); - vselect.exec(); - if (vselect.result() == QDialog::Accepted) - { - BaseVersionPtr version = vselect.selectedVersion(); - if (version) - setSelectedVersion(version); - } -} - -void NewInstanceDialog::on_iconButton_clicked() -{ - IconPickerDialog dlg(this); - dlg.exec(InstIconKey); - - if (dlg.result() == QDialog::Accepted) - { - InstIconKey = dlg.selectedIconKey; - ui->iconButton->setIcon(MMC->icons()->getIcon(InstIconKey)); - } -} - -void NewInstanceDialog::on_instNameTextBox_textChanged(const QString &arg1) -{ - updateDialogState(); -} diff --git a/gui/newinstancedialog.h b/gui/newinstancedialog.h deleted file mode 100644 index 4357c28d..00000000 --- a/gui/newinstancedialog.h +++ /dev/null @@ -1,55 +0,0 @@ -/* Copyright 2013 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 -#include "logic/BaseVersion.h" - -namespace Ui -{ -class NewInstanceDialog; -} - -class NewInstanceDialog : public QDialog -{ - Q_OBJECT - -public: - explicit NewInstanceDialog(QWidget *parent = 0); - ~NewInstanceDialog(); - - void updateDialogState(); - - void setSelectedVersion(BaseVersionPtr version); - - void loadVersionList(); - - QString instName() const; - QString iconKey() const; - BaseVersionPtr selectedVersion() const; - -private -slots: - void on_btnChangeVersion_clicked(); - void on_iconButton_clicked(); - void on_instNameTextBox_textChanged(const QString &arg1); - -private: - Ui::NewInstanceDialog *ui; - - BaseVersionPtr m_selectedVersion; - QString InstIconKey; -}; diff --git a/gui/newinstancedialog.ui b/gui/newinstancedialog.ui deleted file mode 100644 index 540176d5..00000000 --- a/gui/newinstancedialog.ui +++ /dev/null @@ -1,179 +0,0 @@ - - - NewInstanceDialog - - - Qt::ApplicationModal - - - - 0 - 0 - 220 - 234 - - - - New Instance - - - - :/icons/toolbar/new:/icons/toolbar/new - - - true - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - :/icons/instances/infinity:/icons/instances/infinity - - - - 80 - 80 - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - Name - - - - - - - Qt::Horizontal - - - - - - - - - Version: - - - - - - - true - - - - - - - ... - - - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - Qt::Horizontal - - - - - - - Qt::Horizontal - - - QDialogButtonBox::Cancel|QDialogButtonBox::Ok - - - - - - - - - - - buttonBox - accepted() - NewInstanceDialog - accept() - - - 248 - 254 - - - 157 - 274 - - - - - buttonBox - rejected() - NewInstanceDialog - reject() - - - 316 - 260 - - - 286 - 274 - - - - - diff --git a/gui/newmodeditwindow.ui b/gui/newmodeditwindow.ui deleted file mode 100644 index a7587d11..00000000 --- a/gui/newmodeditwindow.ui +++ /dev/null @@ -1,159 +0,0 @@ - - - Dialog - - - - 0 - 0 - 569 - 420 - - - - Dialog - - - - - - true - - - - 0 - 0 - - - - 2 - - - Qt::ElideNone - - - false - - - - Library - - - - - - - - - - Mods - - - - - - - - - - - &Add - - - - - - - &Remove - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - &View Folder - - - - - - - - - - Resource Pack - - - - - - - - - - - PushButton - - - - - - - PushButton - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - PushButton - - - - - - - - - - - - - false - - - QDialogButtonBox::Close - - - - - - - - diff --git a/gui/platform.h b/gui/platform.h deleted file mode 100644 index 5cf9ed80..00000000 --- a/gui/platform.h +++ /dev/null @@ -1,35 +0,0 @@ -/* Copyright 2013 MultiMC Contributors - * - * Authors: Orochimarufan - * - * 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. - */ - -#ifndef PLATFORM_H -#define PLATFORM_H - -/** - * @file platform.h - * This file contains platform-specific functions, tweaks and fixes. - */ - -#include - -class MultiMCPlatform -{ -public: - // X11 WM_CLASS - static void fixWM_CLASS(QWidget *widget); -}; - -#endif // PLATFORM_H diff --git a/gui/platform_other.cpp b/gui/platform_other.cpp deleted file mode 100644 index a41abe36..00000000 --- a/gui/platform_other.cpp +++ /dev/null @@ -1,27 +0,0 @@ -/* Copyright 2013 MultiMC Contributors - * - * Authors: Orochimarufan - * - * 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 -/** - * Stub for non-X11 platforms - * @brief MultiMCPlatform::fixWM_CLASS - * @param widget - */ -void MultiMCPlatform::fixWM_CLASS(QWidget *widget) -{ - Q_UNUSED(widget); -} diff --git a/gui/platform_x11.cpp b/gui/platform_x11.cpp deleted file mode 100644 index 0401e8bf..00000000 --- a/gui/platform_x11.cpp +++ /dev/null @@ -1,62 +0,0 @@ -/* Copyright 2013 MultiMC Contributors - * - * Authors: Orochimarufan - * - * 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 -#include -#include - -static QByteArray WM_CLASS = "MultiMC5\0MultiMC5"; - -template -static inline unsigned int XcbCallVoid(xcb_void_cookie_t (*func)(xcb_connection_t *, ArgTypes...), ArgTypes2... args...) -{ - return func(QX11Info::connection(), args...).sequence; -} - -static void getAtoms(size_t n, xcb_atom_t *atoms, const char *const names[], bool create) -{ - xcb_connection_t *conn = QX11Info::connection(); - xcb_intern_atom_cookie_t *cookies = (xcb_intern_atom_cookie_t *)malloc(sizeof(xcb_intern_atom_cookie_t) * 2); - for (size_t i = 0; i < n; ++i) - cookies[i] = xcb_intern_atom(conn, create, strlen(names[i]), names[i]); - memset(atoms, 0, sizeof(xcb_atom_t) * n); - for (size_t i = 0; i < n; ++i) - { - xcb_intern_atom_reply_t *r = xcb_intern_atom_reply(conn, cookies[i], 0); - if (r) - { - atoms[i] = r->atom; - free(r); - } - } - free(cookies); -} - -static inline xcb_atom_t getAtom(const char *name, bool create=false) -{ - xcb_atom_t atom; - getAtoms(1, &atom, &name, create); - return atom; -} - -void MultiMCPlatform::fixWM_CLASS(QWidget *widget) -{ - static const xcb_atom_t atom = getAtom("WM_CLASS"); - XcbCallVoid(xcb_change_property, XCB_PROP_MODE_REPLACE, - widget->winId(), atom, XCB_ATOM_STRING, 8, WM_CLASS.count(), - WM_CLASS.constData()); -} diff --git a/gui/settingsdialog.cpp b/gui/settingsdialog.cpp deleted file mode 100644 index bf331fc0..00000000 --- a/gui/settingsdialog.cpp +++ /dev/null @@ -1,256 +0,0 @@ -/* Copyright 2013 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 -#include "settingsdialog.h" -#include "ui_settingsdialog.h" -#include "logic/JavaUtils.h" -#include "logic/NagUtils.h" -#include "gui/versionselectdialog.h" -#include "gui/platform.h" -#include "gui/CustomMessageBox.h" -#include "logic/lists/JavaVersionList.h" - -#include -#include -#include -#include -#include - -SettingsDialog::SettingsDialog(QWidget *parent) : QDialog(parent), ui(new Ui::SettingsDialog) -{ - MultiMCPlatform::fixWM_CLASS(this); - ui->setupUi(this); - ui->sortingModeGroup->setId(ui->sortByNameBtn, Sort_Name); - ui->sortingModeGroup->setId(ui->sortLastLaunchedBtn, Sort_LastLaunch); - - loadSettings(MMC->settings().get()); - updateCheckboxStuff(); -} - -SettingsDialog::~SettingsDialog() -{ - delete ui; -} -void SettingsDialog::showEvent(QShowEvent *ev) -{ - QDialog::showEvent(ev); - adjustSize(); -} - -void SettingsDialog::updateCheckboxStuff() -{ - ui->windowWidthSpinBox->setEnabled(!ui->maximizedCheckBox->isChecked()); - ui->windowHeightSpinBox->setEnabled(!ui->maximizedCheckBox->isChecked()); -} - -void SettingsDialog::on_instDirBrowseBtn_clicked() -{ - QString raw_dir = QFileDialog::getExistingDirectory(this, tr("Instance Directory"), - ui->instDirTextBox->text()); - QString cooked_dir = NormalizePath(raw_dir); - - // do not allow current dir - it's dirty. Do not allow dirs that don't exist - if (!cooked_dir.isEmpty() && QDir(cooked_dir).exists()) - { - ui->instDirTextBox->setText(cooked_dir); - } -} - -void SettingsDialog::on_modsDirBrowseBtn_clicked() -{ - QString raw_dir = QFileDialog::getExistingDirectory(this, tr("Mods Directory"), - ui->modsDirTextBox->text()); - QString cooked_dir = NormalizePath(raw_dir); - - // do not allow current dir - it's dirty. Do not allow dirs that don't exist - if (!cooked_dir.isEmpty() && QDir(cooked_dir).exists()) - { - ui->modsDirTextBox->setText(cooked_dir); - } -} - -void SettingsDialog::on_lwjglDirBrowseBtn_clicked() -{ - QString raw_dir = QFileDialog::getExistingDirectory(this, tr("LWJGL Directory"), - ui->lwjglDirTextBox->text()); - QString cooked_dir = NormalizePath(raw_dir); - - // do not allow current dir - it's dirty. Do not allow dirs that don't exist - if (!cooked_dir.isEmpty() && QDir(cooked_dir).exists()) - { - ui->lwjglDirTextBox->setText(cooked_dir); - } -} - -void SettingsDialog::on_compatModeCheckBox_clicked(bool checked) -{ - Q_UNUSED(checked); - updateCheckboxStuff(); -} - -void SettingsDialog::on_maximizedCheckBox_clicked(bool checked) -{ - Q_UNUSED(checked); - updateCheckboxStuff(); -} - -void SettingsDialog::on_buttonBox_accepted() -{ - applySettings(MMC->settings().get()); -} - -void SettingsDialog::applySettings(SettingsObject *s) -{ - // Special cases - - // Warn about dev builds. - if (!ui->devBuildsCheckBox->isChecked()) - { - s->set("UseDevBuilds", false); - } - else if (!s->get("UseDevBuilds").toBool()) - { - auto response = CustomMessageBox::selectable(this, tr("Development builds"), - tr("Development builds contain experimental features " - "and may be unstable. Are you sure you want to enable them?"), - QMessageBox::Question, QMessageBox::Yes | QMessageBox::No)->exec(); - if (response == QMessageBox::Yes) - { - s->set("UseDevBuilds", true); - } - } - - // Updates - s->set("AutoUpdate", ui->autoUpdateCheckBox->isChecked()); - - // Folders - // TODO: Offer to move instances to new instance folder. - s->set("InstanceDir", ui->instDirTextBox->text()); - s->set("CentralModsDir", ui->modsDirTextBox->text()); - s->set("LWJGLDir", ui->lwjglDirTextBox->text()); - - // Console - s->set("ShowConsole", ui->showConsoleCheck->isChecked()); - s->set("AutoCloseConsole", ui->autoCloseConsoleCheck->isChecked()); - - // Window Size - s->set("LaunchMaximized", ui->maximizedCheckBox->isChecked()); - s->set("MinecraftWinWidth", ui->windowWidthSpinBox->value()); - s->set("MinecraftWinHeight", ui->windowHeightSpinBox->value()); - - // Auto Login - s->set("AutoLogin", ui->autoLoginCheckBox->isChecked()); - - // Memory - s->set("MinMemAlloc", ui->minMemSpinBox->value()); - s->set("MaxMemAlloc", ui->maxMemSpinBox->value()); - s->set("PermGen", ui->permGenSpinBox->value()); - - // Java Settings - s->set("JavaPath", ui->javaPathTextBox->text()); - s->set("JvmArgs", ui->jvmArgsTextBox->text()); - NagUtils::checkJVMArgs(s->get("JvmArgs").toString(), this->parentWidget()); - - // Custom Commands - s->set("PreLaunchCommand", ui->preLaunchCmdTextBox->text()); - s->set("PostExitCommand", ui->postExitCmdTextBox->text()); - - auto sortMode = (InstSortMode) ui->sortingModeGroup->checkedId(); - switch(sortMode) - { - case Sort_LastLaunch: - s->set("InstSortMode", "LastLaunch"); - break; - case Sort_Name: - default: - s->set("InstSortMode", "Name"); - break; - } - - s->set("PostExitCommand", ui->postExitCmdTextBox->text()); -} - -void SettingsDialog::loadSettings(SettingsObject *s) -{ - // Updates - ui->autoUpdateCheckBox->setChecked(s->get("AutoUpdate").toBool()); - ui->devBuildsCheckBox->setChecked(s->get("UseDevBuilds").toBool()); - - // Folders - ui->instDirTextBox->setText(s->get("InstanceDir").toString()); - ui->modsDirTextBox->setText(s->get("CentralModsDir").toString()); - ui->lwjglDirTextBox->setText(s->get("LWJGLDir").toString()); - - // Console - ui->showConsoleCheck->setChecked(s->get("ShowConsole").toBool()); - ui->autoCloseConsoleCheck->setChecked(s->get("AutoCloseConsole").toBool()); - - // Window Size - ui->maximizedCheckBox->setChecked(s->get("LaunchMaximized").toBool()); - ui->windowWidthSpinBox->setValue(s->get("MinecraftWinWidth").toInt()); - ui->windowHeightSpinBox->setValue(s->get("MinecraftWinHeight").toInt()); - - // Auto Login - ui->autoLoginCheckBox->setChecked(s->get("AutoLogin").toBool()); - - // Memory - ui->minMemSpinBox->setValue(s->get("MinMemAlloc").toInt()); - ui->maxMemSpinBox->setValue(s->get("MaxMemAlloc").toInt()); - ui->permGenSpinBox->setValue(s->get("PermGen").toInt()); - - QString sortMode = s->get("InstSortMode").toString(); - - if(sortMode == "LastLaunch") - { - ui->sortLastLaunchedBtn->setChecked(true); - } - else - { - ui->sortByNameBtn->setChecked(true); - } - - // Java Settings - ui->javaPathTextBox->setText(s->get("JavaPath").toString()); - ui->jvmArgsTextBox->setText(s->get("JvmArgs").toString()); - - // Custom Commands - ui->preLaunchCmdTextBox->setText(s->get("PreLaunchCommand").toString()); - ui->postExitCmdTextBox->setText(s->get("PostExitCommand").toString()); -} - -void SettingsDialog::on_pushButton_clicked() -{ - JavaVersionPtr java; - - VersionSelectDialog vselect(MMC->javalist().get(), tr("Select a Java version"), this, true); - vselect.setResizeOn(2); - vselect.exec(); - - if (vselect.result() == QDialog::Accepted && vselect.selectedVersion()) - { - java = std::dynamic_pointer_cast(vselect.selectedVersion()); - ui->javaPathTextBox->setText(java->path); - } -} - -void SettingsDialog::on_btnBrowse_clicked() -{ - QString dir = QFileDialog::getOpenFileName(this, tr("Find Java executable")); - if (!dir.isNull()) - { - ui->javaPathTextBox->setText(dir); - } -} diff --git a/gui/settingsdialog.h b/gui/settingsdialog.h deleted file mode 100644 index a8dfb1c6..00000000 --- a/gui/settingsdialog.h +++ /dev/null @@ -1,64 +0,0 @@ -/* Copyright 2013 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. - */ - -#ifndef SETTINGSDIALOG_H -#define SETTINGSDIALOG_H - -#include - -class SettingsObject; - -namespace Ui { -class SettingsDialog; -} - -class SettingsDialog : public QDialog -{ - Q_OBJECT - -public: - explicit SettingsDialog(QWidget *parent = 0); - ~SettingsDialog(); - - void updateCheckboxStuff(); - - void applySettings(SettingsObject *s); - void loadSettings(SettingsObject* s); - -protected: - virtual void showEvent ( QShowEvent* ); - -private slots: - void on_instDirBrowseBtn_clicked(); - - void on_modsDirBrowseBtn_clicked(); - - void on_lwjglDirBrowseBtn_clicked(); - - void on_compatModeCheckBox_clicked(bool checked); - - void on_maximizedCheckBox_clicked(bool checked); - - void on_buttonBox_accepted(); - - void on_pushButton_clicked(); - - void on_btnBrowse_clicked(); - -private: - Ui::SettingsDialog *ui; -}; - -#endif // SETTINGSDIALOG_H diff --git a/gui/settingsdialog.ui b/gui/settingsdialog.ui deleted file mode 100644 index bf173b1b..00000000 --- a/gui/settingsdialog.ui +++ /dev/null @@ -1,569 +0,0 @@ - - - SettingsDialog - - - - 0 - 0 - 502 - 599 - - - - - 0 - 0 - - - - Settings - - - - :/icons/toolbar/settings:/icons/toolbar/settings - - - true - - - - - - QTabWidget::Rounded - - - 0 - - - - General - - - - - - true - - - Sorting Mode - - - - - - By last launched - - - sortingModeGroup - - - - - - - By name - - - sortingModeGroup - - - - - - - - - - Update Settings - - - - - - Use development builds? - - - - - - - Check for updates when MultiMC starts? - - - - - - - - - - Folders - - - - - - Instances: - - - - - - - - - - ... - - - - - - - Mods: - - - - - - - - - - ... - - - - - - - LWJGL: - - - - - - - - - - ... - - - - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - - Minecraft - - - - - - Window Size - - - - - - Start Minecraft maximized? - - - - - - - - - Window height: - - - - - - - Window width: - - - - - - - 854 - - - 65536 - - - 1 - - - 854 - - - - - - - 480 - - - 65536 - - - 480 - - - - - - - - - - - - Console Settings - - - - - - Show console while the game is running? - - - - - - - Automatically close console when the game quits? - - - - - - - - - - Login automatically when an instance icon is double clicked? - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - - Java - - - - - - Memory - - - - - - 512 - - - 65536 - - - 128 - - - 1024 - - - - - - - Minimum memory allocation: - - - - - - - Maximum memory allocation: - - - - - - - 256 - - - 65536 - - - 128 - - - 256 - - - - - - - PermGen: - - - - - - - 64 - - - 999999999 - - - 8 - - - 64 - - - - - - - - - - Java Settings - - - - - - - 0 - 0 - - - - Java path: - - - - - - - - 0 - 0 - - - - JVM arguments: - - - - - - - - 0 - 0 - - - - Browse... - - - - - - - - - - - 0 - 0 - - - - Auto-detect... - - - - - - - - - - - - - Custom Commands - - - - - - Post-exit command: - - - - - - - Pre-launch command: - - - - - - - - - - - - - - - - - 0 - 0 - - - - Pre-launch command runs before the instance launches and post-exit command runs after it exits. Both will be run in MultiMC's working directory with INST_ID, INST_DIR, and INST_NAME as environment variables. - - - Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop - - - true - - - - - - - - - - - Qt::Horizontal - - - QDialogButtonBox::Cancel|QDialogButtonBox::Ok - - - - - - - settingsTabs - buttonBox - sortLastLaunchedBtn - sortByNameBtn - devBuildsCheckBox - autoUpdateCheckBox - instDirTextBox - modsDirTextBox - lwjglDirTextBox - instDirBrowseBtn - modsDirBrowseBtn - lwjglDirBrowseBtn - maximizedCheckBox - windowWidthSpinBox - windowHeightSpinBox - showConsoleCheck - autoCloseConsoleCheck - autoLoginCheckBox - minMemSpinBox - maxMemSpinBox - permGenSpinBox - javaPathTextBox - pushButton - btnBrowse - jvmArgsTextBox - preLaunchCmdTextBox - postExitCmdTextBox - - - - - - - buttonBox - accepted() - SettingsDialog - accept() - - - 257 - 410 - - - 157 - 274 - - - - - buttonBox - rejected() - SettingsDialog - reject() - - - 325 - 410 - - - 286 - 274 - - - - - - - - diff --git a/gui/versionselectdialog.cpp b/gui/versionselectdialog.cpp deleted file mode 100644 index 8fa62f75..00000000 --- a/gui/versionselectdialog.cpp +++ /dev/null @@ -1,110 +0,0 @@ -/* Copyright 2013 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 "versionselectdialog.h" -#include "ui_versionselectdialog.h" - -#include - -#include - -#include -#include "gui/platform.h" - -#include -#include -#include - -VersionSelectDialog::VersionSelectDialog(BaseVersionList *vlist, QString title, QWidget *parent, bool cancelable) - : QDialog(parent), ui(new Ui::VersionSelectDialog) -{ - MultiMCPlatform::fixWM_CLASS(this); - ui->setupUi(this); - setWindowModality(Qt::WindowModal); - setWindowTitle(title); - - m_vlist = vlist; - - m_proxyModel = new QSortFilterProxyModel(this); - m_proxyModel->setSourceModel(vlist); - - ui->listView->setModel(m_proxyModel); - ui->listView->header()->setSectionResizeMode(QHeaderView::ResizeToContents); - ui->listView->header()->setSectionResizeMode(resizeOnColumn, QHeaderView::Stretch); - - if(!cancelable) - { - ui->buttonBox->button(QDialogButtonBox::Cancel)->setEnabled(false); - } -} - -VersionSelectDialog::~VersionSelectDialog() -{ - delete ui; -} - -void VersionSelectDialog::setResizeOn(int column) -{ - ui->listView->header()->setSectionResizeMode(resizeOnColumn, QHeaderView::ResizeToContents); - resizeOnColumn = column; - ui->listView->header()->setSectionResizeMode(resizeOnColumn, QHeaderView::Stretch); -} - -int VersionSelectDialog::exec() -{ - QDialog::open(); - if (!m_vlist->isLoaded()) - loadList(); - return QDialog::exec(); -} - -void VersionSelectDialog::loadList() -{ - ProgressDialog *taskDlg = new ProgressDialog(this); - Task *loadTask = m_vlist->getLoadTask(); - loadTask->setParent(taskDlg); - taskDlg->exec(loadTask); -} - -BaseVersionPtr VersionSelectDialog::selectedVersion() const -{ - auto currentIndex = ui->listView->selectionModel()->currentIndex(); - auto variant = m_proxyModel->data(currentIndex, BaseVersionList::VersionPointerRole); - return variant.value(); -} - -void VersionSelectDialog::on_refreshButton_clicked() -{ - loadList(); -} - -void VersionSelectDialog::setFilter(int column, QString filter) -{ - m_proxyModel->setFilterKeyColumn(column); - m_proxyModel->setFilterFixedString(filter); - /* - QStringList filteredTypes; - if (!ui->filterSnapshotsCheckbox->isChecked()) - filteredTypes += "Snapshot"; - if (!ui->filterMCNostalgiaCheckbox->isChecked()) - filteredTypes += "Nostalgia"; - - QString regexStr = "^.*$"; - if (filteredTypes.length() > 0) - regexStr = QString("^((?!%1).)*$").arg(filteredTypes.join('|')); - - QLOG_DEBUG() << "Filter:" << regexStr; - */ -} diff --git a/gui/versionselectdialog.h b/gui/versionselectdialog.h deleted file mode 100644 index 319caeca..00000000 --- a/gui/versionselectdialog.h +++ /dev/null @@ -1,61 +0,0 @@ -/* Copyright 2013 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. - */ - -#ifndef VERSIONSELECTDIALOG_H -#define VERSIONSELECTDIALOG_H - -#include - -#include -#include "logic/BaseVersion.h" - -class BaseVersionList; - -namespace Ui -{ -class VersionSelectDialog; -} - -class VersionSelectDialog : public QDialog -{ - Q_OBJECT - -public: - explicit VersionSelectDialog(BaseVersionList *vlist, QString title, QWidget *parent = 0, bool cancelable = true); - ~VersionSelectDialog(); - - virtual int exec(); - - //! Starts a task that loads the list. - void loadList(); - - BaseVersionPtr selectedVersion() const; - - void setFilter(int column, QString filter); - void setResizeOn(int column); - -private slots: - void on_refreshButton_clicked(); -private: - Ui::VersionSelectDialog *ui; - - BaseVersionList *m_vlist; - - QSortFilterProxyModel *m_proxyModel; - - int resizeOnColumn = 0; -}; - -#endif // VERSIONSELECTDIALOG_H diff --git a/gui/versionselectdialog.ui b/gui/versionselectdialog.ui deleted file mode 100644 index 222f29cf..00000000 --- a/gui/versionselectdialog.ui +++ /dev/null @@ -1,103 +0,0 @@ - - - VersionSelectDialog - - - - 0 - 0 - 400 - 347 - - - - Dialog - - - - - - Qt::ScrollBarAlwaysOff - - - true - - - false - - - false - - - true - - - true - - - false - - - - - - - - - Reloads the version list. - - - &Refresh - - - - - - - Qt::Horizontal - - - QDialogButtonBox::Cancel|QDialogButtonBox::Ok - - - - - - - - - - - buttonBox - accepted() - VersionSelectDialog - accept() - - - 257 - 290 - - - 157 - 274 - - - - - buttonBox - rejected() - VersionSelectDialog - reject() - - - 325 - 290 - - - 286 - 274 - - - - - diff --git a/gui/widgets/InstanceDelegate.cpp b/gui/widgets/InstanceDelegate.cpp new file mode 100644 index 00000000..487fed61 --- /dev/null +++ b/gui/widgets/InstanceDelegate.cpp @@ -0,0 +1,246 @@ +/* Copyright 2013 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 "InstanceDelegate.h" +#include +#include +#include +#include +#include + +// Origin: Qt +static void viewItemTextLayout ( QTextLayout &textLayout, int lineWidth, qreal &height, qreal &widthUsed ) +{ + height = 0; + widthUsed = 0; + textLayout.beginLayout(); + QString str = textLayout.text(); + while ( true ) + { + QTextLine line = textLayout.createLine(); + if ( !line.isValid() ) + break; + if(line.textLength() == 0) + break; + line.setLineWidth ( lineWidth ); + line.setPosition ( QPointF ( 0, height ) ); + height += line.height(); + widthUsed = qMax ( widthUsed, line.naturalTextWidth() ); + } + textLayout.endLayout(); +} + +#define QFIXED_MAX (INT_MAX/256) + +ListViewDelegate::ListViewDelegate ( QObject* parent ) : QStyledItemDelegate ( parent ) +{ + +} + +void drawSelectionRect(QPainter *painter, const QStyleOptionViewItemV4 &option, const QRect &rect) +{ + if ((option.state & QStyle::State_Selected)) + painter->fillRect ( rect, option.palette.brush ( QPalette::Highlight ) ); + else + { + QColor backgroundColor = option.palette.color(QPalette::Background); + backgroundColor.setAlpha(160); + painter->fillRect ( rect, QBrush(backgroundColor) ); + } + +} + +void drawFocusRect(QPainter *painter, const QStyleOptionViewItemV4 &option, const QRect &rect) +{ + if (!(option.state & QStyle::State_HasFocus)) + return; + QStyleOptionFocusRect opt; + opt.direction = option.direction; + opt.fontMetrics = option.fontMetrics; + opt.palette = option.palette; + opt.rect = rect; + //opt.state = option.state | QStyle::State_KeyboardFocusChange | QStyle::State_Item; + auto col = option.state & QStyle::State_Selected ? QPalette::Highlight : QPalette::Base; + opt.backgroundColor = option.palette.color(col); + // Apparently some widget styles expect this hint to not be set + painter->setRenderHint(QPainter::Antialiasing, false); + + QStyle *style = option.widget ? option.widget->style() : QApplication::style(); + + style->drawPrimitive(QStyle::PE_FrameFocusRect, &opt, painter, option.widget); + + painter->setRenderHint(QPainter::Antialiasing); +} + +static QSize viewItemTextSize ( const QStyleOptionViewItemV4 *option ) +{ + QStyle *style = option->widget ? option->widget->style() : QApplication::style(); + QTextOption textOption; + textOption.setWrapMode ( QTextOption::WrapAtWordBoundaryOrAnywhere ); + QTextLayout textLayout; + textLayout.setTextOption ( textOption ); + textLayout.setFont ( option->font ); + textLayout.setText ( option->text ); + const int textMargin = style->pixelMetric ( QStyle::PM_FocusFrameHMargin, option, option->widget ) + 1; + QRect bounds ( 0,0,100 - 2*textMargin,600 ); + qreal height = 0, widthUsed = 0; + viewItemTextLayout ( textLayout, bounds.width(), height, widthUsed ); + const QSize size ( qCeil ( widthUsed ), qCeil ( height ) ); + return QSize ( size.width() + 2 * textMargin, size.height() ); +} + +void ListViewDelegate::paint ( QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index ) const +{ + QStyleOptionViewItemV4 opt = option; + initStyleOption ( &opt, index ); + painter->save(); + painter->setClipRect ( opt.rect ); + + opt.features |= QStyleOptionViewItem::WrapText; + opt.text = index.data().toString(); + opt.textElideMode = Qt::ElideRight; + opt.displayAlignment = Qt::AlignTop | Qt::AlignHCenter; + + QStyle *style = opt.widget ? opt.widget->style() : QApplication::style(); + + //const int iconSize = style->pixelMetric(QStyle::PM_IconViewIconSize); + const int iconSize = 48; + QRect iconbox = opt.rect; + const int textMargin = style->pixelMetric ( QStyle::PM_FocusFrameHMargin, 0, opt.widget ) + 1; + QRect textRect = opt.rect; + QRect textHighlightRect = textRect; + // clip the decoration on top, remove width padding + textRect.adjust ( textMargin,iconSize + textMargin + 5,-textMargin,0 ); + + textHighlightRect.adjust ( 0,iconSize + 5,0,0 ); + + // draw background + { + QSize textSize = viewItemTextSize ( &opt ); + QPalette::ColorGroup cg; + QStyleOptionViewItemV4 opt2(opt); + + if((opt.widget && opt.widget->isEnabled()) || (opt.state & QStyle::State_Enabled)) + { + if(! ( opt.state & QStyle::State_Active )) + cg = QPalette::Inactive; + else + cg = QPalette::Normal; + } + else + { + cg = QPalette::Disabled; + } + opt2.palette.setCurrentColorGroup(cg); + + // fill in background, if any + if ( opt.backgroundBrush.style() != Qt::NoBrush ) + { + QPointF oldBO = painter->brushOrigin(); + painter->setBrushOrigin ( opt.rect.topLeft() ); + painter->fillRect ( opt.rect, opt.backgroundBrush ); + painter->setBrushOrigin ( oldBO ); + } + + if ( opt.showDecorationSelected ) + { + drawSelectionRect(painter,opt2, opt.rect); + drawFocusRect(painter,opt2, opt.rect); + //painter->fillRect ( opt.rect, opt.palette.brush ( cg, QPalette::Highlight ) ); + } + else + { + + //if ( opt.state & QStyle::State_Selected ) + { + //QRect textRect = subElementRect ( QStyle::SE_ItemViewItemText, opt, opt.widget ); + //painter->fillRect ( textHighlightRect, opt.palette.brush ( cg, QPalette::Highlight ) ); + drawSelectionRect(painter,opt2, textHighlightRect); + drawFocusRect(painter,opt2, textHighlightRect); + } + } + } + + // draw the icon + { + QIcon::Mode mode = QIcon::Normal; + if ( ! ( opt.state & QStyle::State_Enabled ) ) + mode = QIcon::Disabled; + else if ( opt.state & QStyle::State_Selected ) + mode = QIcon::Selected; + QIcon::State state = opt.state & QStyle::State_Open ? QIcon::On : QIcon::Off; + + iconbox.setHeight ( iconSize ); + opt.icon.paint ( painter, iconbox, Qt::AlignCenter, mode, state ); + } + // set the text colors + QPalette::ColorGroup cg = opt.state & QStyle::State_Enabled ? QPalette::Normal : QPalette::Disabled; + if ( cg == QPalette::Normal && ! ( opt.state & QStyle::State_Active ) ) + cg = QPalette::Inactive; + if ( opt.state & QStyle::State_Selected ) + { + painter->setPen ( opt.palette.color ( cg, QPalette::HighlightedText ) ); + } + else + { + painter->setPen ( opt.palette.color ( cg, QPalette::Text ) ); + } + + // draw the text + QTextOption textOption; + textOption.setWrapMode ( QTextOption::WrapAtWordBoundaryOrAnywhere ); + textOption.setTextDirection ( opt.direction ); + textOption.setAlignment ( QStyle::visualAlignment ( opt.direction, opt.displayAlignment ) ); + QTextLayout textLayout; + textLayout.setTextOption ( textOption ); + textLayout.setFont ( opt.font ); + textLayout.setText ( opt.text ); + + qreal width, height; + viewItemTextLayout ( textLayout, textRect.width(), height, width ); + + const int lineCount = textLayout.lineCount(); + + const QRect layoutRect = QStyle::alignedRect ( opt.direction, opt.displayAlignment, QSize ( textRect.width(), int ( height ) ), textRect ); + const QPointF position = layoutRect.topLeft(); + for ( int i = 0; i < lineCount; ++i ) + { + const QTextLine line = textLayout.lineAt ( i ); + line.draw ( painter, position ); + } + + painter->restore(); +} + + +QSize ListViewDelegate::sizeHint ( const QStyleOptionViewItem & option, const QModelIndex & index ) const +{ + QStyleOptionViewItemV4 opt = option; + initStyleOption ( &opt, index ); + opt.features |= QStyleOptionViewItem::WrapText; + opt.text = index.data().toString(); + opt.textElideMode = Qt::ElideRight; + opt.displayAlignment = Qt::AlignTop | Qt::AlignHCenter; + + QStyle *style = opt.widget ? opt.widget->style() : QApplication::style(); + const int textMargin = style->pixelMetric ( QStyle::PM_FocusFrameHMargin, &option, opt.widget ) + 1; + int height = 48 + textMargin * 2 + 5; // TODO: turn constants into variables + QSize szz = viewItemTextSize ( &opt ); + height += szz.height(); + // FIXME: maybe the icon items could scale and keep proportions? + QSize sz ( 100,height ); + return sz; +} + diff --git a/gui/widgets/InstanceDelegate.h b/gui/widgets/InstanceDelegate.h new file mode 100644 index 00000000..6f924405 --- /dev/null +++ b/gui/widgets/InstanceDelegate.h @@ -0,0 +1,27 @@ +/* Copyright 2013 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 + +class ListViewDelegate : public QStyledItemDelegate +{ +public: + explicit ListViewDelegate ( QObject* parent = 0 ); +protected: + void paint ( QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index ) const; + QSize sizeHint ( const QStyleOptionViewItem & option, const QModelIndex & index ) const; +}; diff --git a/gui/widgets/LabeledToolButton.cpp b/gui/widgets/LabeledToolButton.cpp new file mode 100644 index 00000000..fe3cac45 --- /dev/null +++ b/gui/widgets/LabeledToolButton.cpp @@ -0,0 +1,86 @@ +/* Copyright 2013 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 +#include +#include +#include +#include "LabeledToolButton.h" +#include + +/* + * + * Tool Button with a label on it, instead of the normal text rendering + * + */ + +LabeledToolButton::LabeledToolButton(QWidget * parent) + : QToolButton(parent) + , m_label(new QLabel(this)) +{ + //QToolButton::setText(" "); + m_label->setWordWrap(true); + m_label->setMouseTracking(false); + m_label->setAlignment(Qt::AlignCenter); + m_label->setTextInteractionFlags(Qt::NoTextInteraction); + // somehow, this makes word wrap work in the QLabel. yay. + m_label->setMinimumWidth(100); +} + +QString LabeledToolButton::text() const +{ + return m_label->text(); +} + +void LabeledToolButton::setText(const QString & text) +{ + m_label->setText(text); +} + +/*! + \reimp +*/ +QSize LabeledToolButton::sizeHint() const +{ + /* + Q_D(const QToolButton); + if (d->sizeHint.isValid()) + return d->sizeHint; + */ + ensurePolished(); + + int w = 0, h = 0; + QStyleOptionToolButton opt; + initStyleOption(&opt); + QSize sz =m_label->sizeHint(); + w = sz.width(); + h = sz.height(); + + opt.rect.setSize(QSize(w, h)); // PM_MenuButtonIndicator depends on the height + if (popupMode() == MenuButtonPopup) + w += style()->pixelMetric(QStyle::PM_MenuButtonIndicator, &opt, this); + + QSize rawSize = style()->sizeFromContents(QStyle::CT_ToolButton, &opt, QSize(w, h), this); + QSize sizeHint = rawSize.expandedTo(QApplication::globalStrut()); + return sizeHint; +} + + + +void LabeledToolButton::resizeEvent(QResizeEvent * event) +{ + m_label->setGeometry(QRect(4, 4, width()-8, height()-8)); + QWidget::resizeEvent(event); +} diff --git a/gui/widgets/LabeledToolButton.h b/gui/widgets/LabeledToolButton.h new file mode 100644 index 00000000..b417f814 --- /dev/null +++ b/gui/widgets/LabeledToolButton.h @@ -0,0 +1,37 @@ +/* Copyright 2013 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 +#include + +class QLabel; + +class LabeledToolButton : public QToolButton +{ + Q_OBJECT + + QLabel * m_label; + +public: + LabeledToolButton(QWidget * parent = 0); + + QString text() const; + void setText(const QString & text); + virtual QSize sizeHint() const; +protected: + void resizeEvent(QResizeEvent * event); +}; diff --git a/gui/widgets/MCModInfoFrame.cpp b/gui/widgets/MCModInfoFrame.cpp new file mode 100644 index 00000000..ad167bc9 --- /dev/null +++ b/gui/widgets/MCModInfoFrame.cpp @@ -0,0 +1,111 @@ +/* Copyright 2013 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 +#include + +#include "MCModInfoFrame.h" +#include "ui_MCModInfoFrame.h" +#include "gui/dialogs/CustomMessageBox.h" + +void MCModInfoFrame::updateWithMod(Mod &m) +{ + if(m.type() == m.MOD_FOLDER) + { + clear(); + return; + } + + QString text = ""; + QString name = ""; + if(m.name().isEmpty()) name = m.id(); + else name = m.name(); + + if(m.homeurl().isEmpty()) text = name; + else text = "" + name + ""; + if(!m.authors().isEmpty()) text += " by " + m.authors(); + + setModText(text); + + if(m.description().isEmpty()) + { + setModDescription(tr("No description provided in mcmod.info")); + } + else + { + setModDescription(m.description()); + } +} + +void MCModInfoFrame::clear() +{ + setModText(tr("Select a mod to view title and authors...")); + setModDescription(tr("Select a mod to view description...")); +} + +MCModInfoFrame::MCModInfoFrame(QWidget *parent) : + QFrame(parent), + ui(new Ui::MCModInfoFrame) +{ + ui->setupUi(this); +} + +MCModInfoFrame::~MCModInfoFrame() +{ + delete ui; +} + +void MCModInfoFrame::setModText(QString text) +{ + ui->label_ModText->setText(text); +} + +void MCModInfoFrame::setModDescription(QString text) +{ + ui->label_ModDescription->setToolTip(""); + QString intermediatetext = text.trimmed(); + bool prev(false); + QChar rem('\n'); + QString finaltext; + finaltext.reserve(intermediatetext.size()); + foreach(const QChar& c, intermediatetext) + { + if(c == rem && prev){ + continue; + } + prev = c == rem; + finaltext += c; + } + QString labeltext; + labeltext.reserve(300); + if(finaltext.length() > 290) + { + ui->label_ModDescription->setOpenExternalLinks(false); + ui->label_ModDescription->setTextFormat(Qt::TextFormat::RichText); + desc = text; + labeltext.append("" + finaltext.left(287) + "..."); + QObject::connect(ui->label_ModDescription, &QLabel::linkActivated, this, &MCModInfoFrame::modDescEllipsisHandler); + } + else + { + ui->label_ModDescription->setTextFormat(Qt::TextFormat::PlainText); + labeltext.append(finaltext); + } + ui->label_ModDescription->setText(labeltext); +} +void MCModInfoFrame::modDescEllipsisHandler(const QString &link) +{ + CustomMessageBox::selectable(this, tr(""), desc)->show(); +} diff --git a/gui/widgets/MCModInfoFrame.h b/gui/widgets/MCModInfoFrame.h new file mode 100644 index 00000000..54c5d674 --- /dev/null +++ b/gui/widgets/MCModInfoFrame.h @@ -0,0 +1,46 @@ +/* Copyright 2013 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 +#include "logic/Mod.h" + +namespace Ui +{ +class MCModInfoFrame; +} + +class MCModInfoFrame : public QFrame +{ + Q_OBJECT + +public: + explicit MCModInfoFrame(QWidget *parent = 0); + ~MCModInfoFrame(); + + void setModText(QString text); + void setModDescription(QString text); + + void updateWithMod(Mod &m); + void clear(); + +public slots: + void modDescEllipsisHandler(const QString& link ); + +private: + Ui::MCModInfoFrame *ui; + QString desc; +}; diff --git a/gui/widgets/MCModInfoFrame.ui b/gui/widgets/MCModInfoFrame.ui new file mode 100644 index 00000000..60e0a65c --- /dev/null +++ b/gui/widgets/MCModInfoFrame.ui @@ -0,0 +1,68 @@ + + + MCModInfoFrame + + + + 0 + 0 + 527 + 113 + + + + + 0 + 0 + + + + + 16777215 + 120 + + + + Frame + + + + + + Select a mod to view title and authors... + + + Qt::RichText + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop + + + true + + + true + + + + + + + Select a mod to view description... + + + Qt::PlainText + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop + + + true + + + + + + + + diff --git a/gui/widgets/ModListView.cpp b/gui/widgets/ModListView.cpp new file mode 100644 index 00000000..838af75e --- /dev/null +++ b/gui/widgets/ModListView.cpp @@ -0,0 +1,51 @@ +/* Copyright 2013 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 "ModListView.h" +#include +#include +#include +#include +#include + +ModListView::ModListView ( QWidget* parent ) + :QTreeView ( parent ) +{ + setAllColumnsShowFocus ( true ); + setExpandsOnDoubleClick ( false ); + setRootIsDecorated ( false ); + setSortingEnabled ( false ); + setAlternatingRowColors ( true ); + setSelectionMode ( QAbstractItemView::ContiguousSelection ); + setHeaderHidden ( false ); + setSelectionBehavior(QAbstractItemView::SelectRows); + setVerticalScrollBarPolicy ( Qt::ScrollBarAlwaysOn ); + setHorizontalScrollBarPolicy ( Qt::ScrollBarAsNeeded ); + setDropIndicatorShown(true); + setDragEnabled(true); + setDragDropMode(QAbstractItemView::DropOnly); + viewport()->setAcceptDrops(true); +} + +void ModListView::setModel ( QAbstractItemModel* model ) +{ + QTreeView::setModel ( model ); + auto head = header(); + head->setStretchLastSection(false); + head->setSectionResizeMode(0, QHeaderView::Stretch); + for(int i = 1; i < head->count(); i++) + head->setSectionResizeMode(i, QHeaderView::ResizeToContents); + dropIndicatorPosition(); +} diff --git a/gui/widgets/ModListView.h b/gui/widgets/ModListView.h new file mode 100644 index 00000000..b26fa26b --- /dev/null +++ b/gui/widgets/ModListView.h @@ -0,0 +1,27 @@ +/* Copyright 2013 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 + +class Mod; + +class ModListView: public QTreeView +{ + Q_OBJECT +public: + explicit ModListView ( QWidget* parent = 0 ); + virtual void setModel ( QAbstractItemModel* model ); +}; diff --git a/logic/BaseInstance.cpp b/logic/BaseInstance.cpp index 6a6b195b..c38f75ef 100644 --- a/logic/BaseInstance.cpp +++ b/logic/BaseInstance.cpp @@ -3,7 +3,7 @@ * 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 @@ -19,7 +19,7 @@ #include #include -#include +#include "MultiMC.h" #include "inisettingsobject.h" #include "setting.h" @@ -28,64 +28,74 @@ #include "pathutils.h" #include "lists/MinecraftVersionList.h" - -BaseInstance::BaseInstance( BaseInstancePrivate* d_in, - const QString& rootDir, - SettingsObject* settings_obj, - QObject* parent - ) -:inst_d(d_in), QObject(parent) +BaseInstance::BaseInstance(BaseInstancePrivate *d_in, const QString &rootDir, + SettingsObject *settings_obj, QObject *parent) + : inst_d(d_in), QObject(parent) { I_D(BaseInstance); d->m_settings = settings_obj; d->m_rootDir = rootDir; - + settings().registerSetting(new Setting("name", "Unnamed Instance")); settings().registerSetting(new Setting("iconKey", "default")); settings().registerSetting(new Setting("notes", "")); settings().registerSetting(new Setting("lastLaunchTime", 0)); - + /* - * custom base jar has no default. it is determined in code... see the accessor methods for it - * + * custom base jar has no default. it is determined in code... see the accessor methods for + *it + * * for instances that DO NOT have the CustomBaseJar setting (legacy instances), * [.]minecraft/bin/mcbackup.jar is the default base jar */ settings().registerSetting(new Setting("UseCustomBaseJar", true)); settings().registerSetting(new Setting("CustomBaseJar", "")); - + auto globalSettings = MMC->settings(); - + // Java Settings settings().registerSetting(new Setting("OverrideJava", false)); - settings().registerSetting(new OverrideSetting("JavaPath", globalSettings->getSetting("JavaPath"))); - settings().registerSetting(new OverrideSetting("JvmArgs", globalSettings->getSetting("JvmArgs"))); - + settings().registerSetting( + new OverrideSetting("JavaPath", globalSettings->getSetting("JavaPath"))); + settings().registerSetting( + new OverrideSetting("JvmArgs", globalSettings->getSetting("JvmArgs"))); + // Custom Commands settings().registerSetting(new Setting("OverrideCommands", false)); - settings().registerSetting(new OverrideSetting("PreLaunchCommand", globalSettings->getSetting("PreLaunchCommand"))); - settings().registerSetting(new OverrideSetting("PostExitCommand", globalSettings->getSetting("PostExitCommand"))); - + settings().registerSetting(new OverrideSetting( + "PreLaunchCommand", globalSettings->getSetting("PreLaunchCommand"))); + settings().registerSetting( + new OverrideSetting("PostExitCommand", globalSettings->getSetting("PostExitCommand"))); + // Window Size settings().registerSetting(new Setting("OverrideWindow", false)); - settings().registerSetting(new OverrideSetting("LaunchMaximized", globalSettings->getSetting("LaunchMaximized"))); - settings().registerSetting(new OverrideSetting("MinecraftWinWidth", globalSettings->getSetting("MinecraftWinWidth"))); - settings().registerSetting(new OverrideSetting("MinecraftWinHeight", globalSettings->getSetting("MinecraftWinHeight"))); - + settings().registerSetting( + new OverrideSetting("LaunchMaximized", globalSettings->getSetting("LaunchMaximized"))); + settings().registerSetting(new OverrideSetting( + "MinecraftWinWidth", globalSettings->getSetting("MinecraftWinWidth"))); + settings().registerSetting(new OverrideSetting( + "MinecraftWinHeight", globalSettings->getSetting("MinecraftWinHeight"))); + // Memory settings().registerSetting(new Setting("OverrideMemory", false)); - settings().registerSetting(new OverrideSetting("MinMemAlloc", globalSettings->getSetting("MinMemAlloc"))); - settings().registerSetting(new OverrideSetting("MaxMemAlloc", globalSettings->getSetting("MaxMemAlloc"))); - settings().registerSetting(new OverrideSetting("PermGen", globalSettings->getSetting("PermGen"))); - + settings().registerSetting( + new OverrideSetting("MinMemAlloc", globalSettings->getSetting("MinMemAlloc"))); + settings().registerSetting( + new OverrideSetting("MaxMemAlloc", globalSettings->getSetting("MaxMemAlloc"))); + settings().registerSetting( + new OverrideSetting("PermGen", globalSettings->getSetting("PermGen"))); + // Auto login settings().registerSetting(new Setting("OverrideLogin", false)); - settings().registerSetting(new OverrideSetting("AutoLogin", globalSettings->getSetting("AutoLogin"))); - + settings().registerSetting( + new OverrideSetting("AutoLogin", globalSettings->getSetting("AutoLogin"))); + // Console settings().registerSetting(new Setting("OverrideConsole", false)); - settings().registerSetting(new OverrideSetting("ShowConsole", globalSettings->getSetting("ShowConsole"))); - settings().registerSetting(new OverrideSetting("AutoCloseConsole", globalSettings->getSetting("AutoCloseConsole"))); + settings().registerSetting( + new OverrideSetting("ShowConsole", globalSettings->getSetting("ShowConsole"))); + settings().registerSetting(new OverrideSetting( + "AutoCloseConsole", globalSettings->getSetting("AutoCloseConsole"))); } void BaseInstance::nuke() @@ -94,7 +104,6 @@ void BaseInstance::nuke() emit nuked(this); } - QString BaseInstance::id() const { return QFileInfo(instanceRoot()).fileName(); @@ -106,7 +115,6 @@ QString BaseInstance::instanceType() const return d->m_settings->get("InstanceType").toString(); } - QString BaseInstance::instanceRoot() const { I_D(BaseInstance); @@ -117,9 +125,9 @@ QString BaseInstance::minecraftRoot() const { QFileInfo mcDir(PathCombine(instanceRoot(), "minecraft")); QFileInfo dotMCDir(PathCombine(instanceRoot(), ".minecraft")); - + if (dotMCDir.exists() && !mcDir.exists()) - return dotMCDir.filePath(); + return dotMCDir.filePath(); else return mcDir.filePath(); } @@ -147,7 +155,7 @@ QString BaseInstance::baseJar() const { I_D(BaseInstance); bool customJar = d->m_settings->get("UseCustomBaseJar").toBool(); - if(customJar) + if (customJar) { return customBaseJar(); } @@ -158,99 +166,97 @@ QString BaseInstance::baseJar() const QString BaseInstance::customBaseJar() const { I_D(BaseInstance); - QString value = d->m_settings->get ( "CustomBaseJar" ).toString(); - if(value.isNull() || value.isEmpty()) + QString value = d->m_settings->get("CustomBaseJar").toString(); + if (value.isNull() || value.isEmpty()) { return defaultCustomBaseJar(); } return value; } -void BaseInstance::setCustomBaseJar ( QString val ) +void BaseInstance::setCustomBaseJar(QString val) { I_D(BaseInstance); - if(val.isNull() || val.isEmpty() || val == defaultCustomBaseJar()) - d->m_settings->reset ( "CustomBaseJar" ); + if (val.isNull() || val.isEmpty() || val == defaultCustomBaseJar()) + d->m_settings->reset("CustomBaseJar"); else - d->m_settings->set ( "CustomBaseJar", val ); + d->m_settings->set("CustomBaseJar", val); } -void BaseInstance::setShouldUseCustomBaseJar ( bool val ) +void BaseInstance::setShouldUseCustomBaseJar(bool val) { I_D(BaseInstance); - d->m_settings->set ( "UseCustomBaseJar", val ); + d->m_settings->set("UseCustomBaseJar", val); } bool BaseInstance::shouldUseCustomBaseJar() const { I_D(BaseInstance); - return d->m_settings->get ( "UseCustomBaseJar" ).toBool(); + return d->m_settings->get("UseCustomBaseJar").toBool(); } - qint64 BaseInstance::lastLaunch() const { I_D(BaseInstance); - return d->m_settings->get ( "lastLaunchTime" ).value(); + return d->m_settings->get("lastLaunchTime").value(); } -void BaseInstance::setLastLaunch ( qint64 val ) +void BaseInstance::setLastLaunch(qint64 val) { I_D(BaseInstance); - d->m_settings->set ( "lastLaunchTime", val ); - emit propertiesChanged ( this ); + d->m_settings->set("lastLaunchTime", val); + emit propertiesChanged(this); } -void BaseInstance::setGroupInitial ( QString val ) +void BaseInstance::setGroupInitial(QString val) { I_D(BaseInstance); d->m_group = val; - emit propertiesChanged ( this ); + emit propertiesChanged(this); } -void BaseInstance::setGroupPost ( QString val ) +void BaseInstance::setGroupPost(QString val) { setGroupInitial(val); emit groupChanged(); } - QString BaseInstance::group() const { I_D(BaseInstance); return d->m_group; } -void BaseInstance::setNotes ( QString val ) +void BaseInstance::setNotes(QString val) { I_D(BaseInstance); - d->m_settings->set ( "notes", val ); + d->m_settings->set("notes", val); } QString BaseInstance::notes() const { I_D(BaseInstance); - return d->m_settings->get ( "notes" ).toString(); + return d->m_settings->get("notes").toString(); } -void BaseInstance::setIconKey ( QString val ) +void BaseInstance::setIconKey(QString val) { I_D(BaseInstance); - d->m_settings->set ( "iconKey", val ); - emit propertiesChanged ( this ); + d->m_settings->set("iconKey", val); + emit propertiesChanged(this); } QString BaseInstance::iconKey() const { I_D(BaseInstance); - return d->m_settings->get ( "iconKey" ).toString(); + return d->m_settings->get("iconKey").toString(); } -void BaseInstance::setName ( QString val ) +void BaseInstance::setName(QString val) { I_D(BaseInstance); - d->m_settings->set ( "name", val ); - emit propertiesChanged ( this ); + d->m_settings->set("name", val); + emit propertiesChanged(this); } QString BaseInstance::name() const { I_D(BaseInstance); - return d->m_settings->get ( "name" ).toString(); + return d->m_settings->get("name").toString(); } diff --git a/logic/BaseInstance_p.h b/logic/BaseInstance_p.h index 06c0c0ba..06581a34 100644 --- a/logic/BaseInstance_p.h +++ b/logic/BaseInstance_p.h @@ -1,10 +1,25 @@ +/* Copyright 2013 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 #include class BaseInstance; -#define I_D(Class) Class##Private * const d = (Class##Private * const) inst_d.get() +#define I_D(Class) Class##Private *const d = (Class##Private * const)inst_d.get() struct BaseInstancePrivate { diff --git a/logic/BaseUpdate.cpp b/logic/BaseUpdate.cpp index 02b29d32..5aeb12ef 100644 --- a/logic/BaseUpdate.cpp +++ b/logic/BaseUpdate.cpp @@ -1,6 +1,21 @@ +/* Copyright 2013 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 "BaseUpdate.h" -BaseUpdate::BaseUpdate ( BaseInstance* inst, QObject* parent ) : Task ( parent ) +BaseUpdate::BaseUpdate(BaseInstance *inst, QObject *parent) : Task(parent) { m_inst = inst; } diff --git a/logic/BaseUpdate.h b/logic/BaseUpdate.h index 9ada0770..ddeefa97 100644 --- a/logic/BaseUpdate.h +++ b/logic/BaseUpdate.h @@ -3,7 +3,7 @@ * 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 @@ -34,15 +34,14 @@ class BaseUpdate : public Task Q_OBJECT public: explicit BaseUpdate(BaseInstance *inst, QObject *parent = 0); - + virtual void executeTask() = 0; -protected slots: - //virtual void error(const QString &msg); +protected +slots: + // virtual void error(const QString &msg); void updateDownloadProgress(qint64 current, qint64 total); - + protected: BaseInstance *m_inst; }; - - diff --git a/logic/BaseVersion.h b/logic/BaseVersion.h index 01745c46..1864c94c 100644 --- a/logic/BaseVersion.h +++ b/logic/BaseVersion.h @@ -3,7 +3,7 @@ * 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 @@ -14,6 +14,7 @@ */ #pragma once + #include /*! @@ -26,13 +27,13 @@ struct BaseVersion * 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) @@ -42,4 +43,4 @@ struct BaseVersion typedef std::shared_ptr BaseVersionPtr; -Q_DECLARE_METATYPE( BaseVersionPtr ) \ No newline at end of file +Q_DECLARE_METATYPE(BaseVersionPtr) \ No newline at end of file diff --git a/logic/CMakeLists.txt b/logic/CMakeLists.txt deleted file mode 100644 index b1eacced..00000000 --- a/logic/CMakeLists.txt +++ /dev/null @@ -1,24 +0,0 @@ -project(libMultiMC) - -set(CMAKE_AUTOMOC ON) - -# Find Qt -find_package(Qt5Core REQUIRED) -find_package(Qt5Network REQUIRED) -find_package(Qt5Xml REQUIRED) - -# Include Qt headers. -include_directories(${Qt5Base_INCLUDE_DIRS}) -include_directories(${Qt5Network_INCLUDE_DIRS}) - -# Include utility library. -include_directories(${CMAKE_SOURCE_DIR}/libutil/include) - -# Include settings library. -include_directories(${CMAKE_SOURCE_DIR}/libsettings/include) - -SET(LIBINST_HEADERS - -) - - diff --git a/logic/EnabledItemFilter.cpp b/logic/EnabledItemFilter.cpp index 6ecd0271..c252a0ad 100644 --- a/logic/EnabledItemFilter.cpp +++ b/logic/EnabledItemFilter.cpp @@ -1,9 +1,22 @@ +/* Copyright 2013 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 "EnabledItemFilter.h" -EnabledItemFilter::EnabledItemFilter(QObject* parent) - :QSortFilterProxyModel(parent) +EnabledItemFilter::EnabledItemFilter(QObject *parent) : QSortFilterProxyModel(parent) { - } void EnabledItemFilter::setActive(bool active) @@ -14,17 +27,17 @@ void EnabledItemFilter::setActive(bool active) bool EnabledItemFilter::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const { - if(!m_active) + if (!m_active) return true; QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent); - if(sourceModel()->flags(index) & Qt::ItemIsEnabled) + if (sourceModel()->flags(index) & Qt::ItemIsEnabled) { return true; } return false; } -bool EnabledItemFilter::lessThan(const QModelIndex& left, const QModelIndex& right) const +bool EnabledItemFilter::lessThan(const QModelIndex &left, const QModelIndex &right) const { - return QSortFilterProxyModel::lessThan(left, right); + return QSortFilterProxyModel::lessThan(left, right); } diff --git a/logic/EnabledItemFilter.h b/logic/EnabledItemFilter.h index cb6d4041..bf5e1e85 100644 --- a/logic/EnabledItemFilter.h +++ b/logic/EnabledItemFilter.h @@ -1,3 +1,18 @@ +/* Copyright 2013 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 @@ -7,10 +22,11 @@ class EnabledItemFilter : public QSortFilterProxyModel public: EnabledItemFilter(QObject *parent = 0); void setActive(bool active); - + protected: bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const; bool lessThan(const QModelIndex &left, const QModelIndex &right) const; + private: bool m_active = false; }; \ No newline at end of file diff --git a/logic/ForgeInstaller.cpp b/logic/ForgeInstaller.cpp index a946dd44..8d4c5b41 100644 --- a/logic/ForgeInstaller.cpp +++ b/logic/ForgeInstaller.cpp @@ -1,3 +1,18 @@ +/* Copyright 2013 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 "ForgeInstaller.h" #include "OneSixVersion.h" #include "OneSixLibrary.h" diff --git a/logic/ForgeInstaller.h b/logic/ForgeInstaller.h index f6f22a2a..0b9f9c77 100644 --- a/logic/ForgeInstaller.h +++ b/logic/ForgeInstaller.h @@ -1,3 +1,18 @@ +/* Copyright 2013 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 #include @@ -19,7 +34,3 @@ private: QString realVersionId; QString m_universal_url; }; - - - - diff --git a/logic/InstanceFactory.cpp b/logic/InstanceFactory.cpp index e64d22ca..e1f1f202 100644 --- a/logic/InstanceFactory.cpp +++ b/logic/InstanceFactory.cpp @@ -30,7 +30,7 @@ #include #include "pathutils.h" -#include +#include "logger/QsLog.h" InstanceFactory InstanceFactory::loader; @@ -129,19 +129,20 @@ InstanceFactory::InstCreateError InstanceFactory::copyInstance(BaseInstance *&ne return InstanceFactory::CantCreateDir; } auto error = loadInstance(newInstance, instDir); - switch(error) + switch (error) { - case NoLoadError: - return NoCreateError; - case UnknownLoadError: - { - rootDir.removeRecursively(); - return UnknownCreateError; - } - case NotAnInstance: - { - rootDir.removeRecursively(); - return CantCreateDir; - } - }; + case NoLoadError: + return NoCreateError; + case UnknownLoadError: + { + rootDir.removeRecursively(); + return UnknownCreateError; + } + case NotAnInstance: + { + rootDir.removeRecursively(); + return CantCreateDir; + } + } + ; } diff --git a/logic/InstanceLauncher.cpp b/logic/InstanceLauncher.cpp index 720052a3..9f78e55b 100644 --- a/logic/InstanceLauncher.cpp +++ b/logic/InstanceLauncher.cpp @@ -1,18 +1,34 @@ +/* Copyright 2013 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 + #include "InstanceLauncher.h" #include "MultiMC.h" -#include -#include "gui/logindialog.h" -#include "gui/ProgressDialog.h" -#include "gui/consolewindow.h" +#include "gui/ConsoleWindow.h" +#include "gui/dialogs/LoginDialog.h" +#include "gui/dialogs/ProgressDialog.h" + #include "logic/net/LoginTask.h" #include "logic/MinecraftProcess.h" -#include "lists/InstanceList.h" - +#include "logic/lists/InstanceList.h" -InstanceLauncher::InstanceLauncher ( QString instId ) - :QObject(), instId ( instId ) -{} +InstanceLauncher::InstanceLauncher(QString instId) : QObject(), instId(instId) +{ +} void InstanceLauncher::onTerminated() { @@ -22,53 +38,56 @@ void InstanceLauncher::onTerminated() void InstanceLauncher::onLoginComplete() { - LoginTask * task = ( LoginTask * ) QObject::sender(); + LoginTask *task = (LoginTask *)QObject::sender(); auto result = task->getResult(); auto instance = MMC->instances()->getInstanceById(instId); - proc = instance->prepareForLaunch ( result ); - if ( !proc ) + proc = instance->prepareForLaunch(result); + if (!proc) { - //FIXME: report error + // FIXME: report error return; } console = new ConsoleWindow(proc); console->show(); - connect ( proc, SIGNAL ( ended() ), SLOT ( onTerminated() ) ); - connect ( proc, SIGNAL ( log ( QString,MessageLevel::Enum ) ), console, SLOT ( write ( QString,MessageLevel::Enum ) ) ); + connect(proc, SIGNAL(ended()), SLOT(onTerminated())); + connect(proc, SIGNAL(log(QString, MessageLevel::Enum)), console, + SLOT(write(QString, MessageLevel::Enum))); proc->launch(); } -void InstanceLauncher::doLogin ( const QString& errorMsg ) +void InstanceLauncher::doLogin(const QString &errorMsg) { - LoginDialog* loginDlg = new LoginDialog ( nullptr, errorMsg ); + LoginDialog *loginDlg = new LoginDialog(nullptr, errorMsg); loginDlg->exec(); - if ( loginDlg->result() == QDialog::Accepted ) + if (loginDlg->result() == QDialog::Accepted) { - UserInfo uInfo {loginDlg->getUsername(), loginDlg->getPassword() }; + UserInfo uInfo{loginDlg->getUsername(), loginDlg->getPassword()}; - ProgressDialog* tDialog = new ProgressDialog ( nullptr ); - LoginTask* loginTask = new LoginTask ( uInfo, tDialog ); - connect ( loginTask, SIGNAL ( succeeded() ),SLOT ( onLoginComplete() ), Qt::QueuedConnection ); - connect ( loginTask, SIGNAL ( failed ( QString ) ),SLOT ( doLogin ( QString ) ), Qt::QueuedConnection ); - tDialog->exec ( loginTask ); + ProgressDialog *tDialog = new ProgressDialog(nullptr); + LoginTask *loginTask = new LoginTask(uInfo, tDialog); + connect(loginTask, SIGNAL(succeeded()), SLOT(onLoginComplete()), Qt::QueuedConnection); + connect(loginTask, SIGNAL(failed(QString)), SLOT(doLogin(QString)), + Qt::QueuedConnection); + tDialog->exec(loginTask); } - //onLoginComplete(LoginResponse("Offline","Offline", 1)); + // onLoginComplete(LoginResponse("Offline","Offline", 1)); } int InstanceLauncher::launch() { - std::cout << "Launching Instance '" << qPrintable ( instId ) << "'" << std::endl; + std::cout << "Launching Instance '" << qPrintable(instId) << "'" << std::endl; auto instance = MMC->instances()->getInstanceById(instId); - if ( !instance ) + if (!instance) { - std::cout << "Could not find instance requested. note that you have to specify the ID, not the NAME" << std::endl; + std::cout << "Could not find instance requested. note that you have to specify the ID, " + "not the NAME" << std::endl; return 1; } std::cout << "Logging in..." << std::endl; - doLogin ( "" ); + doLogin(""); return MMC->exec(); } diff --git a/logic/InstanceLauncher.h b/logic/InstanceLauncher.h index de93e3d7..107c069f 100644 --- a/logic/InstanceLauncher.h +++ b/logic/InstanceLauncher.h @@ -1,3 +1,18 @@ +/* Copyright 2013 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 @@ -9,20 +24,21 @@ class ConsoleWindow; class InstanceLauncher : public QObject { Q_OBJECT - + private: QString instId; MinecraftProcess *proc; ConsoleWindow *console; - + public: InstanceLauncher(QString instId); - -private slots: + +private +slots: void onTerminated(); void onLoginComplete(); void doLogin(const QString &errorMsg); - + public: int launch(); }; diff --git a/logic/JavaUtils.cpp b/logic/JavaUtils.cpp index 8e9c984f..61d0231a 100644 --- a/logic/JavaUtils.cpp +++ b/logic/JavaUtils.cpp @@ -13,21 +13,22 @@ * limitations under the License. */ -#include "JavaUtils.h" -#include "pathutils.h" -#include "MultiMC.h" - #include #include #include #include -#include -#include + #include +#include + +#include "MultiMC.h" + +#include "JavaUtils.h" +#include "logger/QsLog.h" +#include "gui/dialogs/VersionSelectDialog.h" JavaUtils::JavaUtils() { - } JavaVersionPtr JavaUtils::GetDefaultJava() @@ -48,20 +49,24 @@ QList JavaUtils::FindJavaFromRegistryKey(DWORD keyType, QString QList javas; QString archType = "unknown"; - if(keyType == KEY_WOW64_64KEY) archType = "64"; - else if(keyType == KEY_WOW64_32KEY) archType = "32"; + 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) + 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) + if (RegQueryValueExA(jreKey, "CurrentVersion", NULL, NULL, (BYTE *)value, &valueSz) == + ERROR_MORE_DATA) { value = new char[valueSz]; - RegQueryValueExA(jreKey, "CurrentVersion", NULL, NULL, (BYTE*)value, &valueSz); + RegQueryValueExA(jreKey, "CurrentVersion", NULL, NULL, (BYTE *)value, &valueSz); } QString recommended = value; @@ -70,37 +75,43 @@ QList JavaUtils::FindJavaFromRegistryKey(DWORD keyType, QString DWORD subKeyNameSize, numSubKeys, retCode; // Get the number of subkeys - RegQueryInfoKey(jreKey, NULL, NULL, NULL, &numSubKeys, NULL, NULL, NULL, NULL, NULL, NULL, NULL); + RegQueryInfoKey(jreKey, NULL, NULL, NULL, &numSubKeys, NULL, NULL, NULL, NULL, NULL, + NULL, NULL); // Iterate until RegEnumKeyEx fails - if(numSubKeys > 0) + if (numSubKeys > 0) { - for(int i = 0; i < numSubKeys; i++) + for (int i = 0; i < numSubKeys; i++) { subKeyNameSize = 255; - retCode = RegEnumKeyEx(jreKey, i, subKeyName, &subKeyNameSize, NULL, NULL, NULL, NULL); - if(retCode == ERROR_SUCCESS) + 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) + 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) + if (RegQueryValueEx(newKey, "JavaHome", NULL, NULL, (BYTE *)value, + &valueSz) == ERROR_MORE_DATA) { value = new char[valueSz]; - RegQueryValueEx(newKey, "JavaHome", NULL, NULL, (BYTE*)value, &valueSz); + RegQueryValueEx(newKey, "JavaHome", NULL, NULL, (BYTE *)value, + &valueSz); // Now, we construct the version object and add it to the list. JavaVersionPtr javaVersion(new JavaVersion()); javaVersion->id = subKeyName; javaVersion->arch = archType; - javaVersion->path = QDir(PathCombine(value, "bin")).absoluteFilePath("java.exe"); + javaVersion->path = + QDir(PathCombine(value, "bin")).absoluteFilePath("java.exe"); javaVersion->recommended = (recommended == subKeyName); javas.append(javaVersion); } @@ -121,17 +132,21 @@ QList JavaUtils::FindJavaPaths() { QList javas; - QList JRE64s = this->FindJavaFromRegistryKey(KEY_WOW64_64KEY, "SOFTWARE\\JavaSoft\\Java Runtime Environment"); - QList JDK64s = this->FindJavaFromRegistryKey(KEY_WOW64_64KEY, "SOFTWARE\\JavaSoft\\Java Development Kit"); - QList JRE32s = this->FindJavaFromRegistryKey(KEY_WOW64_32KEY, "SOFTWARE\\JavaSoft\\Java Runtime Environment"); - QList JDK32s = this->FindJavaFromRegistryKey(KEY_WOW64_32KEY, "SOFTWARE\\JavaSoft\\Java Development Kit"); + QList JRE64s = this->FindJavaFromRegistryKey( + KEY_WOW64_64KEY, "SOFTWARE\\JavaSoft\\Java Runtime Environment"); + QList JDK64s = this->FindJavaFromRegistryKey( + KEY_WOW64_64KEY, "SOFTWARE\\JavaSoft\\Java Development Kit"); + QList JRE32s = this->FindJavaFromRegistryKey( + KEY_WOW64_32KEY, "SOFTWARE\\JavaSoft\\Java Runtime Environment"); + QList JDK32s = this->FindJavaFromRegistryKey( + KEY_WOW64_32KEY, "SOFTWARE\\JavaSoft\\Java Development Kit"); javas.append(JRE64s); javas.append(JDK64s); javas.append(JRE32s); javas.append(JDK32s); - if(javas.size() <= 0) + if (javas.size() <= 0) { QLOG_WARN() << "Failed to find Java in the Windows registry - defaulting to \"java\""; javas.append(this->GetDefaultJava()); @@ -140,10 +155,11 @@ QList JavaUtils::FindJavaPaths() QLOG_INFO() << "Found the following Java installations (64 -> 32, JRE -> JDK): "; - for(auto &java : javas) + for (auto &java : javas) { QString sRec; - if(java->recommended) sRec = "(Recommended)"; + if (java->recommended) + sRec = "(Recommended)"; QLOG_INFO() << java->id << java->arch << " at " << java->path << sRec; } diff --git a/logic/JavaUtils.h b/logic/JavaUtils.h index e4f777d0..8d7550d0 100644 --- a/logic/JavaUtils.h +++ b/logic/JavaUtils.h @@ -17,11 +17,13 @@ #include #include -#include -#include "osutils.h" + +#include + +#include "logic/lists/JavaVersionList.h" #if WINDOWS - #include +#include #endif class JavaUtils diff --git a/logic/LegacyForge.cpp b/logic/LegacyForge.cpp index adcf487c..94212ae4 100644 --- a/logic/LegacyForge.cpp +++ b/logic/LegacyForge.cpp @@ -1,26 +1,25 @@ -// -// Copyright 2012 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. -// +/* Copyright 2013 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 "LegacyForge.h" -MinecraftForge::MinecraftForge ( const QString& file ) : Mod ( file ) +MinecraftForge::MinecraftForge(const QString &file) : Mod(file) { - } -bool MinecraftForge::FixVersionIfNeeded ( QString newVersion ) + +bool MinecraftForge::FixVersionIfNeeded(QString newVersion) {/* wxString reportedVersion = GetModVersion(); if(reportedVersion == "..." || reportedVersion.empty()) @@ -40,7 +39,7 @@ bool MinecraftForge::FixVersionIfNeeded ( QString newVersion ) // release last entry in.reset(); outzip.PutNextEntry("forgeversion.properties"); - + wxStringTokenizer tokenizer(newVersion,"."); wxString verFile; verFile << wxString("forge.major.number=") << tokenizer.GetNextToken() << "\n"; diff --git a/logic/LegacyForge.h b/logic/LegacyForge.h index 00a054b8..f4165ffa 100644 --- a/logic/LegacyForge.h +++ b/logic/LegacyForge.h @@ -1,25 +1,25 @@ -// -// Copyright 2012 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. -// +/* Copyright 2013 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 "Mod.h" class MinecraftForge : public Mod { public: - MinecraftForge ( const QString& file ); + MinecraftForge(const QString &file); bool FixVersionIfNeeded(QString newVersion); }; diff --git a/logic/LegacyInstance.cpp b/logic/LegacyInstance.cpp index 2fd18693..9a91b839 100644 --- a/logic/LegacyInstance.cpp +++ b/logic/LegacyInstance.cpp @@ -1,16 +1,35 @@ -#include "LegacyInstance.h" -#include "LegacyInstance_p.h" -#include "MinecraftProcess.h" -#include "LegacyUpdate.h" -#include "lists/IconList.h" -#include -#include -#include -#include "gui/LegacyModEditDialog.h" +/* Copyright 2013 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 #include #include -#include +#include +#include +#include + +#include "MultiMC.h" + +#include "LegacyInstance.h" +#include "LegacyInstance_p.h" + +#include "logic/MinecraftProcess.h" +#include "logic/LegacyUpdate.h" +#include "logic/lists/IconList.h" + +#include "gui/dialogs/LegacyModEditDialog.h" #define LAUNCHER_FILE "MultiMCLauncher.jar" diff --git a/logic/LegacyInstance.h b/logic/LegacyInstance.h index 8bf334f6..8a8d4b91 100644 --- a/logic/LegacyInstance.h +++ b/logic/LegacyInstance.h @@ -1,3 +1,18 @@ +/* Copyright 2013 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 "BaseInstance.h" @@ -58,7 +73,8 @@ public: virtual bool versionIsCustom() override { return false; - }; + } + ; virtual bool shouldUpdate() const; virtual void setShouldUpdate(bool val); diff --git a/logic/LegacyInstance_p.h b/logic/LegacyInstance_p.h index 0809b8d2..ed97ccd3 100644 --- a/logic/LegacyInstance_p.h +++ b/logic/LegacyInstance_p.h @@ -1,16 +1,30 @@ +/* Copyright 2013 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 #include +#include + #include "BaseInstance_p.h" #include "ModList.h" -#include - -class ModList; -struct LegacyInstancePrivate: public BaseInstancePrivate +struct LegacyInstancePrivate : public BaseInstancePrivate { std::shared_ptr jar_mod_list; std::shared_ptr core_mod_list; std::shared_ptr loader_mod_list; std::shared_ptr texture_pack_list; -}; \ No newline at end of file +}; diff --git a/logic/LegacyUpdate.cpp b/logic/LegacyUpdate.cpp index 5120b241..9533f8ff 100644 --- a/logic/LegacyUpdate.cpp +++ b/logic/LegacyUpdate.cpp @@ -1,3 +1,18 @@ +/* Copyright 2013 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 "LegacyUpdate.h" #include "lists/LwjglVersionList.h" #include "lists/MinecraftVersionList.h" @@ -9,7 +24,7 @@ #include #include #include -#include +#include "logger/QsLog.h" LegacyUpdate::LegacyUpdate(BaseInstance *inst, QObject *parent) : BaseUpdate(inst, parent) { diff --git a/logic/LegacyUpdate.h b/logic/LegacyUpdate.h index 69560f55..b30fa0b3 100644 --- a/logic/LegacyUpdate.h +++ b/logic/LegacyUpdate.h @@ -3,7 +3,7 @@ * 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 @@ -19,9 +19,9 @@ #include #include -#include "net/NetJob.h" -#include "tasks/Task.h" -#include "BaseUpdate.h" +#include "logic/net/NetJob.h" +#include "logic/tasks/Task.h" +#include "logic/BaseUpdate.h" class MinecraftVersion; class BaseInstance; @@ -34,39 +34,42 @@ class LegacyUpdate : public BaseUpdate public: explicit LegacyUpdate(BaseInstance *inst, QObject *parent = 0); virtual void executeTask(); - -private slots: + +private +slots: void lwjglStart(); - void lwjglFinished( QNetworkReply* ); + void lwjglFinished(QNetworkReply *); void lwjglFailed(); - + void jarStart(); void jarFinished(); void jarFailed(); - + void extractLwjgl(); - + void ModTheJar(); + private: enum MetainfAction { - KeepMetainf, // the META-INF folder will be added from the merged jar + KeepMetainf, // the META-INF folder will be added from the merged jar IgnoreMetainf // the META-INF from the merged jar will be ignored }; - bool MergeZipFiles(QuaZip *into, QFileInfo from, QSet& contained, MetainfAction metainf); + bool MergeZipFiles(QuaZip *into, QFileInfo from, QSet &contained, + MetainfAction metainf); + private: - + std::shared_ptr m_reply; - + // target version, determined during this task // MinecraftVersion *targetVersion; QString lwjglURL; QString lwjglVersion; - + QString lwjglTargetPath; QString lwjglNativesPath; + private: NetJobPtr legacyDownloadJob; }; - - diff --git a/logic/MinecraftProcess.h b/logic/MinecraftProcess.h index 812559d5..ad887c5b 100644 --- a/logic/MinecraftProcess.h +++ b/logic/MinecraftProcess.h @@ -14,6 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #pragma once #include @@ -24,15 +25,17 @@ * @brief the MessageLevel Enum * defines what level a message is */ -namespace MessageLevel { -enum Enum { - MultiMC, /**< MultiMC Messages */ - Debug, /**< Debug Messages */ - Info, /**< Info Messages */ - Message, /**< Standard Messages */ - Warning, /**< Warnings */ - Error, /**< Errors */ - Fatal /**< Fatal Errors */ +namespace MessageLevel +{ +enum Enum +{ + MultiMC, /**< MultiMC Messages */ + Debug, /**< Debug Messages */ + Info, /**< Info Messages */ + Message, /**< Standard Messages */ + Warning, /**< Warnings */ + Error, /**< Errors */ + Fatal /**< Fatal Errors */ }; } @@ -56,25 +59,29 @@ public: void launch(); void setMinecraftWorkdir(QString path); - + void setMinecraftArguments(QStringList args); - + void killMinecraft(); - - inline void setLogin(QString user, QString sid) { username = user; sessionID = sid; } - + + inline void setLogin(QString user, QString sid) + { + username = user; + sessionID = sid; + } + signals: /** * @brief emitted when mc has finished and the PostLaunchCommand was run */ - void ended(BaseInstance*); + void ended(BaseInstance *); /** * @brief emitted when we want to log something * @param text the text to log * @param level the level to log at */ - void log(QString text, MessageLevel::Enum level=MessageLevel::MultiMC); + void log(QString text, MessageLevel::Enum level = MessageLevel::MultiMC); protected: BaseInstance *m_instance; @@ -83,10 +90,12 @@ protected: QString m_out_leftover; QProcess m_prepostlaunchprocess; -protected slots: +protected +slots: void finish(int, QProcess::ExitStatus status); void on_stdErr(); void on_stdOut(); + private: bool killed; MessageLevel::Enum getLevel(const QString &message, MessageLevel::Enum defaultLevel); diff --git a/logic/MinecraftVersion.h b/logic/MinecraftVersion.h index 53c2f5ef..504381a8 100644 --- a/logic/MinecraftVersion.h +++ b/logic/MinecraftVersion.h @@ -3,7 +3,7 @@ * 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 @@ -25,10 +25,10 @@ struct MinecraftVersion : public BaseVersion * This is primarily used for sorting versions in a list. */ qint64 timestamp; - + /// The URL that this version will be downloaded from. maybe. QString download_url; - + /// This version's type. Used internally to identify what kind of version this is. enum VersionType { @@ -36,31 +36,31 @@ struct MinecraftVersion : public BaseVersion Legacy, Nostalgia } type; - + /// is this the latest version? bool is_latest = false; - + /// is this a snapshot? bool is_snapshot = false; - + QString m_name; - + QString m_descriptor; - - virtual QString descriptor() + + virtual QString descriptor() { return m_descriptor; } - - virtual QString name() + + virtual QString name() { return m_name; } - + virtual QString typeString() const { QStringList pre_final; - if(is_latest == true) + if (is_latest == true) { pre_final.append("Latest"); } @@ -75,12 +75,12 @@ struct MinecraftVersion : public BaseVersion case Nostalgia: pre_final.append("Nostalgia"); break; - + default: pre_final.append(QString("Type(%1)").arg(type)); break; } - if(is_snapshot == true) + if (is_snapshot == true) { pre_final.append("Snapshot"); } diff --git a/logic/Mod.cpp b/logic/Mod.cpp index c45e3ad2..f9647eea 100644 --- a/logic/Mod.cpp +++ b/logic/Mod.cpp @@ -1,18 +1,17 @@ -// -// Copyright 2012 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. -// +/* Copyright 2013 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 #include @@ -26,7 +25,7 @@ #include "Mod.h" #include #include -#include +#include "logger/QsLog.h" Mod::Mod(const QFileInfo &file) { @@ -121,11 +120,12 @@ void Mod::ReadMCModInfo(QByteArray contents) m_homeurl = firstObj.value("url").toString(); m_description = firstObj.value("description").toString(); QJsonArray authors = firstObj.value("authors").toArray(); - if(authors.size() == 0) m_authors = ""; - else if(authors.size() >= 1) + if (authors.size() == 0) + m_authors = ""; + else if (authors.size() >= 1) { m_authors = authors.at(0).toString(); - for(int i = 1; i < authors.size(); i++) + for (int i = 1; i < authors.size(); i++) { m_authors += ", " + authors.at(i).toString(); } diff --git a/logic/Mod.h b/logic/Mod.h index f3aaf18b..ca362a9d 100644 --- a/logic/Mod.h +++ b/logic/Mod.h @@ -1,18 +1,17 @@ -// -// Copyright 2012 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. -// +/* Copyright 2013 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 diff --git a/logic/ModList.cpp b/logic/ModList.cpp index 236f0db6..8ec73955 100644 --- a/logic/ModList.cpp +++ b/logic/ModList.cpp @@ -1,18 +1,17 @@ -// -// Copyright 2013 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. -// +/* Copyright 2013 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 "ModList.h" #include "LegacyInstance.h" @@ -21,7 +20,7 @@ #include #include #include -#include +#include "logger/QsLog.h" ModList::ModList(const QString &dir, const QString &list_file) : QAbstractListModel(), m_dir(dir), m_list_file(list_file) diff --git a/logic/ModList.h b/logic/ModList.h index e99b6c82..803a5429 100644 --- a/logic/ModList.h +++ b/logic/ModList.h @@ -1,22 +1,29 @@ -// -// Copyright 2013 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 -// +/* Copyright 2013 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 -class LegacyInstance; -class BaseInstance; #include #include #include #include -#include "Mod.h" +#include "logic/Mod.h" + +class LegacyInstance; +class BaseInstance; class QFileSystemWatcher; /** @@ -27,91 +34,105 @@ class ModList : public QAbstractListModel { Q_OBJECT public: - ModList(const QString& dir, const QString& list_file = QString()); + ModList(const QString &dir, const QString &list_file = QString()); - virtual QVariant data ( const QModelIndex& index, int role = Qt::DisplayRole ) const; - virtual int rowCount ( const QModelIndex& parent = QModelIndex() ) const + virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; + virtual int rowCount(const QModelIndex &parent = QModelIndex()) const { return size(); - }; - virtual QVariant headerData ( int section, Qt::Orientation orientation, int role = Qt::DisplayRole ) const; - virtual int columnCount ( const QModelIndex& parent ) const; - - size_t size() const { return mods.size(); }; - bool empty() const { return size() == 0; } - Mod& operator[](size_t index) { return mods[index]; }; - + } + ; + virtual QVariant headerData(int section, Qt::Orientation orientation, + int role = Qt::DisplayRole) const; + virtual int columnCount(const QModelIndex &parent) const; + + size_t size() const + { + return mods.size(); + } + ; + bool empty() const + { + return size() == 0; + } + Mod &operator[](size_t index) + { + return mods[index]; + } + ; + /// Reloads the mod list and returns true if the list changed. virtual bool update(); /** * Adds the given mod to the list at the given index - if the list supports custom ordering */ - virtual bool installMod(const QFileInfo& filename, int index = 0); + virtual bool installMod(const QFileInfo &filename, int index = 0); /// Deletes the mod at the given index. virtual bool deleteMod(int index); - + /// Deletes all the selected mods - virtual bool deleteMods( int first, int last ); - + virtual bool deleteMods(int first, int last); + /** * move the mod at index to the position N * 0 is the beginning of the list, length() is the end of the list. */ virtual bool moveModTo(int from, int to); - + /** * move the mod at index one position upwards */ virtual bool moveModUp(int from); - virtual bool moveModsUp( int first, int last ); - + virtual bool moveModsUp(int first, int last); + /** * move the mod at index one position downwards */ virtual bool moveModDown(int from); - virtual bool moveModsDown( int first, int last ); - + virtual bool moveModsDown(int first, int last); + /// flags, mostly to support drag&drop - virtual Qt::ItemFlags flags(const QModelIndex& index) const; + virtual Qt::ItemFlags flags(const QModelIndex &index) const; /// get data for drag action - virtual QMimeData* mimeData(const QModelIndexList& indexes) const; + virtual QMimeData *mimeData(const QModelIndexList &indexes) const; /// get the supported mime types virtual QStringList mimeTypes() const; /// process data from drop action - virtual bool dropMimeData(const QMimeData* data, Qt::DropAction action, int row, int column, const QModelIndex& parent); + virtual bool dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, + const QModelIndex &parent); /// what drag actions do we support? virtual Qt::DropActions supportedDragActions() const; - + /// what drop actions do we support? virtual Qt::DropActions supportedDropActions() const; - + void startWatching(); void stopWatching(); - + virtual bool isValid(); - + QDir dir() { return m_dir; } + private: QStringList readListFile(); bool saveListFile(); -private slots: +private +slots: void directoryChanged(QString path); - + signals: void changed(); + protected: - QFileSystemWatcher * m_watcher; + QFileSystemWatcher *m_watcher; bool is_watching; QDir m_dir; QString m_list_file; QString m_list_id; QList mods; }; - - - diff --git a/logic/NagUtils.cpp b/logic/NagUtils.cpp index ccabf71f..6f81b3c7 100644 --- a/logic/NagUtils.cpp +++ b/logic/NagUtils.cpp @@ -13,25 +13,26 @@ * limitations under the License. */ -#include "NagUtils.h" -#include "gui/CustomMessageBox.h" +#include "logic/NagUtils.h" +#include "gui/dialogs/CustomMessageBox.h" namespace NagUtils { void checkJVMArgs(QString jvmargs, QWidget *parent) { - if(jvmargs.contains("-XX:PermSize=") || jvmargs.contains(QRegExp("-Xm[sx]"))) + if (jvmargs.contains("-XX:PermSize=") || jvmargs.contains(QRegExp("-Xm[sx]"))) { - CustomMessageBox::selectable(parent, parent->tr("JVM arguments warning"), - parent->tr("You tried to manually set a JVM memory option (using " - " \"-XX:PermSize\", \"-Xmx\" or \"-Xms\") - there" - " are dedicated boxes for these in the settings (Java" - " tab, in the Memory group at the top).\n" - "Your manual settings will be overridden by the" - " dedicated options.\n" - "This message will be displayed until you remove them" - " from the JVM arguments."), - QMessageBox::Warning)->exec(); + CustomMessageBox::selectable( + parent, parent->tr("JVM arguments warning"), + parent->tr("You tried to manually set a JVM memory option (using " + " \"-XX:PermSize\", \"-Xmx\" or \"-Xms\") - there" + " are dedicated boxes for these in the settings (Java" + " tab, in the Memory group at the top).\n" + "Your manual settings will be overridden by the" + " dedicated options.\n" + "This message will be displayed until you remove them" + " from the JVM arguments."), + QMessageBox::Warning)->exec(); } } } diff --git a/logic/NostalgiaInstance.cpp b/logic/NostalgiaInstance.cpp index efd8f46b..2e23ee71 100644 --- a/logic/NostalgiaInstance.cpp +++ b/logic/NostalgiaInstance.cpp @@ -1,9 +1,24 @@ +/* Copyright 2013 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 "NostalgiaInstance.h" -NostalgiaInstance::NostalgiaInstance ( const QString& rootDir, SettingsObject* settings, QObject* parent ) - : OneSixInstance ( rootDir, settings, parent ) +NostalgiaInstance::NostalgiaInstance(const QString &rootDir, SettingsObject *settings, + QObject *parent) + : OneSixInstance(rootDir, settings, parent) { - } QString NostalgiaInstance::getStatusbarDescription() @@ -15,8 +30,3 @@ bool NostalgiaInstance::menuActionEnabled(QString action_name) const { return false; } - -/* -ADD MORE - IF REQUIRED -*/ diff --git a/logic/NostalgiaInstance.h b/logic/NostalgiaInstance.h index 64eb7a81..a26f7f0a 100644 --- a/logic/NostalgiaInstance.h +++ b/logic/NostalgiaInstance.h @@ -1,3 +1,18 @@ +/* Copyright 2013 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 "OneSixInstance.h" @@ -6,8 +21,8 @@ class NostalgiaInstance : public OneSixInstance { Q_OBJECT public: - explicit NostalgiaInstance(const QString &rootDir, SettingsObject * settings, QObject *parent = 0); + explicit NostalgiaInstance(const QString &rootDir, SettingsObject *settings, + QObject *parent = 0); virtual QString getStatusbarDescription(); virtual bool menuActionEnabled(QString action_name) const; }; - diff --git a/logic/OneSixAssets.cpp b/logic/OneSixAssets.cpp index 500385ad..dbc42262 100644 --- a/logic/OneSixAssets.cpp +++ b/logic/OneSixAssets.cpp @@ -1,5 +1,20 @@ +/* Copyright 2013 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 -#include +#include "logger/QsLog.h" #include #include "OneSixAssets.h" #include "net/NetJob.h" @@ -70,7 +85,7 @@ void OneSixAssets::S3BucketFinished() auto metacache = MMC->metacache(); - for (auto object: objectList) + for (auto object : objectList) { // Filter folder keys (zero size) if (object.size == 0) @@ -99,8 +114,7 @@ void OneSixAssets::S3BucketFinished() void OneSixAssets::start() { auto job = new NetJob("Assets index"); - job->addNetAction( - S3ListBucket::make(QUrl("http://s3.amazonaws.com/Minecraft.Resources/"))); + job->addNetAction(S3ListBucket::make(QUrl("http://s3.amazonaws.com/Minecraft.Resources/"))); connect(job, SIGNAL(succeeded()), SLOT(S3BucketFinished())); connect(job, SIGNAL(failed()), SIGNAL(failed())); emit indexStarted(); diff --git a/logic/OneSixAssets.h b/logic/OneSixAssets.h index 72e8a843..948068b8 100644 --- a/logic/OneSixAssets.h +++ b/logic/OneSixAssets.h @@ -1,3 +1,18 @@ +/* Copyright 2013 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 "net/NetJob.h" @@ -14,13 +29,16 @@ signals: void filesStarted(); void filesProgress(int, int, int); -public slots: +public +slots: void S3BucketFinished(); void downloadFinished(); + public: void start(); + private: - ThreadedDeleter * deleter; + ThreadedDeleter *deleter; QStringList nuke_whitelist; NetJobPtr index_job; NetJobPtr files_job; diff --git a/logic/OneSixInstance.cpp b/logic/OneSixInstance.cpp index 7539d8e5..5c93236b 100644 --- a/logic/OneSixInstance.cpp +++ b/logic/OneSixInstance.cpp @@ -1,3 +1,18 @@ +/* Copyright 2013 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 "OneSixInstance.h" #include "OneSixInstance_p.h" #include "OneSixUpdate.h" @@ -8,8 +23,8 @@ #include #include #include -#include -#include +#include "gui/dialogs/OneSixModEditDialog.h" +#include "logger/QsLog.h" OneSixInstance::OneSixInstance(const QString &rootDir, SettingsObject *setting_obj, QObject *parent) diff --git a/logic/OneSixInstance.h b/logic/OneSixInstance.h index d2276afc..2d02b605 100644 --- a/logic/OneSixInstance.h +++ b/logic/OneSixInstance.h @@ -1,7 +1,24 @@ +/* Copyright 2013 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 "BaseInstance.h" #include + +#include "BaseInstance.h" + class OneSixVersion; class BaseUpdate; class ModList; diff --git a/logic/OneSixInstance_p.h b/logic/OneSixInstance_p.h index 06737b6f..6b7ea431 100644 --- a/logic/OneSixInstance_p.h +++ b/logic/OneSixInstance_p.h @@ -1,11 +1,28 @@ +/* Copyright 2013 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 "BaseInstance_p.h" -#include "OneSixVersion.h" -#include "OneSixLibrary.h" -#include "ModList.h" +#include + +#include "logic/BaseInstance_p.h" +#include "logic/OneSixVersion.h" +#include "logic/OneSixLibrary.h" +#include "logic/ModList.h" -struct OneSixInstancePrivate: public BaseInstancePrivate +struct OneSixInstancePrivate : public BaseInstancePrivate { std::shared_ptr version; std::shared_ptr loader_mod_list; diff --git a/logic/OneSixLibrary.cpp b/logic/OneSixLibrary.cpp index 9c1caaa7..df04a0c7 100644 --- a/logic/OneSixLibrary.cpp +++ b/logic/OneSixLibrary.cpp @@ -1,7 +1,24 @@ +/* Copyright 2013 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 + #include "OneSixLibrary.h" #include "OneSixRule.h" #include "OpSys.h" -#include + void OneSixLibrary::finalize() { QStringList parts = m_name.split(':'); diff --git a/logic/OneSixLibrary.h b/logic/OneSixLibrary.h index 5e58ef89..3a772420 100644 --- a/logic/OneSixLibrary.h +++ b/logic/OneSixLibrary.h @@ -1,9 +1,26 @@ +/* Copyright 2013 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 #include #include -#include #include +#include + #include "OpSys.h" class Rule; @@ -14,7 +31,7 @@ private: // basic values used internally (so far) QString m_name; QString m_base_url = "http://s3.amazonaws.com/Minecraft.Download/libraries/"; - QList > m_rules; + QList> m_rules; // custom values /// absolute URL. takes precedence over m_download_path, if defined @@ -39,25 +56,26 @@ private: bool m_is_native = false; /// native suffixes per OS QMap m_native_suffixes; + public: QStringList extract_excludes; - + public: /// Constructor OneSixLibrary(QString name) { m_name = name; } - + QJsonObject toJson(); - + /** * finalize the library, processing the input values into derived values and state - * + * * This SHALL be called after all the values are parsed or after any further change. */ void finalize(); - + /// Set the library composite name void setName(QString name); /// get a decent-looking name @@ -77,13 +95,13 @@ public: } /// Set the url base for downloads void setBaseUrl(QString base_url); - + /// Call this to mark the library as 'native' (it's a zip archive with DLLs) void setIsNative(); /// Attach a name suffix to the specified OS native void addNative(OpSys os, QString suffix); /// Set the load rules - void setRules(QList > rules); + void setRules(QList> rules); /// Returns true if the library should be loaded (or extracted, in case of natives) bool isActive(); diff --git a/logic/OneSixRule.cpp b/logic/OneSixRule.cpp index cb64c9ba..d35be720 100644 --- a/logic/OneSixRule.cpp +++ b/logic/OneSixRule.cpp @@ -1,7 +1,23 @@ -#include "OneSixRule.h" +/* Copyright 2013 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 #include +#include "OneSixRule.h" + QList> rulesFromJsonV4(QJsonObject &objectWithRules) { QList> rules; diff --git a/logic/OneSixRule.h b/logic/OneSixRule.h index 6be01f1b..9cd1a226 100644 --- a/logic/OneSixRule.h +++ b/logic/OneSixRule.h @@ -1,7 +1,24 @@ +/* Copyright 2013 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 #include -#include "OneSixLibrary.h" + +#include "logic/OneSixLibrary.h" enum RuleAction { @@ -17,19 +34,22 @@ class Rule { protected: RuleAction m_result; - virtual bool applies(OneSixLibrary * parent) = 0; + virtual bool applies(OneSixLibrary *parent) = 0; + public: - Rule(RuleAction result) - :m_result(result) {} - virtual ~Rule(){}; + Rule(RuleAction result) : m_result(result) + { + } + virtual ~Rule() {}; virtual QJsonObject toJson() = 0; - RuleAction apply(OneSixLibrary * parent) + RuleAction apply(OneSixLibrary *parent) { - if(applies(parent)) + if (applies(parent)) return m_result; else return Defer; - }; + } + ; }; class OsRule : public Rule @@ -39,34 +59,41 @@ private: OpSys m_system; // the OS version regexp QString m_version_regexp; + protected: - virtual bool applies ( OneSixLibrary* ) + virtual bool applies(OneSixLibrary *) { return (m_system == currentSystem); } OsRule(RuleAction result, OpSys system, QString version_regexp) - : Rule(result), m_system(system), m_version_regexp(version_regexp) {} + : Rule(result), m_system(system), m_version_regexp(version_regexp) + { + } + public: virtual QJsonObject toJson(); - static std::shared_ptr create(RuleAction result, OpSys system, QString version_regexp) + static std::shared_ptr create(RuleAction result, OpSys system, + QString version_regexp) { - return std::shared_ptr (new OsRule(result, system, version_regexp)); + return std::shared_ptr(new OsRule(result, system, version_regexp)); } }; class ImplicitRule : public Rule { protected: - virtual bool applies ( OneSixLibrary* ) + virtual bool applies(OneSixLibrary *) { return true; } - ImplicitRule(RuleAction result) - : Rule(result) {} + ImplicitRule(RuleAction result) : Rule(result) + { + } + public: virtual QJsonObject toJson(); static std::shared_ptr create(RuleAction result) { - return std::shared_ptr (new ImplicitRule(result)); + return std::shared_ptr(new ImplicitRule(result)); } }; diff --git a/logic/OneSixUpdate.cpp b/logic/OneSixUpdate.cpp index 5c421fbf..2d8a167c 100644 --- a/logic/OneSixUpdate.cpp +++ b/logic/OneSixUpdate.cpp @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #include "MultiMC.h" #include "OneSixUpdate.h" diff --git a/logic/OneSixUpdate.h b/logic/OneSixUpdate.h index 7c6fce1b..e5f553c7 100644 --- a/logic/OneSixUpdate.h +++ b/logic/OneSixUpdate.h @@ -3,7 +3,7 @@ * 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 @@ -18,10 +18,10 @@ #include #include #include -#include "net/NetJob.h" -#include "tasks/Task.h" -#include "BaseUpdate.h" +#include "logic/net/NetJob.h" +#include "logic/tasks/Task.h" +#include "logic/BaseUpdate.h" class MinecraftVersion; class BaseInstance; @@ -32,22 +32,21 @@ class OneSixUpdate : public BaseUpdate public: explicit OneSixUpdate(BaseInstance *inst, QObject *parent = 0); virtual void executeTask(); - -private slots: + +private +slots: void versionFileStart(); void versionFileFinished(); void versionFileFailed(); - + void jarlibStart(); void jarlibFinished(); void jarlibFailed(); - + private: NetJobPtr specificVersionDownloadJob; NetJobPtr jarlibDownloadJob; - + // target version, determined during this task std::shared_ptr targetVersion; }; - - diff --git a/logic/OneSixVersion.cpp b/logic/OneSixVersion.cpp index 51958389..01bf41f4 100644 --- a/logic/OneSixVersion.cpp +++ b/logic/OneSixVersion.cpp @@ -1,9 +1,24 @@ -#include "OneSixVersion.h" -#include "OneSixLibrary.h" -#include "OneSixRule.h" +/* Copyright 2013 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 "logic/OneSixVersion.h" +#include "logic/OneSixLibrary.h" +#include "logic/OneSixRule.h" std::shared_ptr fromJsonV4(QJsonObject root, - std::shared_ptr fullVersion) + std::shared_ptr fullVersion) { fullVersion->id = root.value("id").toString(); @@ -82,7 +97,7 @@ std::shared_ptr fromJsonV4(QJsonObject root, { library->setAbsoluteUrl(urlAbsVal.toString()); } - else if(urlAbsuVal.isString()) + else if (urlAbsuVal.isString()) { library->setAbsoluteUrl(urlAbsuVal.toString()); } @@ -167,7 +182,7 @@ std::shared_ptr OneSixVersion::fromFile(QString filepath) } QJsonObject root = jsonDoc.object(); auto version = fromJson(root); - if(version) + if (version) version->original_file = filepath; return version; } @@ -192,11 +207,11 @@ bool OneSixVersion::toOriginalFile() // screw processArguments root.insert("releaseTime", releaseTime); QJsonArray libarray; - for(const auto & lib: libraries) + for (const auto &lib : libraries) { libarray.append(lib->toJson()); } - if(libarray.count()) + if (libarray.count()) root.insert("libraries", libarray); QJsonDocument doc(root); file.write(doc.toJson()); diff --git a/logic/OneSixVersion.h b/logic/OneSixVersion.h index 3529138c..5718dafe 100644 --- a/logic/OneSixVersion.h +++ b/logic/OneSixVersion.h @@ -1,3 +1,18 @@ +/* Copyright 2013 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 #include @@ -86,6 +101,4 @@ public: } */ // QList rules; - - }; diff --git a/logic/OpSys.cpp b/logic/OpSys.cpp index f101fd08..e001b7f3 100644 --- a/logic/OpSys.cpp +++ b/logic/OpSys.cpp @@ -1,23 +1,42 @@ +/* Copyright 2013 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 "OpSys.h" OpSys OpSys_fromString(QString name) { - if(name == "linux") + if (name == "linux") return Os_Linux; - if(name == "windows") + if (name == "windows") return Os_Windows; - if(name == "osx") + if (name == "osx") return Os_OSX; return Os_Other; } QString OpSys_toString(OpSys name) { - switch(name) + switch (name) { - case Os_Linux: return "linux"; - case Os_OSX: return "osx"; - case Os_Windows: return "windows"; - default: return "other"; + case Os_Linux: + return "linux"; + case Os_OSX: + return "osx"; + case Os_Windows: + return "windows"; + default: + return "other"; } } \ No newline at end of file diff --git a/logic/OpSys.h b/logic/OpSys.h index aaa2eb65..363c87d7 100644 --- a/logic/OpSys.h +++ b/logic/OpSys.h @@ -1,3 +1,18 @@ +/* Copyright 2013 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 enum OpSys @@ -12,11 +27,11 @@ OpSys OpSys_fromString(QString); QString OpSys_toString(OpSys); #ifdef Q_OS_WIN32 - #define currentSystem Os_Windows +#define currentSystem Os_Windows +#else +#ifdef Q_OS_MAC +#define currentSystem Os_OSX #else - #ifdef Q_OS_MAC - #define currentSystem Os_OSX - #else - #define currentSystem Os_Linux - #endif +#define currentSystem Os_Linux +#endif #endif \ No newline at end of file diff --git a/logic/lists/BaseVersionList.cpp b/logic/lists/BaseVersionList.cpp index 61da5eeb..6e2c5282 100644 --- a/logic/lists/BaseVersionList.cpp +++ b/logic/lists/BaseVersionList.cpp @@ -3,7 +3,7 @@ * 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 @@ -16,12 +16,11 @@ #include "logic/lists/BaseVersionList.h" #include "logic/BaseVersion.h" -BaseVersionList::BaseVersionList(QObject *parent) : - QAbstractListModel(parent) +BaseVersionList::BaseVersionList(QObject *parent) : QAbstractListModel(parent) { } -BaseVersionPtr BaseVersionList::findVersion( const QString& descriptor ) +BaseVersionPtr BaseVersionList::findVersion(const QString &descriptor) { for (int i = 0; i < count(); i++) { @@ -43,13 +42,12 @@ 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 Qt::DisplayRole: @@ -57,20 +55,20 @@ QVariant BaseVersionList::data(const QModelIndex &index, int role) const { case NameColumn: return version->name(); - + case TypeColumn: return version->typeString(); - + default: return QVariant(); } - + case Qt::ToolTipRole: return version->descriptor(); - + case VersionPointerRole: return qVariantFromValue(version); - + default: return QVariant(); } @@ -85,27 +83,27 @@ QVariant BaseVersionList::headerData(int section, Qt::Orientation orientation, i { case NameColumn: return "Name"; - + case TypeColumn: return "Type"; - + default: return QVariant(); } - + case Qt::ToolTipRole: switch (section) { case NameColumn: return "The name of the version."; - + case TypeColumn: return "The version's type."; - + default: return QVariant(); } - + default: return QVariant(); } diff --git a/logic/lists/BaseVersionList.h b/logic/lists/BaseVersionList.h index d37431ed..5ac9369b 100644 --- a/logic/lists/BaseVersionList.h +++ b/logic/lists/BaseVersionList.h @@ -3,7 +3,7 @@ * 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 @@ -25,12 +25,12 @@ class Task; /*! - * \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 + * \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 @@ -44,21 +44,21 @@ public: { VersionPointerRole = 0x34B1CB48 }; - + enum VListColumns { // First column - Name NameColumn = 0, - + // Second column - Type TypeColumn, - + // Third column - Timestamp TimeColumn }; - + explicit BaseVersionList(QObject *parent = 0); - + /*! * \brief Gets a task that will reload the version list. * Simply execute the task to load the list. @@ -66,24 +66,23 @@ public: * \return A pointer to a task that reloads the version list. */ virtual Task *getLoadTask() = 0; - - //! Checks whether or not the list is loaded. If this returns false, the list should be loaded. + + //! 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 //////// virtual QVariant data(const QModelIndex &index, int role) const; virtual QVariant headerData(int section, Qt::Orientation orientation, int role) const; virtual int rowCount(const QModelIndex &parent) const; virtual int columnCount(const QModelIndex &parent) const; - - + /*! * \brief Finds a version by its descriptor. * \param The descriptor of the version to find. @@ -91,20 +90,21 @@ public: * one doesn't exist. */ virtual BaseVersionPtr findVersion(const QString &descriptor); - + /*! * \brief Gets the latest stable version of this instance type. * This is the version that will be selected by default. * By default, this is simply the first version in the list. */ virtual BaseVersionPtr getLatestStable() const; - + /*! * Sorts the version list. */ virtual void sort() = 0; - -protected slots: + +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 @@ -117,5 +117,5 @@ protected slots: * then copies the versions and sets their parents correctly. * \param versions List of versions whose parents should be set. */ - virtual void updateListData(QList versions) = 0; + virtual void updateListData(QList versions) = 0; }; diff --git a/logic/lists/ForgeVersionList.cpp b/logic/lists/ForgeVersionList.cpp index 27f567cd..b5e421af 100644 --- a/logic/lists/ForgeVersionList.cpp +++ b/logic/lists/ForgeVersionList.cpp @@ -21,7 +21,7 @@ #include #include -#include +#include "logger/QsLog.h" #define JSON_URL "http://files.minecraftforge.net/minecraftforge/json" diff --git a/logic/lists/ForgeVersionList.h b/logic/lists/ForgeVersionList.h index 52593f94..0d10e1f3 100644 --- a/logic/lists/ForgeVersionList.h +++ b/logic/lists/ForgeVersionList.h @@ -75,8 +75,7 @@ public: virtual BaseVersionPtr getLatestStable() const; virtual QVariant data(const QModelIndex &index, int role) const; - virtual QVariant headerData(int section, Qt::Orientation orientation, - int role) const; + virtual QVariant headerData(int section, Qt::Orientation orientation, int role) const; virtual int columnCount(const QModelIndex &parent) const; protected: diff --git a/logic/lists/IconList.cpp b/logic/lists/IconList.cpp index 6988d02f..ecfb8c3c 100644 --- a/logic/lists/IconList.cpp +++ b/logic/lists/IconList.cpp @@ -1,3 +1,18 @@ +/* Copyright 2013 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 #include @@ -27,22 +42,21 @@ public: } }; - IconList::IconList() : QAbstractListModel(), d(new Private()) { QDir instance_icons(":/icons/instances/"); auto file_info_list = instance_icons.entryInfoList(QDir::Files, QDir::Name); - for(auto file_info: file_info_list) + for (auto file_info : file_info_list) { QString key = file_info.baseName(); addIcon(key, key, file_info.absoluteFilePath(), true); } - + // FIXME: get from settings ensureFolderPathExists("icons"); QDir user_icons("icons"); file_info_list = user_icons.entryInfoList(QDir::Files, QDir::Name); - for(auto file_info: file_info_list) + for (auto file_info : file_info_list) { QString filename = file_info.absoluteFilePath(); QString key = file_info.baseName(); @@ -67,16 +81,17 @@ Qt::DropActions IconList::supportedDropActions() const return Qt::CopyAction; } -bool IconList::dropMimeData ( const QMimeData* data, Qt::DropAction action, int row, int column, const QModelIndex& parent ) +bool IconList::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, + const QModelIndex &parent) { if (action == Qt::IgnoreAction) - return true; + return true; // check if the action is supported if (!data || !(action & supportedDropActions())) return false; // files dropped from outside? - if(data->hasUrls()) + if (data->hasUrls()) { /* bool was_watching = is_watching; @@ -85,10 +100,10 @@ bool IconList::dropMimeData ( const QMimeData* data, Qt::DropAction action, int */ auto urls = data->urls(); QStringList iconFiles; - for(auto url: urls) + for (auto url : urls) { // only local files may be dropped... - if(!url.isLocalFile()) + if (!url.isLocalFile()) continue; iconFiles += url.toLocalFile(); } @@ -102,73 +117,73 @@ bool IconList::dropMimeData ( const QMimeData* data, Qt::DropAction action, int return false; } -Qt::ItemFlags IconList::flags ( const QModelIndex& index ) const +Qt::ItemFlags IconList::flags(const QModelIndex &index) const { - Qt::ItemFlags defaultFlags = QAbstractListModel::flags ( index ); + 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 +QVariant IconList::data(const QModelIndex &index, int role) const { - if(!index.isValid()) + if (!index.isValid()) return QVariant(); - + int row = index.row(); - - if(row < 0 || row >= d->icons.size()) + + if (row < 0 || row >= d->icons.size()) return QVariant(); - - switch(role) + + switch (role) { - case Qt::DecorationRole: - return d->icons[row].icon; - case Qt::DisplayRole: - return d->icons[row].name; - case Qt::UserRole: - return d->icons[row].key; - default: - return QVariant(); + case Qt::DecorationRole: + return d->icons[row].icon; + case Qt::DisplayRole: + return d->icons[row].name; + case Qt::UserRole: + return d->icons[row].key; + default: + return QVariant(); } } -int IconList::rowCount ( const QModelIndex& parent ) const +int IconList::rowCount(const QModelIndex &parent) const { return d->icons.size(); } -void IconList::installIcons ( QStringList iconFiles ) +void IconList::installIcons(QStringList iconFiles) { - for(QString file: iconFiles) + for (QString file : iconFiles) { QFileInfo fileinfo(file); - if(!fileinfo.isReadable() || !fileinfo.isFile()) + if (!fileinfo.isReadable() || !fileinfo.isFile()) continue; QString target = PathCombine("icons", fileinfo.fileName()); - + QString suffix = fileinfo.suffix(); - if(suffix != "jpeg" && suffix != "png" && suffix != "jpg") + if (suffix != "jpeg" && suffix != "png" && suffix != "jpg") continue; - - if(!QFile::copy(file, target)) + + if (!QFile::copy(file, target)) continue; - + QString key = fileinfo.baseName(); addIcon(key, key, target); } } -bool IconList::deleteIcon ( QString key ) +bool IconList::deleteIcon(QString key) { int iconIdx = getIconIndex(key); - if(iconIdx == -1) + if (iconIdx == -1) return false; - auto & iconEntry = d->icons[iconIdx]; - if(iconEntry.is_builtin) + auto &iconEntry = d->icons[iconIdx]; + if (iconEntry.is_builtin) return false; - if(QFile::remove(iconEntry.filename)) + if (QFile::remove(iconEntry.filename)) { beginRemoveRows(QModelIndex(), iconIdx, iconIdx); d->icons.remove(iconIdx); @@ -178,35 +193,36 @@ bool IconList::deleteIcon ( QString key ) return true; } -bool IconList::addIcon ( QString key, QString name, QString path, bool is_builtin ) +bool IconList::addIcon(QString key, QString name, QString path, bool is_builtin) { auto iter = d->index.find(key); - if(iter != d->index.end()) + if (iter != d->index.end()) { - if(d->icons[*iter].is_builtin) + if (d->icons[*iter].is_builtin) return false; - + QIcon icon(path); - if(icon.isNull()) + if (icon.isNull()) return false; - - auto & oldOne = d->icons[*iter]; - - if(!QFile::remove(oldOne.filename)) + + auto &oldOne = d->icons[*iter]; + + if (!QFile::remove(oldOne.filename)) return false; // replace the icon oldOne = {key, name, icon, is_builtin, path}; - dataChanged(index(*iter),index(*iter)); + dataChanged(index(*iter), index(*iter)); return true; } else { QIcon icon(path); - if(icon.isNull()) return false; - + if (icon.isNull()) + return false; + // add a new icon - beginInsertRows(QModelIndex(), d->icons.size(),d->icons.size()); + beginInsertRows(QModelIndex(), d->icons.size(), d->icons.size()); d->icons.push_back({key, name, icon, is_builtin, path}); d->index[key] = d->icons.size() - 1; endInsertRows(); @@ -218,39 +234,37 @@ void IconList::reindex() { d->index.clear(); int i = 0; - for(auto& iter: d->icons) + for (auto &iter : d->icons) { d->index[iter.key] = i; i++; } } - -QIcon IconList::getIcon ( QString key ) +QIcon IconList::getIcon(QString key) { int icon_index = getIconIndex(key); - if(icon_index != -1) + if (icon_index != -1) return d->icons[icon_index].icon; - + // Fallback for icons that don't exist. icon_index = getIconIndex("infinity"); - - if(icon_index != -1) + + if (icon_index != -1) return d->icons[icon_index].icon; return QIcon(); } -int IconList::getIconIndex ( QString key ) +int IconList::getIconIndex(QString key) { - if(key == "default") + if (key == "default") key = "infinity"; - + auto iter = d->index.find(key); - if(iter != d->index.end()) + if (iter != d->index.end()) return *iter; - - + return -1; } diff --git a/logic/lists/IconList.h b/logic/lists/IconList.h index cad80cdf..40ad043b 100644 --- a/logic/lists/IconList.h +++ b/logic/lists/IconList.h @@ -1,3 +1,18 @@ +/* Copyright 2013 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 @@ -11,28 +26,29 @@ class IconList : public QAbstractListModel public: IconList(); virtual ~IconList(); - - QIcon getIcon ( QString key ); - int getIconIndex ( QString key ); - - virtual QVariant data ( const QModelIndex& index, int role = Qt::DisplayRole ) const; - virtual int rowCount ( const QModelIndex& parent = QModelIndex() ) const; - + + QIcon getIcon(QString key); + int getIconIndex(QString key); + + virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; + virtual int rowCount(const QModelIndex &parent = QModelIndex()) const; + bool addIcon(QString key, QString name, QString path, bool is_builtin = false); bool deleteIcon(QString key); - + virtual QStringList mimeTypes() const; virtual Qt::DropActions supportedDropActions() const; - virtual bool dropMimeData ( const QMimeData* data, Qt::DropAction action, int row, int column, const QModelIndex& parent ); - virtual Qt::ItemFlags flags ( const QModelIndex& index ) const; - - void installIcons ( QStringList iconFiles ); - + virtual bool dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, + const QModelIndex &parent); + virtual Qt::ItemFlags flags(const QModelIndex &index) const; + + void installIcons(QStringList iconFiles); + private: // hide copy constructor - IconList ( const IconList & ) = delete; + IconList(const IconList &) = delete; // hide assign op - IconList& operator= ( const IconList & ) = delete; + IconList &operator=(const IconList &) = delete; void reindex(); - Private* d; + Private *d; }; diff --git a/logic/lists/InstanceList.cpp b/logic/lists/InstanceList.cpp index b42d7b7a..4446ff22 100644 --- a/logic/lists/InstanceList.cpp +++ b/logic/lists/InstanceList.cpp @@ -29,7 +29,7 @@ #include "logic/lists/IconList.h" #include "logic/BaseInstance.h" #include "logic/InstanceFactory.h" -#include +#include "logger/QsLog.h" const static int GROUP_FILE_FORMAT_VERSION = 1; @@ -423,7 +423,7 @@ bool InstanceProxyModel::subSortLessThan(const QModelIndex &left, BaseInstance *pdataLeft = static_cast(left.internalPointer()); BaseInstance *pdataRight = static_cast(right.internalPointer()); QString sortMode = MMC->settings()->get("InstSortMode").toString(); - if(sortMode == "LastLaunch") + if (sortMode == "LastLaunch") { return pdataLeft->lastLaunch() > pdataRight->lastLaunch(); } diff --git a/logic/lists/InstanceList.h b/logic/lists/InstanceList.h index 3cde6bf5..c3e3561d 100644 --- a/logic/lists/InstanceList.h +++ b/logic/lists/InstanceList.h @@ -98,7 +98,7 @@ signals: public slots: - void on_InstFolderChanged(const Setting & setting, QVariant value); + void on_InstFolderChanged(const Setting &setting, QVariant value); private slots: diff --git a/logic/lists/JavaVersionList.cpp b/logic/lists/JavaVersionList.cpp index 5389c4cc..3dc1969b 100644 --- a/logic/lists/JavaVersionList.cpp +++ b/logic/lists/JavaVersionList.cpp @@ -20,7 +20,7 @@ #include #include -#include +#include "logger/QsLog.h" #include JavaVersionList::JavaVersionList(QObject *parent) : BaseVersionList(parent) @@ -32,7 +32,6 @@ Task *JavaVersionList::getLoadTask() return new JavaListLoadTask(this); } - const BaseVersionPtr JavaVersionList::at(int i) const { return m_vlist.at(i); @@ -187,11 +186,11 @@ void JavaListLoadTask::executeTask() QList javas = ju.FindJavaPaths(); QList javas_bvp; - for(int i = 0; i < javas.length(); i++) + for (int i = 0; i < javas.length(); i++) { BaseVersionPtr java = std::dynamic_pointer_cast(javas.at(i)); - if(java) + if (java) { javas_bvp.append(java); } diff --git a/logic/lists/JavaVersionList.h b/logic/lists/JavaVersionList.h index 23bccfe4..4826ca0c 100644 --- a/logic/lists/JavaVersionList.h +++ b/logic/lists/JavaVersionList.h @@ -64,11 +64,11 @@ public: virtual BaseVersionPtr getTopRecommended() const; virtual QVariant data(const QModelIndex &index, int role) const; - virtual QVariant headerData(int section, Qt::Orientation orientation, - int role) const; + virtual QVariant headerData(int section, Qt::Orientation orientation, int role) const; virtual int columnCount(const QModelIndex &parent) const; -public slots: +public +slots: virtual void updateListData(QList versions); protected: diff --git a/logic/lists/LwjglVersionList.cpp b/logic/lists/LwjglVersionList.cpp index 6bf401ec..3333e86c 100644 --- a/logic/lists/LwjglVersionList.cpp +++ b/logic/lists/LwjglVersionList.cpp @@ -20,7 +20,7 @@ #include #include -#include +#include "logger/QsLog.h" #define RSS_URL "http://sourceforge.net/api/file/index/project-id/58488/mtime/desc/rss" diff --git a/logic/lists/LwjglVersionList.h b/logic/lists/LwjglVersionList.h index 99712292..fa57e8eb 100644 --- a/logic/lists/LwjglVersionList.h +++ b/logic/lists/LwjglVersionList.h @@ -3,7 +3,7 @@ * 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 @@ -28,20 +28,30 @@ typedef std::shared_ptr PtrLWJGLVersion; class LWJGLVersion : public QObject { Q_OBJECT - - LWJGLVersion(const QString &name, const QString &url, QObject *parent = 0) : - QObject(parent), m_name(name), m_url(url) { } + + LWJGLVersion(const QString &name, const QString &url, QObject *parent = 0) + : QObject(parent), m_name(name), m_url(url) + { + } + public: - + static PtrLWJGLVersion Create(const QString &name, const QString &url, QObject *parent = 0) { return PtrLWJGLVersion(new LWJGLVersion(name, url, parent)); - }; - - QString name() const { return m_name; } - - QString url() const { return m_url; } - + } + ; + + QString name() const + { + return m_name; + } + + QString url() const + { + return m_url; + } + protected: QString m_name; QString m_url; @@ -52,64 +62,87 @@ class LWJGLVersionList : public QAbstractListModel Q_OBJECT public: explicit LWJGLVersionList(QObject *parent = 0); - - bool isLoaded() { return m_vlist.length() > 0; } - + + bool isLoaded() + { + return m_vlist.length() > 0; + } + const PtrLWJGLVersion getVersion(const QString &versionName); - PtrLWJGLVersion at(int index) { return m_vlist[index]; } - const PtrLWJGLVersion at(int index) const { return m_vlist[index]; } - - int count() const { return m_vlist.length(); } - + PtrLWJGLVersion at(int index) + { + return m_vlist[index]; + } + const PtrLWJGLVersion at(int index) const + { + return m_vlist[index]; + } + + int count() const + { + return m_vlist.length(); + } + virtual QVariant data(const QModelIndex &index, int role) const; virtual QVariant headerData(int section, Qt::Orientation orientation, int role) const; - virtual int rowCount(const QModelIndex &parent) const { return count(); } + virtual int rowCount(const QModelIndex &parent) const + { + return count(); + } virtual int columnCount(const QModelIndex &parent) const; - + virtual bool isLoading() const; - virtual bool errored() const { return m_errored; } - - virtual QString lastErrorMsg() const { return m_lastErrorMsg; } - -public slots: + virtual bool errored() const + { + return m_errored; + } + + virtual QString lastErrorMsg() const + { + return m_lastErrorMsg; + } + +public +slots: /*! * Loads the version list. * This is done asynchronously. On success, the loadListFinished() signal will - * be emitted. The list model will be reset as well, resulting in the modelReset() - * signal being emitted. Note that the model will be reset before loadListFinished() is emitted. + * be emitted. The list model will be reset as well, resulting in the modelReset() + * signal being emitted. Note that the model will be reset before loadListFinished() is + * emitted. * If loading the list failed, the loadListFailed(QString msg), * signal will be emitted. */ virtual void loadList(); - + signals: /*! * Emitted when the list either starts or finishes loading. * \param loading Whether or not the list is loading. */ void loadingStateUpdated(bool loading); - + void loadListFinished(); - + void loadListFailed(QString msg); - + private: QList m_vlist; - + QNetworkReply *m_netReply; QNetworkReply *reply; - + bool m_loading; bool m_errored; QString m_lastErrorMsg; - + void failed(QString msg); - + void finished(); - + void setLoading(bool loading); - -private slots: + +private +slots: virtual void netRequestComplete(); }; - diff --git a/logic/lists/MinecraftVersionList.cpp b/logic/lists/MinecraftVersionList.cpp index dd26714a..2a9c0d3b 100644 --- a/logic/lists/MinecraftVersionList.cpp +++ b/logic/lists/MinecraftVersionList.cpp @@ -1,4 +1,4 @@ -/* Copyright 2013 Andrew Okin +/* Copyright 2013 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,7 +14,7 @@ */ #include "MinecraftVersionList.h" -#include +#include "MultiMC.h" #include diff --git a/logic/lists/MinecraftVersionList.h b/logic/lists/MinecraftVersionList.h index ed68efbb..90b1ae86 100644 --- a/logic/lists/MinecraftVersionList.h +++ b/logic/lists/MinecraftVersionList.h @@ -1,9 +1,9 @@ -/* Copyright 2013 Andrew Okin +/* Copyright 2013 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 @@ -32,43 +32,44 @@ class MinecraftVersionList : public BaseVersionList Q_OBJECT public: friend class MCVListLoadTask; - + explicit MinecraftVersionList(QObject *parent = 0); - + virtual Task *getLoadTask(); virtual bool isLoaded(); virtual const BaseVersionPtr at(int i) const; virtual int count() const; virtual void sort(); - + virtual BaseVersionPtr getLatestStable() const; - + protected: QList m_vlist; - + bool m_loaded = false; - -protected slots: + +protected +slots: virtual void updateListData(QList versions); }; class MCVListLoadTask : public Task { Q_OBJECT - + public: explicit MCVListLoadTask(MinecraftVersionList *vlist); ~MCVListLoadTask(); - + virtual void executeTask(); - -protected slots: + +protected +slots: void list_downloaded(); - + protected: QNetworkReply *vlistReply; MinecraftVersionList *m_list; MinecraftVersion *m_currentStable; QSet legacyWhitelist; }; - diff --git a/logic/net/ByteArrayDownload.cpp b/logic/net/ByteArrayDownload.cpp index 25e6d51a..af5af8e9 100644 --- a/logic/net/ByteArrayDownload.cpp +++ b/logic/net/ByteArrayDownload.cpp @@ -1,6 +1,21 @@ +/* Copyright 2013 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 "ByteArrayDownload.h" #include "MultiMC.h" -#include +#include "logger/QsLog.h" ByteArrayDownload::ByteArrayDownload(QUrl url) : NetAction() { diff --git a/logic/net/ByteArrayDownload.h b/logic/net/ByteArrayDownload.h index fc32dc04..0d90abc2 100644 --- a/logic/net/ByteArrayDownload.h +++ b/logic/net/ByteArrayDownload.h @@ -1,3 +1,18 @@ +/* Copyright 2013 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 "NetAction.h" diff --git a/logic/net/CacheDownload.cpp b/logic/net/CacheDownload.cpp index f8769576..4fe4e68e 100644 --- a/logic/net/CacheDownload.cpp +++ b/logic/net/CacheDownload.cpp @@ -1,3 +1,18 @@ +/* Copyright 2013 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 "MultiMC.h" #include "CacheDownload.h" #include @@ -5,7 +20,7 @@ #include #include #include -#include +#include "logger/QsLog.h" CacheDownload::CacheDownload(QUrl url, MetaEntryPtr entry) : NetAction(), md5sum(QCryptographicHash::Md5) @@ -33,12 +48,13 @@ void CacheDownload::start() } QLOG_INFO() << "Downloading " << m_url.toString(); QNetworkRequest request(m_url); - if(m_entry->remote_changed_timestamp.size()) - request.setRawHeader(QString("If-Modified-Since").toLatin1(), m_entry->remote_changed_timestamp.toLatin1()); - if(m_entry->etag.size()) + if (m_entry->remote_changed_timestamp.size()) + request.setRawHeader(QString("If-Modified-Since").toLatin1(), + m_entry->remote_changed_timestamp.toLatin1()); + if (m_entry->etag.size()) request.setRawHeader(QString("If-None-Match").toLatin1(), m_entry->etag.toLatin1()); - request.setHeader(QNetworkRequest::UserAgentHeader,"MultiMC/5.0 (Cached)"); + request.setHeader(QNetworkRequest::UserAgentHeader, "MultiMC/5.0 (Cached)"); auto worker = MMC->qnam(); QNetworkReply *rep = worker->get(request); @@ -91,7 +107,7 @@ void CacheDownload::downloadFinished() QFileInfo output_file_info(m_target_path); m_entry->etag = m_reply->rawHeader("ETag").constData(); - if(m_reply->hasRawHeader("Last-Modified")) + if (m_reply->hasRawHeader("Last-Modified")) { m_entry->remote_changed_timestamp = m_reply->rawHeader("Last-Modified").constData(); } diff --git a/logic/net/CacheDownload.h b/logic/net/CacheDownload.h index 1e70874c..2b9a5dd8 100644 --- a/logic/net/CacheDownload.h +++ b/logic/net/CacheDownload.h @@ -1,3 +1,18 @@ +/* Copyright 2013 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 "NetAction.h" diff --git a/logic/net/FileDownload.cpp b/logic/net/FileDownload.cpp index eefdd4da..6b2aa66f 100644 --- a/logic/net/FileDownload.cpp +++ b/logic/net/FileDownload.cpp @@ -1,12 +1,25 @@ +/* Copyright 2013 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 "MultiMC.h" #include "FileDownload.h" #include #include -#include - +#include "logger/QsLog.h" -FileDownload::FileDownload ( QUrl url, QString target_path ) - :NetAction() +FileDownload::FileDownload(QUrl url, QString target_path) : NetAction() { m_url = url; m_target_path = target_path; @@ -18,15 +31,18 @@ FileDownload::FileDownload ( QUrl url, QString target_path ) void FileDownload::start() { QString filename = m_target_path; - m_output_file.setFileName ( filename ); + m_output_file.setFileName(filename); // if there already is a file and md5 checking is in effect and it can be opened - if ( m_output_file.exists() && m_output_file.open ( QIODevice::ReadOnly ) ) + if (m_output_file.exists() && m_output_file.open(QIODevice::ReadOnly)) { // check the md5 against the expected one - QString hash = QCryptographicHash::hash ( m_output_file.readAll(), QCryptographicHash::Md5 ).toHex().constData(); + QString hash = + QCryptographicHash::hash(m_output_file.readAll(), QCryptographicHash::Md5) + .toHex() + .constData(); m_output_file.close(); // skip this file if they match - if ( m_check_md5 && hash == m_expected_md5 ) + if (m_check_md5 && hash == m_expected_md5) { QLOG_INFO() << "Skipping " << m_url.toString() << ": md5 match."; emit succeeded(index_within_job); @@ -37,33 +53,35 @@ void FileDownload::start() m_expected_md5 = hash; } } - if(!ensureFilePathExists(filename)) + if (!ensureFilePathExists(filename)) { emit failed(index_within_job); return; } - + QLOG_INFO() << "Downloading " << m_url.toString(); - QNetworkRequest request ( m_url ); - request.setRawHeader(QString("If-None-Match").toLatin1(), m_expected_md5.toLatin1()); - request.setHeader(QNetworkRequest::UserAgentHeader,"MultiMC/5.0 (Uncached)"); - + QNetworkRequest request(m_url); + request.setRawHeader(QString("If-None-Match").toLatin1(), m_expected_md5.toLatin1()); + request.setHeader(QNetworkRequest::UserAgentHeader, "MultiMC/5.0 (Uncached)"); + auto worker = MMC->qnam(); - QNetworkReply * rep = worker->get ( request ); - - m_reply = std::shared_ptr ( rep ); - connect ( rep, SIGNAL ( downloadProgress ( qint64,qint64 ) ), SLOT ( downloadProgress ( qint64,qint64 ) ) ); - connect ( rep, SIGNAL ( finished() ), SLOT ( downloadFinished() ) ); - connect ( rep, SIGNAL ( error ( QNetworkReply::NetworkError ) ), SLOT ( downloadError ( QNetworkReply::NetworkError ) ) ); - connect ( rep, SIGNAL ( readyRead() ), SLOT ( downloadReadyRead() ) ); + QNetworkReply *rep = worker->get(request); + + m_reply = std::shared_ptr(rep); + connect(rep, SIGNAL(downloadProgress(qint64, qint64)), + SLOT(downloadProgress(qint64, qint64))); + connect(rep, SIGNAL(finished()), SLOT(downloadFinished())); + connect(rep, SIGNAL(error(QNetworkReply::NetworkError)), + SLOT(downloadError(QNetworkReply::NetworkError))); + connect(rep, SIGNAL(readyRead()), SLOT(downloadReadyRead())); } -void FileDownload::downloadProgress ( qint64 bytesReceived, qint64 bytesTotal ) +void FileDownload::downloadProgress(qint64 bytesReceived, qint64 bytesTotal) { - emit progress (index_within_job, bytesReceived, bytesTotal ); + emit progress(index_within_job, bytesReceived, bytesTotal); } -void FileDownload::downloadError ( QNetworkReply::NetworkError error ) +void FileDownload::downloadError(QNetworkReply::NetworkError error) { // error happened during download. // TODO: log the reason why @@ -73,7 +91,7 @@ void FileDownload::downloadError ( QNetworkReply::NetworkError error ) void FileDownload::downloadFinished() { // if the download succeeded - if ( m_status != Job_Failed ) + if (m_status != Job_Failed) { // nothing went wrong... m_status = Job_Finished; @@ -95,9 +113,9 @@ void FileDownload::downloadFinished() void FileDownload::downloadReadyRead() { - if(!m_opened_for_saving) + if (!m_opened_for_saving) { - if ( !m_output_file.open ( QIODevice::WriteOnly ) ) + if (!m_output_file.open(QIODevice::WriteOnly)) { /* * Can't open the file... the job failed @@ -108,5 +126,5 @@ void FileDownload::downloadReadyRead() } m_opened_for_saving = true; } - m_output_file.write ( m_reply->readAll() ); + m_output_file.write(m_reply->readAll()); } diff --git a/logic/net/FileDownload.h b/logic/net/FileDownload.h index 5f72587f..31e0259c 100644 --- a/logic/net/FileDownload.h +++ b/logic/net/FileDownload.h @@ -1,3 +1,18 @@ +/* Copyright 2013 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 "NetAction.h" diff --git a/logic/net/ForgeXzDownload.cpp b/logic/net/ForgeXzDownload.cpp index 20279d99..6c9d7a60 100644 --- a/logic/net/ForgeXzDownload.cpp +++ b/logic/net/ForgeXzDownload.cpp @@ -1,3 +1,18 @@ +/* Copyright 2013 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 "MultiMC.h" #include "ForgeXzDownload.h" #include @@ -5,10 +20,9 @@ #include #include #include -#include +#include "logger/QsLog.h" -ForgeXzDownload::ForgeXzDownload(QUrl url, MetaEntryPtr entry) - : NetAction() +ForgeXzDownload::ForgeXzDownload(QUrl url, MetaEntryPtr entry) : NetAction() { QString urlstr = url.toString(); urlstr.append(".pack.xz"); @@ -35,7 +49,7 @@ void ForgeXzDownload::start() QLOG_INFO() << "Downloading " << m_url.toString(); QNetworkRequest request(m_url); request.setRawHeader(QString("If-None-Match").toLatin1(), m_entry->etag.toLatin1()); - request.setHeader(QNetworkRequest::UserAgentHeader,"MultiMC/5.0 (Cached)"); + request.setHeader(QNetworkRequest::UserAgentHeader, "MultiMC/5.0 (Cached)"); auto worker = MMC->qnam(); QNetworkReply *rep = worker->get(request); @@ -96,7 +110,7 @@ void ForgeXzDownload::downloadFinished() void ForgeXzDownload::downloadReadyRead() { - + if (!m_opened_for_saving) { if (!m_pack200_xz_file.open()) @@ -154,7 +168,7 @@ void ForgeXzDownload::decompressAndInstall() { if (b.in_pos == b.in_size) { - b.in_size = m_pack200_xz_file.read((char*)in, sizeof(in)); + b.in_size = m_pack200_xz_file.read((char *)in, sizeof(in)); b.in_pos = 0; } @@ -162,7 +176,7 @@ void ForgeXzDownload::decompressAndInstall() if (b.out_pos == sizeof(out)) { - if (pack200_file.write((char*)out, b.out_pos) != b.out_pos) + if (pack200_file.write((char *)out, b.out_pos) != b.out_pos) { // msg = "Write error\n"; xz_dec_end(s); @@ -182,7 +196,7 @@ void ForgeXzDownload::decompressAndInstall() continue; } - if (pack200_file.write((char*)out, b.out_pos) != b.out_pos ) + if (pack200_file.write((char *)out, b.out_pos) != b.out_pos) { // write error pack200_file.close(); @@ -236,7 +250,7 @@ void ForgeXzDownload::decompressAndInstall() } } } - + // revert pack200 pack200_file.close(); QString pack_name = pack200_file.fileName(); @@ -244,16 +258,16 @@ void ForgeXzDownload::decompressAndInstall() { unpack_200(pack_name.toStdString(), m_target_path.toStdString()); } - catch(std::runtime_error & err) + catch (std::runtime_error &err) { QLOG_ERROR() << "Error unpacking " << pack_name.toUtf8() << " : " << err.what(); QFile f(m_target_path); - if(f.exists()) + if (f.exists()) f.remove(); emit failed(index_within_job); return; } - + QFile jar_file(m_target_path); if (!jar_file.open(QIODevice::ReadOnly)) @@ -263,10 +277,10 @@ void ForgeXzDownload::decompressAndInstall() return; } m_entry->md5sum = QCryptographicHash::hash(jar_file.readAll(), QCryptographicHash::Md5) - .toHex() - .constData(); + .toHex() + .constData(); jar_file.close(); - + QFileInfo output_file_info(m_target_path); m_entry->etag = m_reply->rawHeader("ETag").constData(); m_entry->local_changed_timestamp = diff --git a/logic/net/ForgeXzDownload.h b/logic/net/ForgeXzDownload.h index 0b73711e..9f1bb029 100644 --- a/logic/net/ForgeXzDownload.h +++ b/logic/net/ForgeXzDownload.h @@ -1,3 +1,18 @@ +/* Copyright 2013 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 "NetAction.h" diff --git a/logic/net/HttpMetaCache.cpp b/logic/net/HttpMetaCache.cpp index 5ba5b98d..29007951 100644 --- a/logic/net/HttpMetaCache.cpp +++ b/logic/net/HttpMetaCache.cpp @@ -1,3 +1,18 @@ +/* Copyright 2013 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 "MultiMC.h" #include "HttpMetaCache.h" #include @@ -9,7 +24,7 @@ #include #include -#include +#include "logger/QsLog.h" #include #include @@ -20,14 +35,12 @@ QString MetaEntry::getFullPath() return PathCombine(MMC->metacache()->getBasePath(base), path); } - -HttpMetaCache::HttpMetaCache(QString path) - :QObject() +HttpMetaCache::HttpMetaCache(QString path) : QObject() { m_index_file = path; saveBatchingTimer.setSingleShot(true); saveBatchingTimer.setTimerType(Qt::VeryCoarseTimer); - connect(&saveBatchingTimer,SIGNAL(timeout()),SLOT(SaveNow())); + connect(&saveBatchingTimer, SIGNAL(timeout()), SLOT(SaveNow())); } HttpMetaCache::~HttpMetaCache() @@ -36,58 +49,61 @@ HttpMetaCache::~HttpMetaCache() SaveNow(); } -MetaEntryPtr HttpMetaCache::getEntry ( QString base, QString resource_path ) +MetaEntryPtr HttpMetaCache::getEntry(QString base, QString resource_path) { // no base. no base path. can't store - if(!m_entries.contains(base)) + if (!m_entries.contains(base)) { // TODO: log problem return MetaEntryPtr(); } - EntryMap & map = m_entries[base]; - if(map.entry_list.contains(resource_path)) + EntryMap &map = m_entries[base]; + if (map.entry_list.contains(resource_path)) { return map.entry_list[resource_path]; } return MetaEntryPtr(); } -MetaEntryPtr HttpMetaCache::resolveEntry ( QString base, QString resource_path, QString expected_etag ) +MetaEntryPtr HttpMetaCache::resolveEntry(QString base, QString resource_path, + QString expected_etag) { auto entry = getEntry(base, resource_path); // it's not present? generate a default stale entry - if(!entry) + if (!entry) { return staleEntry(base, resource_path); } - - auto & selected_base = m_entries[base]; + + auto &selected_base = m_entries[base]; QString real_path = PathCombine(selected_base.base_path, resource_path); QFileInfo finfo(real_path); - + // is the file really there? if not -> stale - if(!finfo.isFile() || !finfo.isReadable()) + if (!finfo.isFile() || !finfo.isReadable()) { // if the file doesn't exist, we disown the entry selected_base.entry_list.remove(resource_path); return staleEntry(base, resource_path); } - - if(!expected_etag.isEmpty() && expected_etag != entry->etag) + + if (!expected_etag.isEmpty() && expected_etag != entry->etag) { // if the etag doesn't match expected, we disown the entry selected_base.entry_list.remove(resource_path); return staleEntry(base, resource_path); } - + // if the file changed, check md5sum qint64 file_last_changed = finfo.lastModified().toUTC().toMSecsSinceEpoch(); - if(file_last_changed != entry->local_changed_timestamp) + if (file_last_changed != entry->local_changed_timestamp) { QFile input(real_path); input.open(QIODevice::ReadOnly); - QString md5sum = QCryptographicHash::hash(input.readAll(), QCryptographicHash::Md5).toHex().constData(); - if(entry->md5sum != md5sum) + QString md5sum = QCryptographicHash::hash(input.readAll(), QCryptographicHash::Md5) + .toHex() + .constData(); + if (entry->md5sum != md5sum) { selected_base.entry_list.remove(resource_path); return staleEntry(base, resource_path); @@ -101,14 +117,15 @@ MetaEntryPtr HttpMetaCache::resolveEntry ( QString base, QString resource_path, return entry; } -bool HttpMetaCache::updateEntry ( MetaEntryPtr stale_entry ) +bool HttpMetaCache::updateEntry(MetaEntryPtr stale_entry) { - if(!m_entries.contains(stale_entry->base)) + if (!m_entries.contains(stale_entry->base)) { - QLOG_ERROR() << "Cannot add entry with unknown base: " << stale_entry->base.toLocal8Bit(); + QLOG_ERROR() << "Cannot add entry with unknown base: " + << stale_entry->base.toLocal8Bit(); return false; } - if(stale_entry->stale) + if (stale_entry->stale) { QLOG_ERROR() << "Cannot add stale entry: " << stale_entry->getFullPath().toLocal8Bit(); return false; @@ -127,10 +144,10 @@ MetaEntryPtr HttpMetaCache::staleEntry(QString base, QString resource_path) return MetaEntryPtr(foo); } -void HttpMetaCache::addBase ( QString base, QString base_root ) +void HttpMetaCache::addBase(QString base, QString base_root) { // TODO: report error - if(m_entries.contains(base)) + if (m_entries.contains(base)) return; // TODO: check if the base path is valid EntryMap foo; @@ -138,57 +155,57 @@ void HttpMetaCache::addBase ( QString base, QString base_root ) m_entries[base] = foo; } -QString HttpMetaCache::getBasePath ( QString base ) +QString HttpMetaCache::getBasePath(QString base) { - if(m_entries.contains(base)) + if (m_entries.contains(base)) { return m_entries[base].base_path; } return QString(); } - void HttpMetaCache::Load() { QFile index(m_index_file); - if(!index.open(QIODevice::ReadOnly)) + if (!index.open(QIODevice::ReadOnly)) return; - + QJsonDocument json = QJsonDocument::fromJson(index.readAll()); - if(!json.isObject()) + if (!json.isObject()) return; auto root = json.object(); // check file version first - auto version_val =root.value("version"); - if(!version_val.isString()) + auto version_val = root.value("version"); + if (!version_val.isString()) return; - if(version_val.toString() != "1") + if (version_val.toString() != "1") return; - + // read the entry array - auto entries_val =root.value("entries"); - if(!entries_val.isArray()) + auto entries_val = root.value("entries"); + if (!entries_val.isArray()) return; QJsonArray array = entries_val.toArray(); - for(auto element: array) + for (auto element : array) { - if(!element.isObject()) + if (!element.isObject()) return; auto element_obj = element.toObject(); QString base = element_obj.value("base").toString(); - if(!m_entries.contains(base)) + if (!m_entries.contains(base)) continue; - auto & entrymap = m_entries[base]; + auto &entrymap = m_entries[base]; auto foo = new MetaEntry; foo->base = base; QString path = foo->path = element_obj.value("path").toString(); foo->md5sum = element_obj.value("md5sum").toString(); foo->etag = element_obj.value("etag").toString(); foo->local_changed_timestamp = element_obj.value("last_changed_timestamp").toDouble(); - foo->remote_changed_timestamp = element_obj.value("remote_changed_timestamp").toString(); + foo->remote_changed_timestamp = + element_obj.value("remote_changed_timestamp").toString(); // presumed innocent until closer examination foo->stale = false; - entrymap.entry_list[path] = MetaEntryPtr( foo ); + entrymap.entry_list[path] = MetaEntryPtr(foo); } } @@ -202,33 +219,35 @@ void HttpMetaCache::SaveEventually() void HttpMetaCache::SaveNow() { QSaveFile tfile(m_index_file); - if(!tfile.open(QIODevice::WriteOnly | QIODevice::Truncate)) + if (!tfile.open(QIODevice::WriteOnly | QIODevice::Truncate)) return; QJsonObject toplevel; - toplevel.insert("version",QJsonValue(QString("1"))); + toplevel.insert("version", QJsonValue(QString("1"))); QJsonArray entriesArr; - for(auto group : m_entries) + for (auto group : m_entries) { - for(auto entry : group.entry_list) + for (auto entry : group.entry_list) { QJsonObject entryObj; entryObj.insert("base", QJsonValue(entry->base)); entryObj.insert("path", QJsonValue(entry->path)); entryObj.insert("md5sum", QJsonValue(entry->md5sum)); entryObj.insert("etag", QJsonValue(entry->etag)); - entryObj.insert("last_changed_timestamp", QJsonValue(double(entry->local_changed_timestamp))); - if(!entry->remote_changed_timestamp.isEmpty()) - entryObj.insert("remote_changed_timestamp", QJsonValue(entry->remote_changed_timestamp)); + entryObj.insert("last_changed_timestamp", + QJsonValue(double(entry->local_changed_timestamp))); + if (!entry->remote_changed_timestamp.isEmpty()) + entryObj.insert("remote_changed_timestamp", + QJsonValue(entry->remote_changed_timestamp)); entriesArr.append(entryObj); } } - toplevel.insert("entries",entriesArr); + toplevel.insert("entries", entriesArr); QJsonDocument doc(toplevel); QByteArray jsonData = doc.toJson(); qint64 result = tfile.write(jsonData); - if(result == -1) + if (result == -1) return; - if(result != jsonData.size()) + if (result != jsonData.size()) return; tfile.commit(); } diff --git a/logic/net/HttpMetaCache.h b/logic/net/HttpMetaCache.h index 557d9298..e91d2684 100644 --- a/logic/net/HttpMetaCache.h +++ b/logic/net/HttpMetaCache.h @@ -1,3 +1,18 @@ +/* Copyright 2013 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 #include diff --git a/logic/net/LoginTask.cpp b/logic/net/LoginTask.cpp index 5717aa9f..4a789bb4 100644 --- a/logic/net/LoginTask.cpp +++ b/logic/net/LoginTask.cpp @@ -100,7 +100,9 @@ void LoginTask::processYggdrasilReply(QNetworkReply *reply) processReply(reply, &LoginTask::parseYggdrasilReply, &LoginTask::parseYggdrasilError); } -void LoginTask::processReply(QNetworkReply *reply, std::function parser, std::function errorHandler) +void LoginTask::processReply(QNetworkReply *reply, + std::function parser, + std::function errorHandler) { if (netReply != reply) return; @@ -147,7 +149,7 @@ QString LoginTask::parseLegacyError(QNetworkReply *reply) case 503: return tr("The login servers are currently unavailable. Check " - "http://help.mojang.com/ for more info."); + "http://help.mojang.com/ for more info."); default: QLOG_DEBUG() << "Login failed with QNetworkReply code:" << reply->error(); @@ -161,7 +163,8 @@ QString LoginTask::parseYggdrasilError(QNetworkReply *reply) QJsonParseError jsonError; QJsonDocument jsonDoc = QJsonDocument::fromJson(data, &jsonError); - // If there are JSON errors fall back to using the legacy error handling using HTTP status codes + // If there are JSON errors fall back to using the legacy error handling using HTTP status + // codes if (jsonError.error != QJsonParseError::NoError) { return parseLegacyError(reply); @@ -174,10 +177,10 @@ QString LoginTask::parseYggdrasilError(QNetworkReply *reply) QJsonObject root = jsonDoc.object(); - //QString error = root.value("error").toString(); + // QString error = root.value("error").toString(); QString errorMessage = root.value("errorMessage").toString(); - if(errorMessage.isEmpty()) + if (errorMessage.isEmpty()) { return parseLegacyError(reply); } @@ -230,14 +233,14 @@ void LoginTask::yggdrasilLogin() "accessToken": "random access token", // hexadecimal "clientToken": "client identifier", // identical to the one received "availableProfiles": [ // only present if the agent field was received - { - "id": "profile identifier", // hexadecimal - "name": "player name" - } + { + "id": "profile identifier", // hexadecimal + "name": "player name" + } ], "selectedProfile": { // only present if the agent field was received - "id": "profile identifier", - "name": "player name" + "id": "profile identifier", + "name": "player name" } } */ @@ -264,7 +267,7 @@ void LoginTask::parseYggdrasilReply(QByteArray data) QString playerID; QString playerName; auto selectedProfile = root.value("selectedProfile"); - if(selectedProfile.isObject()) + if (selectedProfile.isObject()) { auto selectedProfileO = selectedProfile.toObject(); playerID = selectedProfileO.value("id").toString(); @@ -281,7 +284,7 @@ void LoginTask::parseYggdrasilReply(QByteArray data) QString client_id; }; */ - + result = {uInfo.username, sessionID, playerName, playerID, accessToken}; emitSucceeded(); } diff --git a/logic/net/LoginTask.h b/logic/net/LoginTask.h index aa925999..26ac0808 100644 --- a/logic/net/LoginTask.h +++ b/logic/net/LoginTask.h @@ -45,7 +45,8 @@ public: return result; } -protected slots: +protected +slots: void legacyLogin(); void processLegacyReply(QNetworkReply *reply); void parseLegacyReply(QByteArray data); @@ -56,7 +57,8 @@ protected slots: void parseYggdrasilReply(QByteArray data); QString parseYggdrasilError(QNetworkReply *reply); - void processReply(QNetworkReply *reply, std::function, std::function); + void processReply(QNetworkReply *reply, std::function, + std::function); protected: void executeTask(); diff --git a/logic/net/NetAction.h b/logic/net/NetAction.h index b7c922f5..c96d8f8f 100644 --- a/logic/net/NetAction.h +++ b/logic/net/NetAction.h @@ -1,3 +1,18 @@ +/* Copyright 2013 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 @@ -42,12 +57,14 @@ signals: void succeeded(int index); void failed(int index); -protected slots: +protected +slots: virtual void downloadProgress(qint64 bytesReceived, qint64 bytesTotal) = 0; virtual void downloadError(QNetworkReply::NetworkError error) = 0; virtual void downloadFinished() = 0; virtual void downloadReadyRead() = 0; -public slots: +public +slots: virtual void start() = 0; }; diff --git a/logic/net/NetJob.cpp b/logic/net/NetJob.cpp index c7ca4409..21c6d3f7 100644 --- a/logic/net/NetJob.cpp +++ b/logic/net/NetJob.cpp @@ -1,3 +1,18 @@ +/* Copyright 2013 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 "NetJob.h" #include "pathutils.h" #include "MultiMC.h" @@ -5,7 +20,7 @@ #include "ByteArrayDownload.h" #include "CacheDownload.h" -#include +#include "logger/QsLog.h" void NetJob::partSucceeded(int index) { @@ -15,7 +30,7 @@ void NetJob::partSucceeded(int index) num_succeeded++; QLOG_INFO() << m_job_name.toLocal8Bit() << "progress:" << num_succeeded << "/" - << downloads.size(); + << downloads.size(); emit filesProgress(num_succeeded, num_failed, downloads.size()); if (num_failed + num_succeeded == downloads.size()) @@ -50,7 +65,7 @@ void NetJob::partFailed(int index) else { QLOG_ERROR() << "Part" << index << "failed, restarting (" << downloads[index]->m_url - << ")"; + << ")"; // restart the job slot.failures++; downloads[index]->start(); diff --git a/logic/net/NetJob.h b/logic/net/NetJob.h index 01d12e60..c5c0d00c 100644 --- a/logic/net/NetJob.h +++ b/logic/net/NetJob.h @@ -1,3 +1,18 @@ +/* Copyright 2013 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 #include @@ -18,10 +33,9 @@ class NetJob : public ProgressProvider public: explicit NetJob(QString job_name) : ProgressProvider(), m_job_name(job_name) {}; - template - bool addNetAction(T action) + template bool addNetAction(T action) { - NetActionPtr base = std::static_pointer_cast(action); + NetActionPtr base = std::static_pointer_cast(action); base->index_within_job = downloads.size(); downloads.append(action); parts_progress.append(part_info()); diff --git a/logic/net/S3ListBucket.cpp b/logic/net/S3ListBucket.cpp index 643c3224..89dff951 100644 --- a/logic/net/S3ListBucket.cpp +++ b/logic/net/S3ListBucket.cpp @@ -1,6 +1,21 @@ +/* Copyright 2013 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 "S3ListBucket.h" #include "MultiMC.h" -#include +#include "logger/QsLog.h" #include #include #include @@ -123,7 +138,7 @@ void S3ListBucket::processValidReply() emit failed(index_within_job); return; } - if(is_truncated) + if (is_truncated) { current_marker = objects.last().Key; bytesSoFar += m_reply->size(); diff --git a/logic/net/S3ListBucket.h b/logic/net/S3ListBucket.h index f054532d..e7c5e05c 100644 --- a/logic/net/S3ListBucket.h +++ b/logic/net/S3ListBucket.h @@ -1,3 +1,18 @@ +/* Copyright 2013 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 "NetAction.h" diff --git a/logic/tasks/ProgressProvider.h b/logic/tasks/ProgressProvider.h index e158eb54..f6f2906a 100644 --- a/logic/tasks/ProgressProvider.h +++ b/logic/tasks/ProgressProvider.h @@ -1,20 +1,41 @@ +/* Copyright 2013 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 + class ProgressProvider : public QObject { Q_OBJECT protected: - explicit ProgressProvider(QObject* parent = 0): QObject(parent){} + explicit ProgressProvider(QObject *parent = 0) : QObject(parent) + { + } signals: void started(); void progress(qint64 current, qint64 total); void succeeded(); void failed(QString reason); void status(QString status); + public: virtual QString getStatus() const = 0; virtual void getProgress(qint64 ¤t, qint64 &total) = 0; virtual bool isRunning() const = 0; -public slots: +public +slots: virtual void start() = 0; }; diff --git a/logic/tasks/Task.cpp b/logic/tasks/Task.cpp index 2f137c55..47214723 100644 --- a/logic/tasks/Task.cpp +++ b/logic/tasks/Task.cpp @@ -3,7 +3,7 @@ * 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 @@ -14,12 +14,10 @@ */ #include "Task.h" -#include +#include "logger/QsLog.h" -Task::Task(QObject *parent) : - ProgressProvider(parent) +Task::Task(QObject *parent) : ProgressProvider(parent) { - } QString Task::getStatus() const @@ -39,13 +37,12 @@ void Task::setProgress(int new_progress) emit progress(new_progress, 100); } -void Task::getProgress(qint64& current, qint64& total) +void Task::getProgress(qint64 ¤t, qint64 &total) { current = m_progress; total = 100; } - void Task::start() { m_running = true; @@ -66,7 +63,6 @@ void Task::emitSucceeded() emit succeeded(); } - bool Task::isRunning() const { return m_running; diff --git a/logic/tasks/Task.h b/logic/tasks/Task.h index cfe71c51..980b2af8 100644 --- a/logic/tasks/Task.h +++ b/logic/tasks/Task.h @@ -3,7 +3,7 @@ * 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 @@ -24,24 +24,26 @@ class Task : public ProgressProvider Q_OBJECT public: explicit Task(QObject *parent = 0); - + virtual QString getStatus() const; - virtual void getProgress(qint64& current, qint64& total); + virtual void getProgress(qint64 ¤t, qint64 &total); virtual bool isRunning() const; - -public slots: + +public +slots: virtual void start(); - + protected: virtual void executeTask() = 0; - + virtual void emitSucceeded(); virtual void emitFailed(QString reason); -protected slots: - void setStatus(const QString& status); +protected +slots: + void setStatus(const QString &status); void setProgress(int progress); - + protected: QString m_status; int m_progress = 0; -- cgit v1.2.3