id
int64
0
755k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
65
repo_stars
int64
100
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
9 values
repo_extraction_date
stringclasses
92 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
28,791
mdc.h
doxygen_doxygen/deps/spdlog/include/spdlog/mdc.h
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors. // Distributed under the MIT License (http://opensource.org/licenses/MIT) #pragma once #include <map> #include <string> #include <spdlog/common.h> // MDC is a simple map of key->string values stored in thread local storage whose content will be printed by the loggers. // Note: Not supported in async mode (thread local storage - so the async thread pool have different copy). // // Usage example: // spdlog::mdc::put("mdc_key_1", "mdc_value_1"); // spdlog::info("Hello, {}", "World!"); // => [2024-04-26 02:08:05.040] [info] [mdc_key_1:mdc_value_1] Hello, World! namespace spdlog { class SPDLOG_API mdc { public: using mdc_map_t = std::map<std::string, std::string>; static void put(const std::string &key, const std::string &value) { get_context()[key] = value; } static std::string get(const std::string &key) { auto &context = get_context(); auto it = context.find(key); if (it != context.end()) { return it->second; } return ""; } static void remove(const std::string &key) { get_context().erase(key); } static void clear() { get_context().clear(); } static mdc_map_t &get_context() { static thread_local mdc_map_t context; return context; } }; } // namespace spdlog
1,362
C++
.h
35
34.4
121
0.651216
doxygen/doxygen
5,592
1,269
1,920
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,875
ostream.h
doxygen_doxygen/deps/spdlog/include/spdlog/fmt/bundled/ostream.h
// Formatting library for C++ - std::ostream support // // Copyright (c) 2012 - present, Victor Zverovich // All rights reserved. // // For the license information refer to format.h. #ifndef FMT_OSTREAM_H_ #define FMT_OSTREAM_H_ #include <fstream> // std::filebuf #ifdef _WIN32 # ifdef __GLIBCXX__ # include <ext/stdio_filebuf.h> # include <ext/stdio_sync_filebuf.h> # endif # include <io.h> #endif #include "format.h" FMT_BEGIN_NAMESPACE namespace detail { template <typename Streambuf> class formatbuf : public Streambuf { private: using char_type = typename Streambuf::char_type; using streamsize = decltype(std::declval<Streambuf>().sputn(nullptr, 0)); using int_type = typename Streambuf::int_type; using traits_type = typename Streambuf::traits_type; buffer<char_type>& buffer_; public: explicit formatbuf(buffer<char_type>& buf) : buffer_(buf) {} protected: // The put area is always empty. This makes the implementation simpler and has // the advantage that the streambuf and the buffer are always in sync and // sputc never writes into uninitialized memory. A disadvantage is that each // call to sputc always results in a (virtual) call to overflow. There is no // disadvantage here for sputn since this always results in a call to xsputn. auto overflow(int_type ch) -> int_type override { if (!traits_type::eq_int_type(ch, traits_type::eof())) buffer_.push_back(static_cast<char_type>(ch)); return ch; } auto xsputn(const char_type* s, streamsize count) -> streamsize override { buffer_.append(s, s + count); return count; } }; // Generate a unique explicit instantion in every translation unit using a tag // type in an anonymous namespace. namespace { struct file_access_tag {}; } // namespace template <typename Tag, typename BufType, FILE* BufType::*FileMemberPtr> class file_access { friend auto get_file(BufType& obj) -> FILE* { return obj.*FileMemberPtr; } }; #if FMT_MSC_VERSION template class file_access<file_access_tag, std::filebuf, &std::filebuf::_Myfile>; auto get_file(std::filebuf&) -> FILE*; #endif inline auto write_ostream_unicode(std::ostream& os, fmt::string_view data) -> bool { FILE* f = nullptr; #if FMT_MSC_VERSION if (auto* buf = dynamic_cast<std::filebuf*>(os.rdbuf())) f = get_file(*buf); else return false; #elif defined(_WIN32) && defined(__GLIBCXX__) auto* rdbuf = os.rdbuf(); if (auto* sfbuf = dynamic_cast<__gnu_cxx::stdio_sync_filebuf<char>*>(rdbuf)) f = sfbuf->file(); else if (auto* fbuf = dynamic_cast<__gnu_cxx::stdio_filebuf<char>*>(rdbuf)) f = fbuf->file(); else return false; #else ignore_unused(os, data, f); #endif #ifdef _WIN32 if (f) { int fd = _fileno(f); if (_isatty(fd)) { os.flush(); return write_console(fd, data); } } #endif return false; } inline auto write_ostream_unicode(std::wostream&, fmt::basic_string_view<wchar_t>) -> bool { return false; } // Write the content of buf to os. // It is a separate function rather than a part of vprint to simplify testing. template <typename Char> void write_buffer(std::basic_ostream<Char>& os, buffer<Char>& buf) { const Char* buf_data = buf.data(); using unsigned_streamsize = std::make_unsigned<std::streamsize>::type; unsigned_streamsize size = buf.size(); unsigned_streamsize max_size = to_unsigned(max_value<std::streamsize>()); do { unsigned_streamsize n = size <= max_size ? size : max_size; os.write(buf_data, static_cast<std::streamsize>(n)); buf_data += n; size -= n; } while (size != 0); } template <typename Char, typename T> void format_value(buffer<Char>& buf, const T& value) { auto&& format_buf = formatbuf<std::basic_streambuf<Char>>(buf); auto&& output = std::basic_ostream<Char>(&format_buf); #if !defined(FMT_STATIC_THOUSANDS_SEPARATOR) output.imbue(std::locale::classic()); // The default is always unlocalized. #endif output << value; output.exceptions(std::ios_base::failbit | std::ios_base::badbit); } template <typename T> struct streamed_view { const T& value; }; } // namespace detail // Formats an object of type T that has an overloaded ostream operator<<. template <typename Char> struct basic_ostream_formatter : formatter<basic_string_view<Char>, Char> { void set_debug_format() = delete; template <typename T, typename OutputIt> auto format(const T& value, basic_format_context<OutputIt, Char>& ctx) const -> OutputIt { auto buffer = basic_memory_buffer<Char>(); detail::format_value(buffer, value); return formatter<basic_string_view<Char>, Char>::format( {buffer.data(), buffer.size()}, ctx); } }; using ostream_formatter = basic_ostream_formatter<char>; template <typename T, typename Char> struct formatter<detail::streamed_view<T>, Char> : basic_ostream_formatter<Char> { template <typename OutputIt> auto format(detail::streamed_view<T> view, basic_format_context<OutputIt, Char>& ctx) const -> OutputIt { return basic_ostream_formatter<Char>::format(view.value, ctx); } }; /** \rst Returns a view that formats `value` via an ostream ``operator<<``. **Example**:: fmt::print("Current thread id: {}\n", fmt::streamed(std::this_thread::get_id())); \endrst */ template <typename T> constexpr auto streamed(const T& value) -> detail::streamed_view<T> { return {value}; } namespace detail { inline void vprint_directly(std::ostream& os, string_view format_str, format_args args) { auto buffer = memory_buffer(); detail::vformat_to(buffer, format_str, args); detail::write_buffer(os, buffer); } } // namespace detail FMT_EXPORT template <typename Char> void vprint(std::basic_ostream<Char>& os, basic_string_view<type_identity_t<Char>> format_str, basic_format_args<buffer_context<type_identity_t<Char>>> args) { auto buffer = basic_memory_buffer<Char>(); detail::vformat_to(buffer, format_str, args); if (detail::write_ostream_unicode(os, {buffer.data(), buffer.size()})) return; detail::write_buffer(os, buffer); } /** \rst Prints formatted data to the stream *os*. **Example**:: fmt::print(cerr, "Don't {}!", "panic"); \endrst */ FMT_EXPORT template <typename... T> void print(std::ostream& os, format_string<T...> fmt, T&&... args) { const auto& vargs = fmt::make_format_args(args...); if (detail::is_utf8()) vprint(os, fmt, vargs); else detail::vprint_directly(os, fmt, vargs); } FMT_EXPORT template <typename... Args> void print(std::wostream& os, basic_format_string<wchar_t, type_identity_t<Args>...> fmt, Args&&... args) { vprint(os, fmt, fmt::make_format_args<buffer_context<wchar_t>>(args...)); } FMT_EXPORT template <typename... T> void println(std::ostream& os, format_string<T...> fmt, T&&... args) { fmt::print(os, "{}\n", fmt::format(fmt, std::forward<T>(args)...)); } FMT_EXPORT template <typename... Args> void println(std::wostream& os, basic_format_string<wchar_t, type_identity_t<Args>...> fmt, Args&&... args) { print(os, L"{}\n", fmt::format(fmt, std::forward<Args>(args)...)); } FMT_END_NAMESPACE #endif // FMT_OSTREAM_H_
7,305
C++
.h
208
31.6875
80
0.684136
doxygen/doxygen
5,592
1,269
1,920
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,876
locale.h
doxygen_doxygen/deps/spdlog/include/spdlog/fmt/bundled/locale.h
#include "xchar.h" #warning fmt/locale.h is deprecated, include fmt/format.h or fmt/xchar.h instead
100
C++
.h
2
49
80
0.785714
doxygen/doxygen
5,592
1,269
1,920
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,889
lodepng.h
doxygen_doxygen/deps/liblodepng/lodepng.h
/* LodePNG version 20080927 Copyright (c) 2005-2008 Lode Vandevenne This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ /** Minified version of LodePNG, with only the encoder code */ #ifndef LODEPNG_H #define LODEPNG_H #include <stdio.h> #include <stdlib.h> #include <string.h> #ifdef __cplusplus extern "C" { #endif /* ////////////////////////////////////////////////////////////////////////// */ /* LodeFlate & LodeZlib Setting structs */ /* ////////////////////////////////////////////////////////////////////////// */ typedef struct LodeZlib_DeflateSettings /*deflate = compress*/ { /*LZ77 related settings*/ unsigned btype; /*the block type for LZ*/ unsigned useLZ77; /*whether or not to use LZ77*/ unsigned windowSize; /*the maximum is 32768*/ } LodeZlib_DeflateSettings; /* ////////////////////////////////////////////////////////////////////////// */ /* LodePNG */ /* ////////////////////////////////////////////////////////////////////////// */ typedef struct LodePNG_InfoColor /*info about the color type of an image*/ { /*header (IHDR)*/ unsigned colorType; /*color type*/ unsigned bitDepth; /*bits per sample*/ /*palette (PLTE)*/ unsigned char* palette; /*palette in RGBARGBA... order*/ size_t palettesize; /*palette size in number of colors (amount of bytes is 4 * palettesize)*/ /*transparent color key (tRNS)*/ unsigned key_defined; /*is a transparent color key given?*/ unsigned key_r; /*red component of color key*/ unsigned key_g; /*green component of color key*/ unsigned key_b; /*blue component of color key*/ } LodePNG_InfoColor; typedef struct LodePNG_InfoPng /*information about the PNG image, except pixels and sometimes except width and height*/ { /*header (IHDR), palette (PLTE) and transparency (tRNS)*/ unsigned width; /*width of the image in pixels (ignored by encoder, but filled in by decoder)*/ unsigned height; /*height of the image in pixels (ignored by encoder, but filled in by decoder)*/ unsigned compressionMethod; /*compression method of the original file*/ unsigned filterMethod; /*filter method of the original file*/ unsigned interlaceMethod; /*interlace method of the original file*/ LodePNG_InfoColor color; /*color type and bits, palette, transparency*/ } LodePNG_InfoPng; typedef struct LodePNG_InfoRaw /*contains user-chosen information about the raw image data, which is independent of the PNG image*/ { LodePNG_InfoColor color; } LodePNG_InfoRaw; unsigned LodePNG_InfoColor_addPalette(LodePNG_InfoColor* info, unsigned char r, unsigned char g, unsigned char b, unsigned char a); /*add 1 color to the palette*/ typedef struct LodePNG_EncodeSettings { LodeZlib_DeflateSettings zlibsettings; /*settings for the zlib encoder, such as window size, ...*/ unsigned autoLeaveOutAlphaChannel; /*automatically use color type without alpha instead of given one, if given image is opaque*/ unsigned force_palette; /*force creating a PLTE chunk if colortype is 2 or 6 (= a suggested palette). If colortype is 3, PLTE is _always_ created.*/ } LodePNG_EncodeSettings; void LodePNG_EncodeSettings_init(LodePNG_EncodeSettings* settings); typedef struct LodePNG_Encoder { LodePNG_EncodeSettings settings; LodePNG_InfoPng infoPng; /*the info specified by the user may not be changed by the encoder. The encoder will try to generate a PNG close to the given info.*/ LodePNG_InfoRaw infoRaw; /*put the properties of the input raw image in here*/ unsigned error; } LodePNG_Encoder; void LodePNG_Encoder_init(LodePNG_Encoder* encoder); void LodePNG_Encoder_cleanup(LodePNG_Encoder* encoder); void LodePNG_Encoder_copy(LodePNG_Encoder* dest, const LodePNG_Encoder* source); /*This function allocates the out buffer and stores the size in *outsize.*/ void LodePNG_encode(LodePNG_Encoder* encoder, unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h); /*free functions allowing to load and save a file from/to harddisk*/ /*This function allocates the out buffer and stores the size in *outsize.*/ //unsigned LodePNG_loadFile(unsigned char** out, size_t* outsize, const char* filename); unsigned LodePNG_saveFile(const unsigned char* buffer, size_t buffersize, const char* filename); #ifdef __cplusplus } #endif #endif
5,213
C++
.h
96
52.020833
162
0.70173
doxygen/doxygen
5,592
1,269
1,920
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,890
iconv.h
doxygen_doxygen/deps/iconv_winbuild/include/iconv.h
/* Copyright (C) 1999-2003 Free Software Foundation, Inc. This file is part of the GNU LIBICONV Library. The GNU LIBICONV Library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. The GNU LIBICONV Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with the GNU LIBICONV Library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /* When installed, this file is called "iconv.h". */ #ifndef _LIBICONV_H #define _LIBICONV_H #define _LIBICONV_VERSION 0x0109 /* version number: (major<<8) + minor */ #ifdef LIBICONV_STATIC #define LIBICONV_DLL_EXPORTED #else /* LIBICONV_STATIC */ #ifdef BUILDING_LIBICONV #define LIBICONV_DLL_EXPORTED __declspec(dllexport) #else #define LIBICONV_DLL_EXPORTED __declspec(dllimport) #endif #endif /* LIBICONV_STATIC */ extern LIBICONV_DLL_EXPORTED int _libiconv_version; /* Likewise */ /* We would like to #include any system header file which could define iconv_t, 1. in order to eliminate the risk that the user gets compilation errors because some other system header file includes /usr/include/iconv.h which defines iconv_t or declares iconv after this file, 2. when compiling for LIBICONV_PLUG, we need the proper iconv_t type in order to produce binary compatible code. But gcc's #include_next is not portable. Thus, once libiconv's iconv.h has been installed in /usr/local/include, there is no way any more to include the original /usr/include/iconv.h. We simply have to get away without it. Ad 1. The risk that a system header file does #include "iconv.h" or #include_next "iconv.h" is small. They all do #include <iconv.h>. Ad 2. The iconv_t type is a pointer type in all cases I have seen. (It has to be a scalar type because (iconv_t)(-1) is a possible return value from iconv_open().) */ /* Define iconv_t ourselves. */ #undef iconv_t #define iconv_t libiconv_t typedef void* iconv_t; /* Get size_t declaration. */ #include <stddef.h> /* Get errno declaration and values. */ #include <errno.h> /* Some systems, like SunOS 4, don't have EILSEQ. Some systems, like BSD/OS, have EILSEQ in a different header. On these systems, define EILSEQ ourselves. */ #ifndef EILSEQ #define EILSEQ #endif #ifdef __cplusplus extern "C" { #endif /* Allocates descriptor for code conversion from encoding `fromcode' to encoding `tocode'. */ #ifndef LIBICONV_PLUG #define iconv_open libiconv_open #endif extern LIBICONV_DLL_EXPORTED iconv_t iconv_open (const char* tocode, const char* fromcode); /* Converts, using conversion descriptor `cd', at most `*inbytesleft' bytes starting at `*inbuf', writing at most `*outbytesleft' bytes starting at `*outbuf'. Decrements `*inbytesleft' and increments `*inbuf' by the same amount. Decrements `*outbytesleft' and increments `*outbuf' by the same amount. */ #ifndef LIBICONV_PLUG #define iconv libiconv #endif extern LIBICONV_DLL_EXPORTED size_t iconv (iconv_t cd, const char* * inbuf, size_t *inbytesleft, char* * outbuf, size_t *outbytesleft); /* Frees resources allocated for conversion descriptor `cd'. */ #ifndef LIBICONV_PLUG #define iconv_close libiconv_close #endif extern LIBICONV_DLL_EXPORTED int iconv_close (iconv_t cd); #ifndef LIBICONV_PLUG /* Nonstandard extensions. */ /* Control of attributes. */ #define iconvctl libiconvctl extern LIBICONV_DLL_EXPORTED int iconvctl (iconv_t cd, int request, void* argument); /* Requests for iconvctl. */ #define ICONV_TRIVIALP 0 /* int *argument */ #define ICONV_GET_TRANSLITERATE 1 /* int *argument */ #define ICONV_SET_TRANSLITERATE 2 /* const int *argument */ #define ICONV_GET_DISCARD_ILSEQ 3 /* int *argument */ #define ICONV_SET_DISCARD_ILSEQ 4 /* const int *argument */ /* Listing of locale independent encodings. */ #define iconvlist libiconvlist extern LIBICONV_DLL_EXPORTED void iconvlist (int (*do_one) (unsigned int namescount, const char * const * names, void* data), void* data); /* Support for relocatable packages. */ /* Sets the original and the current installation prefix of the package. Relocation simply replaces a pathname starting with the original prefix by the corresponding pathname with the current prefix instead. Both prefixes should be directory names without trailing slash (i.e. use "" instead of "/"). */ extern LIBICONV_DLL_EXPORTED void libiconv_set_relocation_prefix (const char *orig_prefix, const char *curr_prefix); #endif #ifdef __cplusplus } #endif #endif /* _LIBICONV_H */
5,168
C++
.h
111
43.243243
135
0.736821
doxygen/doxygen
5,592
1,269
1,920
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
true
true
false
false
false
false
false
false
28,892
version.h
doxygen_doxygen/libversion/version.h
/****************************************************************************** * * Copyright (C) 1997-2020 by Dimitri van Heesch. * * Permission to use, copy, modify, and distribute this software and its * documentation under the terms of the GNU General Public License is hereby * granted. No representations are made about the suitability of this software * for any purpose. It is provided "as is" without express or implied warranty. * See the GNU General Public License for more details. * * Documents produced by Doxygen are derivative works derived from the * input used in their production; they are not affected by this license. * */ #ifndef VERSION_H #define VERSION_H #include <string> std::string getDoxygenVersion(); std::string getGitVersion(); std::string getFullVersion(); #endif
813
C++
.h
21
36.904762
79
0.701777
doxygen/doxygen
5,592
1,269
1,920
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,893
Untar.cpp
PrismLauncher_PrismLauncher/launcher/Untar.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2023-2024 Trial97 <alexandru.tripon97@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 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 "Untar.h" #include <quagzipfile.h> #include <QByteArray> #include <QFileInfo> #include <QIODevice> #include <QString> #include "FileSystem.h" // adaptation of the: // - https://github.com/madler/zlib/blob/develop/contrib/untgz/untgz.c // - https://en.wikipedia.org/wiki/Tar_(computing) // - https://github.com/euroelessar/cutereader/blob/master/karchive/src/ktar.cpp #define BLOCKSIZE 512 #define SHORTNAMESIZE 100 enum class TypeFlag : char { Regular = '0', // regular file ARegular = 0, // regular file Link = '1', // link Symlink = '2', // reserved Character = '3', // character special Block = '4', // block special Directory = '5', // directory FIFO = '6', // FIFO special Contiguous = '7', // reserved // Posix stuff GlobalPosixHeader = 'g', ExtendedPosixHeader = 'x', // 'A'– 'Z' Vendor specific extensions(POSIX .1 - 1988) // GNU GNULongLink = 'K', /* long link name */ GNULongName = 'L', /* long file name */ }; // struct Header { /* byte offset */ // char name[100]; /* 0 */ // char mode[8]; /* 100 */ // char uid[8]; /* 108 */ // char gid[8]; /* 116 */ // char size[12]; /* 124 */ // char mtime[12]; /* 136 */ // char chksum[8]; /* 148 */ // TypeFlag typeflag; /* 156 */ // char linkname[100]; /* 157 */ // char magic[6]; /* 257 */ // char version[2]; /* 263 */ // char uname[32]; /* 265 */ // char gname[32]; /* 297 */ // char devmajor[8]; /* 329 */ // char devminor[8]; /* 337 */ // char prefix[155]; /* 345 */ // /* 500 */ // }; bool readLonglink(QIODevice* in, qint64 size, QByteArray& longlink) { qint64 n = 0; size--; // ignore trailing null if (size < 0) { qCritical() << "The filename size is negative"; return false; } longlink.resize(size + (BLOCKSIZE - size % BLOCKSIZE)); // make the size divisible by BLOCKSIZE for (qint64 offset = 0; offset < longlink.size(); offset += BLOCKSIZE) { n = in->read(longlink.data() + offset, BLOCKSIZE); if (n != BLOCKSIZE) { qCritical() << "The expected blocksize was not respected for the name"; return false; } } longlink.truncate(qstrlen(longlink.constData())); return true; } int getOctal(char* buffer, int maxlenght, bool* ok) { return QByteArray(buffer, qstrnlen(buffer, maxlenght)).toInt(ok, 8); } QString decodeName(char* name) { return QFile::decodeName(QByteArray(name, qstrnlen(name, 100))); } bool Tar::extract(QIODevice* in, QString dst) { char buffer[BLOCKSIZE]; QString name, symlink, firstFolderName; bool doNotReset = false, ok; while (true) { auto n = in->read(buffer, BLOCKSIZE); if (n != BLOCKSIZE) { // allways expect complete blocks qCritical() << "The expected blocksize was not respected"; return false; } if (buffer[0] == 0) { // end of archive return true; } int mode = getOctal(buffer + 100, 8, &ok) | QFile::ReadUser | QFile::WriteUser; // hack to ensure write and read permisions if (!ok) { qCritical() << "The file mode can't be read"; return false; } // there are names that are exactly 100 bytes long // and neither longlink nor \0 terminated (bug:101472) if (name.isEmpty()) { name = decodeName(buffer); if (!firstFolderName.isEmpty() && name.startsWith(firstFolderName)) { name = name.mid(firstFolderName.size()); } } if (symlink.isEmpty()) symlink = decodeName(buffer); qint64 size = getOctal(buffer + 124, 12, &ok); if (!ok) { qCritical() << "The file size can't be read"; return false; } switch (TypeFlag(buffer[156])) { case TypeFlag::Regular: /* fallthrough */ case TypeFlag::ARegular: { auto fileName = FS::PathCombine(dst, name); if (!FS::ensureFilePathExists(fileName)) { qCritical() << "Can't ensure the file path to exist: " << fileName; return false; } QFile out(fileName); if (!out.open(QFile::WriteOnly)) { qCritical() << "Can't open file:" << fileName; return false; } out.setPermissions(QFile::Permissions(mode)); while (size > 0) { QByteArray tmp(BLOCKSIZE, 0); n = in->read(tmp.data(), BLOCKSIZE); if (n != BLOCKSIZE) { qCritical() << "The expected blocksize was not respected when reading file"; return false; } tmp.truncate(qMin(qint64(BLOCKSIZE), size)); out.write(tmp); size -= BLOCKSIZE; } break; } case TypeFlag::Directory: { if (firstFolderName.isEmpty()) { firstFolderName = name; break; } auto folderPath = FS::PathCombine(dst, name); if (!FS::ensureFolderPathExists(folderPath)) { qCritical() << "Can't ensure that folder exists: " << folderPath; return false; } break; } case TypeFlag::GNULongLink: { doNotReset = true; QByteArray longlink; if (readLonglink(in, size, longlink)) { symlink = QFile::decodeName(longlink.constData()); } else { qCritical() << "Failed to read long link"; return false; } break; } case TypeFlag::GNULongName: { doNotReset = true; QByteArray longlink; if (readLonglink(in, size, longlink)) { name = QFile::decodeName(longlink.constData()); } else { qCritical() << "Failed to read long name"; return false; } break; } case TypeFlag::Link: /* fallthrough */ case TypeFlag::Symlink: { auto fileName = FS::PathCombine(dst, name); if (!FS::create_link(FS::PathCombine(QFileInfo(fileName).path(), symlink), fileName)()) { // do not use symlinks qCritical() << "Can't create link for:" << fileName << " to:" << FS::PathCombine(QFileInfo(fileName).path(), symlink); return false; } FS::ensureFilePathExists(fileName); QFile::setPermissions(fileName, QFile::Permissions(mode)); break; } case TypeFlag::Character: /* fallthrough */ case TypeFlag::Block: /* fallthrough */ case TypeFlag::FIFO: /* fallthrough */ case TypeFlag::Contiguous: /* fallthrough */ case TypeFlag::GlobalPosixHeader: /* fallthrough */ case TypeFlag::ExtendedPosixHeader: /* fallthrough */ default: break; } if (!doNotReset) { name.truncate(0); symlink.truncate(0); } doNotReset = false; } return true; } bool GZTar::extract(QString src, QString dst) { QuaGzipFile a(src); if (!a.open(QIODevice::ReadOnly)) { qCritical() << "Can't open tar file:" << src; return false; } return Tar::extract(&a, dst); }
9,523
C++
.cpp
251
28.844622
138
0.545445
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,894
Version.cpp
PrismLauncher_PrismLauncher/launcher/Version.cpp
#include "Version.h" #include <QDebug> #include <QRegularExpression> #include <QRegularExpressionMatch> #include <QUrl> Version::Version(QString str) : m_string(std::move(str)) { parse(); } #define VERSION_OPERATOR(return_on_different) \ bool exclude_our_sections = false; \ bool exclude_their_sections = false; \ \ const auto size = qMax(m_sections.size(), other.m_sections.size()); \ for (int i = 0; i < size; ++i) { \ Section sec1 = (i >= m_sections.size()) ? Section() : m_sections.at(i); \ Section sec2 = (i >= other.m_sections.size()) ? Section() : other.m_sections.at(i); \ \ { /* Don't include appendixes in the comparison */ \ if (sec1.isAppendix()) \ exclude_our_sections = true; \ if (sec2.isAppendix()) \ exclude_their_sections = true; \ \ if (exclude_our_sections) { \ sec1 = Section(); \ if (sec2.m_isNull) \ break; \ } \ \ if (exclude_their_sections) { \ sec2 = Section(); \ if (sec1.m_isNull) \ break; \ } \ } \ \ if (sec1 != sec2) \ return return_on_different; \ } bool Version::operator<(const Version& other) const { VERSION_OPERATOR(sec1 < sec2) return false; } bool Version::operator==(const Version& other) const { VERSION_OPERATOR(false) return true; } bool Version::operator!=(const Version& other) const { return !operator==(other); } bool Version::operator<=(const Version& other) const { return *this < other || *this == other; } bool Version::operator>(const Version& other) const { return !(*this <= other); } bool Version::operator>=(const Version& other) const { return !(*this < other); } void Version::parse() { m_sections.clear(); QString currentSection; if (m_string.isEmpty()) return; auto classChange = [&currentSection](QChar lastChar, QChar currentChar) { if (lastChar.isNull()) return false; if (lastChar.isDigit() != currentChar.isDigit()) return true; const QList<QChar> s_separators{ '.', '-', '+' }; if (s_separators.contains(currentChar) && currentSection.at(0) != currentChar) return true; return false; }; currentSection += m_string.at(0); for (int i = 1; i < m_string.size(); ++i) { const auto& current_char = m_string.at(i); if (classChange(m_string.at(i - 1), current_char)) { if (!currentSection.isEmpty()) m_sections.append(Section(currentSection)); currentSection = ""; } currentSection += current_char; } if (!currentSection.isEmpty()) m_sections.append(Section(currentSection)); } /// qDebug print support for the Version class QDebug operator<<(QDebug debug, const Version& v) { QDebugStateSaver saver(debug); debug.nospace() << "Version{ string: " << v.toString() << ", sections: [ "; bool first = true; for (auto s : v.m_sections) { if (!first) debug.nospace() << ", "; debug.nospace() << s.m_fullString; first = false; } debug.nospace() << " ]" << " }"; return debug; }
5,082
C++
.cpp
110
35.572727
93
0.373511
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,896
MangoHud.cpp
PrismLauncher_PrismLauncher/launcher/MangoHud.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * PrismLauncher - Minecraft Launcher * Copyright (C) 2022 Jan Drögehoff <sentrycraft123@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include <QDebug> #include <QDir> #include <QString> #include <QStringList> #include <QSysInfo> #include <QtGlobal> #include "FileSystem.h" #include "Json.h" #include "MangoHud.h" #ifdef __GLIBC__ #ifndef _GNU_SOURCE #define _GNU_SOURCE #define UNDEF_GNU_SOURCE #endif #include <dlfcn.h> #include <linux/limits.h> #endif namespace MangoHud { QString getLibraryString() { /** * Guess MangoHud install location by searching for vulkan layers in this order: * * $VK_LAYER_PATH * $XDG_DATA_DIRS (/usr/local/share/:/usr/share/) * $XDG_DATA_HOME (~/.local/share) * /etc * $XDG_CONFIG_DIRS (/etc/xdg) * $XDG_CONFIG_HOME (~/.config) * * @returns Absolute path of libMangoHud.so if found and empty QString otherwise. */ QStringList vkLayerList; { QString home = QDir::homePath(); QString vkLayerPath = qEnvironmentVariable("VK_LAYER_PATH"); if (!vkLayerPath.isEmpty()) { vkLayerList << vkLayerPath; } QStringList xdgDataDirs = qEnvironmentVariable("XDG_DATA_DIRS", "/usr/local/share/:/usr/share/").split(QLatin1String(":")); for (QString dir : xdgDataDirs) { vkLayerList << FS::PathCombine(dir, "vulkan", "implicit_layer.d"); } QString xdgDataHome = qEnvironmentVariable("XDG_DATA_HOME"); if (xdgDataHome.isEmpty()) { xdgDataHome = FS::PathCombine(home, ".local", "share"); } vkLayerList << FS::PathCombine(xdgDataHome, "vulkan", "implicit_layer.d"); vkLayerList << "/etc"; QStringList xdgConfigDirs = qEnvironmentVariable("XDG_CONFIG_DIRS", "/etc/xdg").split(QLatin1String(":")); for (QString dir : xdgConfigDirs) { vkLayerList << FS::PathCombine(dir, "vulkan", "implicit_layer.d"); } QString xdgConfigHome = qEnvironmentVariable("XDG_CONFIG_HOME"); if (xdgConfigHome.isEmpty()) { xdgConfigHome = FS::PathCombine(home, ".config"); } vkLayerList << FS::PathCombine(xdgConfigHome, "vulkan", "implicit_layer.d"); } for (const QString& vkLayer : vkLayerList) { // prefer to use architecture specific vulkan layers QString currentArch = QSysInfo::currentCpuArchitecture(); if (currentArch == "arm64") { currentArch = "aarch64"; } QStringList manifestNames = { QString("MangoHud.%1.json").arg(currentArch), "MangoHud.json" }; QString filePath{}; for (const QString& manifestName : manifestNames) { QString tryPath = FS::PathCombine(vkLayer, manifestName); if (QFile::exists(tryPath)) { filePath = tryPath; break; } } if (filePath.isEmpty()) { continue; } try { auto conf = Json::requireDocument(filePath, vkLayer); auto confObject = Json::requireObject(conf, vkLayer); auto layer = Json::ensureObject(confObject, "layer"); QString libraryName = Json::ensureString(layer, "library_path"); if (libraryName.isEmpty()) { continue; } if (QFileInfo(libraryName).isAbsolute()) { return libraryName; } #ifdef __GLIBC__ // Check whether mangohud is usable on a glibc based system QString libraryPath = findLibrary(libraryName); if (!libraryPath.isEmpty()) { return libraryPath; } #else // Without glibc return recorded shared library as-is. return libraryName; #endif } catch (const Exception& e) { } } return {}; } QString findLibrary(QString libName) { #ifdef __GLIBC__ const char* library = libName.toLocal8Bit().constData(); void* handle = dlopen(library, RTLD_NOW); if (!handle) { qCritical() << "dlopen() failed:" << dlerror(); return {}; } char path[PATH_MAX]; if (dlinfo(handle, RTLD_DI_ORIGIN, path) == -1) { qCritical() << "dlinfo() failed:" << dlerror(); dlclose(handle); return {}; } auto fullPath = FS::PathCombine(QString(path), libName); dlclose(handle); return fullPath; #else qWarning() << "MangoHud::findLibrary is not implemented on this platform"; return {}; #endif } } // namespace MangoHud #ifdef UNDEF_GNU_SOURCE #undef _GNU_SOURCE #undef UNDEF_GNU_SOURCE #endif
5,232
C++
.cpp
148
28.709459
131
0.632141
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,897
KonamiCode.cpp
PrismLauncher_PrismLauncher/launcher/KonamiCode.cpp
#include "KonamiCode.h" #include <QDebug> #include <array> namespace { const std::array<Qt::Key, 10> konamiCode = { { Qt::Key_Up, Qt::Key_Up, Qt::Key_Down, Qt::Key_Down, Qt::Key_Left, Qt::Key_Right, Qt::Key_Left, Qt::Key_Right, Qt::Key_B, Qt::Key_A } }; } KonamiCode::KonamiCode(QObject* parent) : QObject(parent) {} void KonamiCode::input(QEvent* event) { if (event->type() == QEvent::KeyPress) { QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event); auto key = Qt::Key(keyEvent->key()); if (key == konamiCode[m_progress]) { m_progress++; } else { m_progress = 0; } if (m_progress == static_cast<int>(konamiCode.size())) { m_progress = 0; emit triggered(); } } }
827
C++
.cpp
24
26.666667
127
0.546934
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
28,898
InstanceImportTask.cpp
PrismLauncher_PrismLauncher/launcher/InstanceImportTask.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * Copyright (c) 2022 flowln <flowlnlnln@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 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 "InstanceImportTask.h" #include "Application.h" #include "FileSystem.h" #include "MMCZip.h" #include "NullInstance.h" #include "QObjectPtr.h" #include "icons/IconList.h" #include "icons/IconUtils.h" #include "modplatform/flame/FlameInstanceCreationTask.h" #include "modplatform/modrinth/ModrinthInstanceCreationTask.h" #include "modplatform/technic/TechnicPackProcessor.h" #include "settings/INISettingsObject.h" #include "tasks/Task.h" #include "net/ApiDownload.h" #include <QtConcurrentRun> #include <algorithm> #include <memory> #include <quazip/quazipdir.h> InstanceImportTask::InstanceImportTask(const QUrl& sourceUrl, QWidget* parent, QMap<QString, QString>&& extra_info) : m_sourceUrl(sourceUrl), m_extra_info(extra_info), m_parent(parent) {} bool InstanceImportTask::abort() { if (!canAbort()) return false; bool wasAborted = false; if (m_task) wasAborted = m_task->abort(); Task::abort(); return wasAborted; } void InstanceImportTask::executeTask() { setAbortable(true); if (m_sourceUrl.isLocalFile()) { m_archivePath = m_sourceUrl.toLocalFile(); processZipPack(); } else { setStatus(tr("Downloading modpack:\n%1").arg(m_sourceUrl.toString())); downloadFromUrl(); } } void InstanceImportTask::downloadFromUrl() { const QString path(m_sourceUrl.host() + '/' + m_sourceUrl.path()); auto entry = APPLICATION->metacache()->resolveEntry("general", path); entry->setStale(true); m_archivePath = entry->getFullPath(); auto filesNetJob = makeShared<NetJob>(tr("Modpack download"), APPLICATION->network()); filesNetJob->addNetAction(Net::ApiDownload::makeCached(m_sourceUrl, entry)); connect(filesNetJob.get(), &NetJob::succeeded, this, &InstanceImportTask::processZipPack); connect(filesNetJob.get(), &NetJob::progress, this, &InstanceImportTask::setProgress); connect(filesNetJob.get(), &NetJob::stepProgress, this, &InstanceImportTask::propagateStepProgress); connect(filesNetJob.get(), &NetJob::failed, this, &InstanceImportTask::emitFailed); connect(filesNetJob.get(), &NetJob::aborted, this, &InstanceImportTask::emitAborted); m_task.reset(filesNetJob); filesNetJob->start(); } QString InstanceImportTask::getRootFromZip(QuaZip* zip, const QString& root) { if (!isRunning()) { return {}; } QuaZipDir rootDir(zip, root); for (auto&& fileName : rootDir.entryList(QDir::Files)) { setDetails(fileName); if (fileName == "instance.cfg") { qDebug() << "MultiMC:" << true; m_modpackType = ModpackType::MultiMC; return root; } if (fileName == "manifest.json") { qDebug() << "Flame:" << true; m_modpackType = ModpackType::Flame; return root; } QCoreApplication::processEvents(); } // Recurse the search to non-ignored subfolders for (auto&& fileName : rootDir.entryList(QDir::Dirs)) { if ("overrides/" == fileName) continue; QString result = getRootFromZip(zip, root + fileName); if (!result.isEmpty()) return result; } return {}; } void InstanceImportTask::processZipPack() { setStatus(tr("Attempting to determine instance type")); QDir extractDir(m_stagingPath); qDebug() << "Attempting to create instance from" << m_archivePath; // open the zip and find relevant files in it auto packZip = std::make_shared<QuaZip>(m_archivePath); if (!packZip->open(QuaZip::mdUnzip)) { emitFailed(tr("Unable to open supplied modpack zip file.")); return; } QuaZipDir packZipDir(packZip.get()); qDebug() << "Attempting to determine instance type"; QString root; // NOTE: Prioritize modpack platforms that aren't searched for recursively. // Especially Flame has a very common filename for its manifest, which may appear inside overrides for example // https://docs.modrinth.com/docs/modpacks/format_definition/#storage if (packZipDir.exists("/modrinth.index.json")) { // process as Modrinth pack qDebug() << "Modrinth:" << true; m_modpackType = ModpackType::Modrinth; } else if (packZipDir.exists("/bin/modpack.jar") || packZipDir.exists("/bin/version.json")) { // process as Technic pack qDebug() << "Technic:" << true; extractDir.mkpath("minecraft"); extractDir.cd("minecraft"); m_modpackType = ModpackType::Technic; } else { root = getRootFromZip(packZip.get()); setDetails(""); } if (m_modpackType == ModpackType::Unknown) { emitFailed(tr("Archive does not contain a recognized modpack type.")); return; } setStatus(tr("Extracting modpack")); // make sure we extract just the pack auto zipTask = makeShared<MMCZip::ExtractZipTask>(packZip, extractDir, root); auto progressStep = std::make_shared<TaskStepProgress>(); connect(zipTask.get(), &Task::finished, this, [this, progressStep] { progressStep->state = TaskStepState::Succeeded; stepProgress(*progressStep); }); connect(zipTask.get(), &Task::succeeded, this, &InstanceImportTask::extractFinished, Qt::QueuedConnection); connect(zipTask.get(), &Task::aborted, this, &InstanceImportTask::emitAborted); connect(zipTask.get(), &Task::failed, this, [this, progressStep](QString reason) { progressStep->state = TaskStepState::Failed; stepProgress(*progressStep); emitFailed(reason); }); connect(zipTask.get(), &Task::stepProgress, this, &InstanceImportTask::propagateStepProgress); connect(zipTask.get(), &Task::progress, this, [this, progressStep](qint64 current, qint64 total) { progressStep->update(current, total); stepProgress(*progressStep); }); connect(zipTask.get(), &Task::status, this, [this, progressStep](QString status) { progressStep->status = status; stepProgress(*progressStep); }); m_task.reset(zipTask); zipTask->start(); } void InstanceImportTask::extractFinished() { setAbortable(false); QDir extractDir(m_stagingPath); qDebug() << "Fixing permissions for extracted pack files..."; QDirIterator it(extractDir, QDirIterator::Subdirectories); while (it.hasNext()) { auto filepath = it.next(); QFileInfo file(filepath); auto permissions = QFile::permissions(filepath); auto origPermissions = permissions; if (file.isDir()) { // Folder +rwx for current user permissions |= QFileDevice::Permission::ReadUser | QFileDevice::Permission::WriteUser | QFileDevice::Permission::ExeUser; } else { // File +rw for current user permissions |= QFileDevice::Permission::ReadUser | QFileDevice::Permission::WriteUser; } if (origPermissions != permissions) { if (!QFile::setPermissions(filepath, permissions)) { logWarning(tr("Could not fix permissions for %1").arg(filepath)); } else { qDebug() << "Fixed" << filepath; } } } switch (m_modpackType) { case ModpackType::MultiMC: processMultiMC(); return; case ModpackType::Technic: processTechnic(); return; case ModpackType::Flame: processFlame(); return; case ModpackType::Modrinth: processModrinth(); return; case ModpackType::Unknown: emitFailed(tr("Archive does not contain a recognized modpack type.")); return; } } void InstanceImportTask::processFlame() { shared_qobject_ptr<FlameCreationTask> inst_creation_task = nullptr; if (!m_extra_info.isEmpty()) { auto pack_id_it = m_extra_info.constFind("pack_id"); Q_ASSERT(pack_id_it != m_extra_info.constEnd()); auto pack_id = pack_id_it.value(); auto pack_version_id_it = m_extra_info.constFind("pack_version_id"); Q_ASSERT(pack_version_id_it != m_extra_info.constEnd()); auto pack_version_id = pack_version_id_it.value(); QString original_instance_id; auto original_instance_id_it = m_extra_info.constFind("original_instance_id"); if (original_instance_id_it != m_extra_info.constEnd()) original_instance_id = original_instance_id_it.value(); inst_creation_task = makeShared<FlameCreationTask>(m_stagingPath, m_globalSettings, m_parent, pack_id, pack_version_id, original_instance_id); } else { // FIXME: Find a way to get IDs in directly imported ZIPs inst_creation_task = makeShared<FlameCreationTask>(m_stagingPath, m_globalSettings, m_parent, QString(), QString()); } inst_creation_task->setName(*this); inst_creation_task->setIcon(m_instIcon); inst_creation_task->setGroup(m_instGroup); inst_creation_task->setConfirmUpdate(shouldConfirmUpdate()); auto weak = inst_creation_task.toWeakRef(); connect(inst_creation_task.get(), &Task::succeeded, this, [this, weak] { if (auto sp = weak.lock()) { setOverride(sp->shouldOverride(), sp->originalInstanceID()); } emitSucceeded(); }); connect(inst_creation_task.get(), &Task::failed, this, &InstanceImportTask::emitFailed); connect(inst_creation_task.get(), &Task::progress, this, &InstanceImportTask::setProgress); connect(inst_creation_task.get(), &Task::stepProgress, this, &InstanceImportTask::propagateStepProgress); connect(inst_creation_task.get(), &Task::status, this, &InstanceImportTask::setStatus); connect(inst_creation_task.get(), &Task::details, this, &InstanceImportTask::setDetails); connect(inst_creation_task.get(), &Task::aborted, this, &Task::abort); connect(inst_creation_task.get(), &Task::abortStatusChanged, this, &Task::setAbortable); m_task.reset(inst_creation_task); setAbortable(true); m_task->start(); } void InstanceImportTask::processTechnic() { shared_qobject_ptr<Technic::TechnicPackProcessor> packProcessor{ new Technic::TechnicPackProcessor }; connect(packProcessor.get(), &Technic::TechnicPackProcessor::succeeded, this, &InstanceImportTask::emitSucceeded); connect(packProcessor.get(), &Technic::TechnicPackProcessor::failed, this, &InstanceImportTask::emitFailed); packProcessor->run(m_globalSettings, name(), m_instIcon, m_stagingPath); } void InstanceImportTask::processMultiMC() { QString configPath = FS::PathCombine(m_stagingPath, "instance.cfg"); auto instanceSettings = std::make_shared<INISettingsObject>(configPath); NullInstance instance(m_globalSettings, instanceSettings, m_stagingPath); // reset time played on import... because packs. instance.resetTimePlayed(); // set a new nice name instance.setName(name()); // if the icon was specified by user, use that. otherwise pull icon from the pack if (m_instIcon != "default") { instance.setIconKey(m_instIcon); } else { m_instIcon = instance.iconKey(); auto importIconPath = IconUtils::findBestIconIn(instance.instanceRoot(), m_instIcon); if (importIconPath.isNull() || !QFile::exists(importIconPath)) importIconPath = IconUtils::findBestIconIn(instance.instanceRoot(), "icon.png"); if (!importIconPath.isNull() && QFile::exists(importIconPath)) { // import icon auto iconList = APPLICATION->icons(); if (iconList->iconFileExists(m_instIcon)) { iconList->deleteIcon(m_instIcon); } iconList->installIcon(importIconPath, m_instIcon); } } emitSucceeded(); } void InstanceImportTask::processModrinth() { shared_qobject_ptr<ModrinthCreationTask> inst_creation_task = nullptr; if (!m_extra_info.isEmpty()) { auto pack_id_it = m_extra_info.constFind("pack_id"); Q_ASSERT(pack_id_it != m_extra_info.constEnd()); auto pack_id = pack_id_it.value(); QString pack_version_id; auto pack_version_id_it = m_extra_info.constFind("pack_version_id"); if (pack_version_id_it != m_extra_info.constEnd()) pack_version_id = pack_version_id_it.value(); QString original_instance_id; auto original_instance_id_it = m_extra_info.constFind("original_instance_id"); if (original_instance_id_it != m_extra_info.constEnd()) original_instance_id = original_instance_id_it.value(); inst_creation_task = makeShared<ModrinthCreationTask>(m_stagingPath, m_globalSettings, m_parent, pack_id, pack_version_id, original_instance_id); } else { QString pack_id; if (!m_sourceUrl.isEmpty()) { QRegularExpression regex(R"(data\/([^\/]*)\/versions)"); pack_id = regex.match(m_sourceUrl.toString()).captured(1); } // FIXME: Find a way to get the ID in directly imported ZIPs inst_creation_task = makeShared<ModrinthCreationTask>(m_stagingPath, m_globalSettings, m_parent, pack_id); } inst_creation_task->setName(*this); inst_creation_task->setIcon(m_instIcon); inst_creation_task->setGroup(m_instGroup); inst_creation_task->setConfirmUpdate(shouldConfirmUpdate()); auto weak = inst_creation_task.toWeakRef(); connect(inst_creation_task.get(), &Task::succeeded, this, [this, weak] { if (auto sp = weak.lock()) { setOverride(sp->shouldOverride(), sp->originalInstanceID()); } emitSucceeded(); }); connect(inst_creation_task.get(), &Task::failed, this, &InstanceImportTask::emitFailed); connect(inst_creation_task.get(), &Task::progress, this, &InstanceImportTask::setProgress); connect(inst_creation_task.get(), &Task::stepProgress, this, &InstanceImportTask::propagateStepProgress); connect(inst_creation_task.get(), &Task::status, this, &InstanceImportTask::setStatus); connect(inst_creation_task.get(), &Task::details, this, &InstanceImportTask::setDetails); connect(inst_creation_task.get(), &Task::aborted, this, &Task::abort); connect(inst_creation_task.get(), &Task::abortStatusChanged, this, &Task::setAbortable); m_task.reset(inst_creation_task); setAbortable(true); m_task->start(); }
15,952
C++
.cpp
354
38.717514
136
0.678937
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,899
Json.cpp
PrismLauncher_PrismLauncher/launcher/Json.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 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 "Json.h" #include <QFile> #include <math.h> #include "FileSystem.h" namespace Json { void write(const QJsonDocument& doc, const QString& filename) { FS::write(filename, doc.toJson()); } void write(const QJsonObject& object, const QString& filename) { write(QJsonDocument(object), filename); } void write(const QJsonArray& array, const QString& filename) { write(QJsonDocument(array), filename); } QByteArray toText(const QJsonObject& obj) { return QJsonDocument(obj).toJson(QJsonDocument::Compact); } QByteArray toText(const QJsonArray& array) { return QJsonDocument(array).toJson(QJsonDocument::Compact); } static bool isBinaryJson(const QByteArray& data) { decltype(QJsonDocument::BinaryFormatTag) tag = QJsonDocument::BinaryFormatTag; return memcmp(data.constData(), &tag, sizeof(QJsonDocument::BinaryFormatTag)) == 0; } QJsonDocument requireDocument(const QByteArray& data, const QString& what) { if (isBinaryJson(data)) { // FIXME: Is this needed? throw JsonException(what + ": Invalid JSON. Binary JSON unsupported"); } else { QJsonParseError error; QJsonDocument doc = QJsonDocument::fromJson(data, &error); if (error.error != QJsonParseError::NoError) { throw JsonException(what + ": Error parsing JSON: " + error.errorString()); } return doc; } } QJsonDocument requireDocument(const QString& filename, const QString& what) { return requireDocument(FS::read(filename), what); } QJsonObject requireObject(const QJsonDocument& doc, const QString& what) { if (!doc.isObject()) { throw JsonException(what + " is not an object"); } return doc.object(); } QJsonArray requireArray(const QJsonDocument& doc, const QString& what) { if (!doc.isArray()) { throw JsonException(what + " is not an array"); } return doc.array(); } void writeString(QJsonObject& to, const QString& key, const QString& value) { if (!value.isEmpty()) { to.insert(key, value); } } void writeStringList(QJsonObject& to, const QString& key, const QStringList& values) { if (!values.isEmpty()) { QJsonArray array; for (auto value : values) { array.append(value); } to.insert(key, array); } } template <> QJsonValue toJson<QUrl>(const QUrl& url) { return QJsonValue(url.toString(QUrl::FullyEncoded)); } template <> QJsonValue toJson<QByteArray>(const QByteArray& data) { return QJsonValue(QString::fromLatin1(data.toHex())); } template <> QJsonValue toJson<QDateTime>(const QDateTime& datetime) { return QJsonValue(datetime.toString(Qt::ISODate)); } template <> QJsonValue toJson<QDir>(const QDir& dir) { return QDir::current().relativeFilePath(dir.absolutePath()); } template <> QJsonValue toJson<QUuid>(const QUuid& uuid) { return uuid.toString(); } template <> QJsonValue toJson<QVariant>(const QVariant& variant) { return QJsonValue::fromVariant(variant); } template <> QByteArray requireIsType<QByteArray>(const QJsonValue& value, const QString& what) { const QString string = ensureIsType<QString>(value, what); // ensure that the string can be safely cast to Latin1 if (string != QString::fromLatin1(string.toLatin1())) { throw JsonException(what + " is not encodable as Latin1"); } return QByteArray::fromHex(string.toLatin1()); } template <> QJsonArray requireIsType<QJsonArray>(const QJsonValue& value, const QString& what) { if (!value.isArray()) { throw JsonException(what + " is not an array"); } return value.toArray(); } template <> QString requireIsType<QString>(const QJsonValue& value, const QString& what) { if (!value.isString()) { throw JsonException(what + " is not a string"); } return value.toString(); } template <> bool requireIsType<bool>(const QJsonValue& value, const QString& what) { if (!value.isBool()) { throw JsonException(what + " is not a bool"); } return value.toBool(); } template <> double requireIsType<double>(const QJsonValue& value, const QString& what) { if (!value.isDouble()) { throw JsonException(what + " is not a double"); } return value.toDouble(); } template <> int requireIsType<int>(const QJsonValue& value, const QString& what) { const double doubl = requireIsType<double>(value, what); if (fmod(doubl, 1) != 0) { throw JsonException(what + " is not an integer"); } return int(doubl); } template <> QDateTime requireIsType<QDateTime>(const QJsonValue& value, const QString& what) { const QString string = requireIsType<QString>(value, what); const QDateTime datetime = QDateTime::fromString(string, Qt::ISODate); if (!datetime.isValid()) { throw JsonException(what + " is not a ISO formatted date/time value"); } return datetime; } template <> QUrl requireIsType<QUrl>(const QJsonValue& value, const QString& what) { const QString string = ensureIsType<QString>(value, what); if (string.isEmpty()) { return QUrl(); } const QUrl url = QUrl(string, QUrl::StrictMode); if (!url.isValid()) { throw JsonException(what + " is not a correctly formatted URL"); } return url; } template <> QDir requireIsType<QDir>(const QJsonValue& value, const QString& what) { const QString string = requireIsType<QString>(value, what); // FIXME: does not handle invalid characters! return QDir::current().absoluteFilePath(string); } template <> QUuid requireIsType<QUuid>(const QJsonValue& value, const QString& what) { const QString string = requireIsType<QString>(value, what); const QUuid uuid = QUuid(string); if (uuid.toString() != string) // converts back => valid { throw JsonException(what + " is not a valid UUID"); } return uuid; } template <> QJsonObject requireIsType<QJsonObject>(const QJsonValue& value, const QString& what) { if (!value.isObject()) { throw JsonException(what + " is not an object"); } return value.toObject(); } template <> QVariant requireIsType<QVariant>(const QJsonValue& value, const QString& what) { if (value.isNull() || value.isUndefined()) { throw JsonException(what + " is null or undefined"); } return value.toVariant(); } template <> QJsonValue requireIsType<QJsonValue>(const QJsonValue& value, const QString& what) { if (value.isNull() || value.isUndefined()) { throw JsonException(what + " is null or undefined"); } return value; } } // namespace Json
8,078
C++
.cpp
259
27.84556
87
0.707799
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
28,900
InstanceList.cpp
PrismLauncher_PrismLauncher/launcher/InstanceList.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * Copyright (C) 2023 TheKodeToad <TheKodeToad@proton.me> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 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 <QDebug> #include <QDir> #include <QDirIterator> #include <QFile> #include <QFileInfo> #include <QFileSystemWatcher> #include <QJsonArray> #include <QJsonDocument> #include <QMimeData> #include <QPair> #include <QSet> #include <QStack> #include <QTextStream> #include <QThread> #include <QTimer> #include <QUuid> #include <QXmlStreamReader> #include "BaseInstance.h" #include "ExponentialSeries.h" #include "FileSystem.h" #include "InstanceList.h" #include "InstanceTask.h" #include "NullInstance.h" #include "WatchLock.h" #include "minecraft/MinecraftInstance.h" #include "settings/INISettingsObject.h" #ifdef Q_OS_WIN32 #include <Windows.h> #endif const static int GROUP_FILE_FORMAT_VERSION = 1; InstanceList::InstanceList(SettingsObjectPtr settings, const QString& instDir, QObject* parent) : QAbstractListModel(parent), m_globalSettings(settings) { resumeWatch(); // Create aand normalize path if (!QDir::current().exists(instDir)) { QDir::current().mkpath(instDir); } connect(this, &InstanceList::instancesChanged, this, &InstanceList::providerUpdated); // NOTE: canonicalPath requires the path to exist. Do not move this above the creation block! m_instDir = QDir(instDir).canonicalPath(); m_watcher = new QFileSystemWatcher(this); connect(m_watcher, &QFileSystemWatcher::directoryChanged, this, &InstanceList::instanceDirContentsChanged); m_watcher->addPath(m_instDir); } InstanceList::~InstanceList() {} Qt::DropActions InstanceList::supportedDragActions() const { return Qt::MoveAction; } Qt::DropActions InstanceList::supportedDropActions() const { return Qt::MoveAction; } bool InstanceList::canDropMimeData(const QMimeData* data, [[maybe_unused]] Qt::DropAction action, [[maybe_unused]] int row, [[maybe_unused]] int column, [[maybe_unused]] const QModelIndex& parent) const { if (data && data->hasFormat("application/x-instanceid")) { return true; } return false; } bool InstanceList::dropMimeData(const QMimeData* data, [[maybe_unused]] Qt::DropAction action, [[maybe_unused]] int row, [[maybe_unused]] int column, [[maybe_unused]] const QModelIndex& parent) { if (data && data->hasFormat("application/x-instanceid")) { return true; } return false; } QStringList InstanceList::mimeTypes() const { auto types = QAbstractListModel::mimeTypes(); types.push_back("application/x-instanceid"); return types; } QMimeData* InstanceList::mimeData(const QModelIndexList& indexes) const { auto mimeData = QAbstractListModel::mimeData(indexes); if (indexes.size() == 1) { auto instanceId = data(indexes[0], InstanceIDRole).toString(); mimeData->setData("application/x-instanceid", instanceId.toUtf8()); } return mimeData; } QStringList InstanceList::getLinkedInstancesById(const QString& id) const { QStringList linkedInstances; for (auto inst : m_instances) { if (inst->isLinkedToInstanceId(id)) linkedInstances.append(inst->id()); } return linkedInstances; } int InstanceList::rowCount(const QModelIndex& parent) const { Q_UNUSED(parent); return m_instances.count(); } QModelIndex InstanceList::index(int row, int column, const QModelIndex& parent) const { Q_UNUSED(parent); if (row < 0 || row >= m_instances.size()) return QModelIndex(); return createIndex(row, column, (void*)m_instances.at(row).get()); } QVariant InstanceList::data(const QModelIndex& index, int role) const { if (!index.isValid()) { return QVariant(); } BaseInstance* pdata = static_cast<BaseInstance*>(index.internalPointer()); switch (role) { case InstancePointerRole: { QVariant v = QVariant::fromValue((void*)pdata); return v; } case InstanceIDRole: { return pdata->id(); } case Qt::EditRole: case Qt::DisplayRole: { return pdata->name(); } case Qt::AccessibleTextRole: { return tr("%1 Instance").arg(pdata->name()); } case Qt::ToolTipRole: { return pdata->instanceRoot(); } case Qt::DecorationRole: { return pdata->iconKey(); } // HACK: see InstanceView.h in gui! case GroupRole: { return getInstanceGroup(pdata->id()); } default: break; } return QVariant(); } bool InstanceList::setData(const QModelIndex& index, const QVariant& value, int role) { if (!index.isValid()) { return false; } if (role != Qt::EditRole) { return false; } BaseInstance* pdata = static_cast<BaseInstance*>(index.internalPointer()); auto newName = value.toString(); if (pdata->name() == newName) { return true; } pdata->setName(newName); return true; } Qt::ItemFlags InstanceList::flags(const QModelIndex& index) const { Qt::ItemFlags f; if (index.isValid()) { f |= (Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable); } return f; } GroupId InstanceList::getInstanceGroup(const InstanceId& id) const { auto inst = getInstanceById(id); if (!inst) { return GroupId(); } auto iter = m_instanceGroupIndex.find(inst->id()); if (iter != m_instanceGroupIndex.end()) { return *iter; } return GroupId(); } void InstanceList::setInstanceGroup(const InstanceId& id, GroupId name) { if (name.isEmpty() && !name.isNull()) name = QString(); auto inst = getInstanceById(id); if (!inst) { qDebug() << "Attempt to set a null instance's group"; return; } bool changed = false; auto iter = m_instanceGroupIndex.find(inst->id()); if (iter != m_instanceGroupIndex.end()) { if (*iter != name) { decreaseGroupCount(*iter); *iter = name; changed = true; } } else { changed = true; m_instanceGroupIndex[id] = name; } if (changed) { increaseGroupCount(name); auto idx = getInstIndex(inst.get()); emit dataChanged(index(idx), index(idx), { GroupRole }); saveGroupList(); } } QStringList InstanceList::getGroups() { return m_groupNameCache.keys(); } void InstanceList::deleteGroup(const GroupId& name) { m_groupNameCache.remove(name); m_collapsedGroups.remove(name); bool removed = false; qDebug() << "Delete group" << name; for (auto& instance : m_instances) { const QString& instID = instance->id(); const QString instGroupName = getInstanceGroup(instID); if (instGroupName == name) { m_instanceGroupIndex.remove(instID); qDebug() << "Remove" << instID << "from group" << name; removed = true; auto idx = getInstIndex(instance.get()); if (idx >= 0) emit dataChanged(index(idx), index(idx), { GroupRole }); } } if (removed) saveGroupList(); } void InstanceList::renameGroup(const QString& src, const QString& dst) { m_groupNameCache.remove(src); if (m_collapsedGroups.remove(src)) m_collapsedGroups.insert(dst); bool modified = false; qDebug() << "Rename group" << src << "to" << dst; for (auto& instance : m_instances) { const QString& instID = instance->id(); const QString instGroupName = getInstanceGroup(instID); if (instGroupName == src) { m_instanceGroupIndex[instID] = dst; increaseGroupCount(dst); qDebug() << "Set" << instID << "group to" << dst; modified = true; auto idx = getInstIndex(instance.get()); if (idx >= 0) emit dataChanged(index(idx), index(idx), { GroupRole }); } } if (modified) saveGroupList(); } bool InstanceList::isGroupCollapsed(const QString& group) { return m_collapsedGroups.contains(group); } bool InstanceList::trashInstance(const InstanceId& id) { auto inst = getInstanceById(id); if (!inst) { qDebug() << "Cannot trash instance" << id << ". No such instance is present (deleted externally?)."; return false; } QString cachedGroupId = m_instanceGroupIndex[id]; qDebug() << "Will trash instance" << id; QString trashedLoc; if (m_instanceGroupIndex.remove(id)) { decreaseGroupCount(cachedGroupId); saveGroupList(); } if (!FS::trash(inst->instanceRoot(), &trashedLoc)) { qDebug() << "Trash of instance" << id << "has not been completely successfully..."; return false; } qDebug() << "Instance" << id << "has been trashed by the launcher."; m_trashHistory.push({ id, inst->instanceRoot(), trashedLoc, cachedGroupId }); return true; } bool InstanceList::trashedSomething() { return !m_trashHistory.empty(); } void InstanceList::undoTrashInstance() { if (m_trashHistory.empty()) { qWarning() << "Nothing to recover from trash."; return; } auto top = m_trashHistory.pop(); while (QDir(top.path).exists()) { top.id += "1"; top.path += "1"; } qDebug() << "Moving" << top.trashPath << "back to" << top.path; QFile(top.trashPath).rename(top.path); m_instanceGroupIndex[top.id] = top.groupName; increaseGroupCount(top.groupName); saveGroupList(); emit instancesChanged(); } void InstanceList::deleteInstance(const InstanceId& id) { auto inst = getInstanceById(id); if (!inst) { qDebug() << "Cannot delete instance" << id << ". No such instance is present (deleted externally?)."; return; } QString cachedGroupId = m_instanceGroupIndex[id]; if (m_instanceGroupIndex.remove(id)) { decreaseGroupCount(cachedGroupId); saveGroupList(); } qDebug() << "Will delete instance" << id; if (!FS::deletePath(inst->instanceRoot())) { qWarning() << "Deletion of instance" << id << "has not been completely successful ..."; return; } qDebug() << "Instance" << id << "has been deleted by the launcher."; } static QMap<InstanceId, InstanceLocator> getIdMapping(const QList<InstancePtr>& list) { QMap<InstanceId, InstanceLocator> out; int i = 0; for (auto& item : list) { auto id = item->id(); if (out.contains(id)) { qWarning() << "Duplicate ID" << id << "in instance list"; } out[id] = std::make_pair(item, i); i++; } return out; } QList<InstanceId> InstanceList::discoverInstances() { qDebug() << "Discovering instances in" << m_instDir; QList<InstanceId> out; QDirIterator iter(m_instDir, QDir::Dirs | QDir::NoDot | QDir::NoDotDot | QDir::Readable | QDir::Hidden, QDirIterator::FollowSymlinks); while (iter.hasNext()) { QString subDir = iter.next(); QFileInfo dirInfo(subDir); if (!QFileInfo(FS::PathCombine(subDir, "instance.cfg")).exists()) continue; // if it is a symlink, ignore it if it goes to the instance folder if (dirInfo.isSymLink()) { QFileInfo targetInfo(dirInfo.symLinkTarget()); QFileInfo instDirInfo(m_instDir); if (targetInfo.canonicalPath() == instDirInfo.canonicalFilePath()) { qDebug() << "Ignoring symlink" << subDir << "that leads into the instances folder"; continue; } } auto id = dirInfo.fileName(); out.append(id); qDebug() << "Found instance ID" << id; } #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) instanceSet = QSet<QString>(out.begin(), out.end()); #else instanceSet = out.toSet(); #endif m_instancesProbed = true; return out; } InstanceList::InstListError InstanceList::loadList() { auto existingIds = getIdMapping(m_instances); QList<InstancePtr> newList; for (auto& id : discoverInstances()) { if (existingIds.contains(id)) { auto instPair = existingIds[id]; existingIds.remove(id); qDebug() << "Should keep and soft-reload" << id; } else { InstancePtr instPtr = loadInstance(id); if (instPtr) { newList.append(instPtr); } } } // TODO: looks like a general algorithm with a few specifics inserted. Do something about it. if (!existingIds.isEmpty()) { // get the list of removed instances and sort it by their original index, from last to first auto deadList = existingIds.values(); auto orderSortPredicate = [](const InstanceLocator& a, const InstanceLocator& b) -> bool { return a.second > b.second; }; std::sort(deadList.begin(), deadList.end(), orderSortPredicate); // remove the contiguous ranges of rows int front_bookmark = -1; int back_bookmark = -1; int currentItem = -1; auto removeNow = [this, &front_bookmark, &back_bookmark, &currentItem]() { beginRemoveRows(QModelIndex(), front_bookmark, back_bookmark); m_instances.erase(m_instances.begin() + front_bookmark, m_instances.begin() + back_bookmark + 1); endRemoveRows(); front_bookmark = -1; back_bookmark = currentItem; }; for (auto& removedItem : deadList) { auto instPtr = removedItem.first; instPtr->invalidate(); currentItem = removedItem.second; if (back_bookmark == -1) { // no bookmark yet back_bookmark = currentItem; } else if (currentItem == front_bookmark - 1) { // part of contiguous sequence, continue } else { // seam between previous and current item removeNow(); } front_bookmark = currentItem; } if (back_bookmark != -1) { removeNow(); } } if (newList.size()) { add(newList); } m_dirty = false; updateTotalPlayTime(); return NoError; } void InstanceList::updateTotalPlayTime() { totalPlayTime = 0; for (auto const& itr : m_instances) { totalPlayTime += itr.get()->totalTimePlayed(); } } void InstanceList::saveNow() { for (auto& item : m_instances) { item->saveNow(); } } void InstanceList::add(const QList<InstancePtr>& t) { beginInsertRows(QModelIndex(), m_instances.count(), m_instances.count() + t.size() - 1); m_instances.append(t); for (auto& ptr : t) { connect(ptr.get(), &BaseInstance::propertiesChanged, this, &InstanceList::propertiesChanged); } endInsertRows(); } void InstanceList::resumeWatch() { if (m_watchLevel > 0) { qWarning() << "Bad suspend level resume in instance list"; return; } m_watchLevel++; if (m_watchLevel > 0 && m_dirty) { loadList(); } } void InstanceList::suspendWatch() { m_watchLevel--; } void InstanceList::providerUpdated() { m_dirty = true; if (m_watchLevel == 1) { loadList(); } } InstancePtr InstanceList::getInstanceById(QString instId) const { if (instId.isEmpty()) return InstancePtr(); for (auto& inst : m_instances) { if (inst->id() == instId) { return inst; } } return InstancePtr(); } InstancePtr InstanceList::getInstanceByManagedName(const QString& managed_name) const { if (managed_name.isEmpty()) return {}; for (auto instance : m_instances) { if (instance->getManagedPackName() == managed_name) return instance; } return {}; } QModelIndex InstanceList::getInstanceIndexById(const QString& id) const { return index(getInstIndex(getInstanceById(id).get())); } int InstanceList::getInstIndex(BaseInstance* inst) const { int count = m_instances.count(); for (int i = 0; i < count; i++) { if (inst == m_instances[i].get()) { return i; } } return -1; } void InstanceList::propertiesChanged(BaseInstance* inst) { int i = getInstIndex(inst); if (i != -1) { emit dataChanged(index(i), index(i)); updateTotalPlayTime(); } } InstancePtr InstanceList::loadInstance(const InstanceId& id) { if (!m_groupsLoaded) { loadGroupList(); } auto instanceRoot = FS::PathCombine(m_instDir, id); auto instanceSettings = std::make_shared<INISettingsObject>(FS::PathCombine(instanceRoot, "instance.cfg")); InstancePtr inst; instanceSettings->registerSetting("InstanceType", ""); QString inst_type = instanceSettings->get("InstanceType").toString(); // NOTE: Some launcher versions didn't save the InstanceType properly. We will just bank on the probability that this is probably a // OneSix instance if (inst_type == "OneSix" || inst_type.isEmpty()) { inst.reset(new MinecraftInstance(m_globalSettings, instanceSettings, instanceRoot)); } else { inst.reset(new NullInstance(m_globalSettings, instanceSettings, instanceRoot)); } qDebug() << "Loaded instance " << inst->name() << " from " << inst->instanceRoot(); return inst; } void InstanceList::increaseGroupCount(const QString& group) { if (group.isEmpty()) return; ++m_groupNameCache[group]; } void InstanceList::decreaseGroupCount(const QString& group) { if (group.isEmpty()) return; if (--m_groupNameCache[group] < 1) { m_groupNameCache.remove(group); m_collapsedGroups.remove(group); } } void InstanceList::saveGroupList() { qDebug() << "Will save group list now."; if (!m_instancesProbed) { qDebug() << "Group saving prevented because we don't know the full list of instances yet."; return; } WatchLock foo(m_watcher, m_instDir); QString groupFileName = m_instDir + "/instgroups.json"; QMap<QString, QSet<QString>> reverseGroupMap; for (auto iter = m_instanceGroupIndex.begin(); iter != m_instanceGroupIndex.end(); iter++) { const QString& id = iter.key(); QString group = iter.value(); if (group.isEmpty()) continue; if (!instanceSet.contains(id)) { qDebug() << "Skipping saving missing instance" << id << "to groups list."; continue; } if (!reverseGroupMap.count(group)) { QSet<QString> set; set.insert(id); reverseGroupMap[group] = set; } else { QSet<QString>& set = reverseGroupMap[group]; set.insert(id); } } QJsonObject toplevel; toplevel.insert("formatVersion", QJsonValue(QString("1"))); QJsonObject groupsArr; for (auto iter = reverseGroupMap.begin(); iter != reverseGroupMap.end(); iter++) { auto list = iter.value(); auto name = iter.key(); QJsonObject groupObj; QJsonArray instanceArr; groupObj.insert("hidden", QJsonValue(m_collapsedGroups.contains(name))); for (auto item : list) { instanceArr.append(QJsonValue(item)); } groupObj.insert("instances", instanceArr); groupsArr.insert(name, groupObj); } toplevel.insert("groups", groupsArr); // empty string represents ungrouped "group" if (m_collapsedGroups.contains("")) { QJsonObject ungrouped; ungrouped.insert("hidden", QJsonValue(true)); toplevel.insert("ungrouped", ungrouped); } QJsonDocument doc(toplevel); try { FS::write(groupFileName, doc.toJson()); qDebug() << "Group list saved."; } catch (const FS::FileSystemException& e) { qCritical() << "Failed to write instance group file :" << e.cause(); } } void InstanceList::loadGroupList() { qDebug() << "Will load group list now."; QString groupFileName = m_instDir + "/instgroups.json"; // if there's no group file, fail if (!QFileInfo(groupFileName).exists()) return; QByteArray jsonData; try { jsonData = FS::read(groupFileName); } catch (const FS::FileSystemException& e) { qCritical() << "Failed to read instance group file :" << e.cause(); return; } QJsonParseError error; QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonData, &error); // if the json was bad, fail if (error.error != QJsonParseError::NoError) { qCritical() << QString("Failed to parse instance group file: %1 at offset %2") .arg(error.errorString(), QString::number(error.offset)) .toUtf8(); return; } // if the root of the json wasn't an object, fail if (!jsonDoc.isObject()) { qWarning() << "Invalid group file. Root entry should be an object."; return; } QJsonObject rootObj = jsonDoc.object(); // Make sure the format version matches, otherwise fail. if (rootObj.value("formatVersion").toVariant().toInt() != GROUP_FILE_FORMAT_VERSION) return; // Get the groups. if it's not an object, fail if (!rootObj.value("groups").isObject()) { qWarning() << "Invalid group list JSON: 'groups' should be an object."; return; } m_instanceGroupIndex.clear(); m_groupNameCache.clear(); // Iterate through all the groups. QJsonObject groupMapping = rootObj.value("groups").toObject(); for (QJsonObject::iterator iter = groupMapping.begin(); iter != groupMapping.end(); iter++) { QString groupName = iter.key(); if (iter.key().isEmpty()) { qWarning() << "Redundant empty group found"; continue; } // If not an object, complain and skip to the next one. if (!iter.value().isObject()) { qWarning() << QString("Group '%1' in the group list should be an object").arg(groupName).toUtf8(); continue; } QJsonObject groupObj = iter.value().toObject(); if (!groupObj.value("instances").isArray()) { qWarning() << QString("Group '%1' in the group list is invalid. It should contain an array called 'instances'.") .arg(groupName) .toUtf8(); continue; } auto hidden = groupObj.value("hidden").toBool(false); if (hidden) m_collapsedGroups.insert(groupName); // Iterate through the list of instances in the group. QJsonArray instancesArray = groupObj.value("instances").toArray(); for (auto value : instancesArray) { m_instanceGroupIndex[value.toString()] = groupName; increaseGroupCount(groupName); } } bool ungroupedHidden = false; if (rootObj.value("ungrouped").isObject()) { QJsonObject ungrouped = rootObj.value("ungrouped").toObject(); ungroupedHidden = ungrouped.value("hidden").toBool(false); } if (ungroupedHidden) { // empty string represents ungrouped "group" m_collapsedGroups.insert(""); } m_groupsLoaded = true; qDebug() << "Group list loaded."; } void InstanceList::instanceDirContentsChanged(const QString& path) { Q_UNUSED(path); emit instancesChanged(); } void InstanceList::on_InstFolderChanged([[maybe_unused]] const Setting& setting, QVariant value) { QString newInstDir = QDir(value.toString()).canonicalPath(); if (newInstDir != m_instDir) { if (m_groupsLoaded) { saveGroupList(); } m_instDir = newInstDir; m_groupsLoaded = false; beginRemoveRows(QModelIndex(), 0, count()); m_instances.erase(m_instances.begin(), m_instances.end()); endRemoveRows(); emit instancesChanged(); } } void InstanceList::on_GroupStateChanged(const QString& group, bool collapsed) { qDebug() << "Group" << group << (collapsed ? "collapsed" : "expanded"); if (collapsed) { m_collapsedGroups.insert(group); } else { m_collapsedGroups.remove(group); } saveGroupList(); } class InstanceStaging : public Task { Q_OBJECT const unsigned minBackoff = 1; const unsigned maxBackoff = 16; public: InstanceStaging(InstanceList* parent, InstanceTask* child, SettingsObjectPtr settings) : m_parent(parent), backoff(minBackoff, maxBackoff) { m_stagingPath = parent->getStagedInstancePath(); m_child.reset(child); m_child->setStagingPath(m_stagingPath); m_child->setParentSettings(std::move(settings)); connect(child, &Task::succeeded, this, &InstanceStaging::childSucceeded); connect(child, &Task::failed, this, &InstanceStaging::childFailed); connect(child, &Task::aborted, this, &InstanceStaging::childAborted); connect(child, &Task::abortStatusChanged, this, &InstanceStaging::setAbortable); connect(child, &Task::status, this, &InstanceStaging::setStatus); connect(child, &Task::details, this, &InstanceStaging::setDetails); connect(child, &Task::progress, this, &InstanceStaging::setProgress); connect(child, &Task::stepProgress, this, &InstanceStaging::propagateStepProgress); connect(&m_backoffTimer, &QTimer::timeout, this, &InstanceStaging::childSucceeded); } virtual ~InstanceStaging() {} // FIXME/TODO: add ability to abort during instance commit retries bool abort() override { if (!canAbort()) return false; m_child->abort(); return Task::abort(); } bool canAbort() const override { return (m_child && m_child->canAbort()); } protected: virtual void executeTask() override { if (m_stagingPath.isNull()) { emitFailed(tr("Could not create staging folder")); return; } m_child->start(); } QStringList warnings() const override { return m_child->warnings(); } private slots: void childSucceeded() { unsigned sleepTime = backoff(); if (m_parent->commitStagedInstance(m_stagingPath, *m_child.get(), m_child->group(), *m_child.get())) { emitSucceeded(); return; } // we actually failed, retry? if (sleepTime == maxBackoff) { emitFailed(tr("Failed to commit instance, even after multiple retries. It is being blocked by something.")); return; } qDebug() << "Failed to commit instance" << m_child->name() << "Initiating backoff:" << sleepTime; m_backoffTimer.start(sleepTime * 500); } void childFailed(const QString& reason) { m_parent->destroyStagingPath(m_stagingPath); emitFailed(reason); } void childAborted() { m_parent->destroyStagingPath(m_stagingPath); emitAborted(); } private: InstanceList* m_parent; /* * WHY: the whole reason why this uses an exponential backoff retry scheme is antivirus on Windows. * Basically, it starts messing things up while the launcher is extracting/creating instances * and causes that horrible failure that is NTFS to lock files in place because they are open. */ ExponentialSeries backoff; QString m_stagingPath; unique_qobject_ptr<InstanceTask> m_child; QTimer m_backoffTimer; }; Task* InstanceList::wrapInstanceTask(InstanceTask* task) { return new InstanceStaging(this, task, m_globalSettings); } QString InstanceList::getStagedInstancePath() { const QString tempRoot = FS::PathCombine(m_instDir, ".tmp"); QString result; int tries = 0; do { if (++tries > 256) return {}; const QString key = QUuid::createUuid().toString(QUuid::Id128).left(6); result = FS::PathCombine(tempRoot, key); } while (QFileInfo::exists(result)); if (!QDir::current().mkpath(result)) return {}; #ifdef Q_OS_WIN32 SetFileAttributesA(tempRoot.toStdString().c_str(), FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_NOT_CONTENT_INDEXED); #endif return result; } bool InstanceList::commitStagedInstance(const QString& path, InstanceName const& instanceName, QString groupName, InstanceTask const& commiting) { if (groupName.isEmpty() && !groupName.isNull()) groupName = QString(); QString instID; InstancePtr inst; auto should_override = commiting.shouldOverride(); if (should_override) { instID = commiting.originalInstanceID(); } else { instID = FS::DirNameFromString(instanceName.modifiedName(), m_instDir); } Q_ASSERT(!instID.isEmpty()); { WatchLock lock(m_watcher, m_instDir); QString destination = FS::PathCombine(m_instDir, instID); if (should_override) { if (!FS::overrideFolder(destination, path)) { qWarning() << "Failed to override" << path << "to" << destination; return false; } } else { if (!FS::move(path, destination)) { qWarning() << "Failed to move" << path << "to" << destination; return false; } m_instanceGroupIndex[instID] = groupName; increaseGroupCount(groupName); } instanceSet.insert(instID); emit instancesChanged(); emit instanceSelectRequest(instID); } saveGroupList(); return true; } bool InstanceList::destroyStagingPath(const QString& keyPath) { return FS::deletePath(keyPath); } int InstanceList::getTotalPlayTime() { updateTotalPlayTime(); return totalPlayTime; } #include "InstanceList.moc"
31,610
C++
.cpp
908
28.144273
138
0.632729
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
28,901
StringUtils.cpp
PrismLauncher_PrismLauncher/launcher/StringUtils.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * Copyright (C) 2023 flowln <flowlnlnln@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 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 "StringUtils.h" #include <qpair.h> #include <QRegularExpression> #include <QUuid> #include <cmath> /// If you're wondering where these came from exactly, then know you're not the only one =D /// TAKEN FROM Qt, because it doesn't expose it intelligently static inline QChar getNextChar(const QString& s, int location) { return (location < s.length()) ? s.at(location) : QChar(); } /// TAKEN FROM Qt, because it doesn't expose it intelligently int StringUtils::naturalCompare(const QString& s1, const QString& s2, Qt::CaseSensitivity cs) { int l1 = 0, l2 = 0; while (l1 <= s1.count() && l2 <= s2.count()) { // skip spaces, tabs and 0's QChar c1 = getNextChar(s1, l1); while (c1.isSpace()) c1 = getNextChar(s1, ++l1); QChar c2 = getNextChar(s2, l2); while (c2.isSpace()) c2 = getNextChar(s2, ++l2); if (c1.isDigit() && c2.isDigit()) { while (c1.digitValue() == 0) c1 = getNextChar(s1, ++l1); while (c2.digitValue() == 0) c2 = getNextChar(s2, ++l2); int lookAheadLocation1 = l1; int lookAheadLocation2 = l2; int currentReturnValue = 0; // find the last digit, setting currentReturnValue as we go if it isn't equal for (QChar lookAhead1 = c1, lookAhead2 = c2; (lookAheadLocation1 <= s1.length() && lookAheadLocation2 <= s2.length()); lookAhead1 = getNextChar(s1, ++lookAheadLocation1), lookAhead2 = getNextChar(s2, ++lookAheadLocation2)) { bool is1ADigit = !lookAhead1.isNull() && lookAhead1.isDigit(); bool is2ADigit = !lookAhead2.isNull() && lookAhead2.isDigit(); if (!is1ADigit && !is2ADigit) break; if (!is1ADigit) return -1; if (!is2ADigit) return 1; if (currentReturnValue == 0) { if (lookAhead1 < lookAhead2) { currentReturnValue = -1; } else if (lookAhead1 > lookAhead2) { currentReturnValue = 1; } } } if (currentReturnValue != 0) return currentReturnValue; } if (cs == Qt::CaseInsensitive) { if (!c1.isLower()) c1 = c1.toLower(); if (!c2.isLower()) c2 = c2.toLower(); } int r = QString::localeAwareCompare(c1, c2); if (r < 0) return -1; if (r > 0) return 1; l1 += 1; l2 += 1; } // The two strings are the same (02 == 2) so fall back to the normal sort return QString::compare(s1, s2, cs); } QString StringUtils::truncateUrlHumanFriendly(QUrl& url, int max_len, bool hard_limit) { auto display_options = QUrl::RemoveUserInfo | QUrl::RemoveFragment | QUrl::NormalizePathSegments; auto str_url = url.toDisplayString(display_options); if (str_url.length() <= max_len) return str_url; auto url_path_parts = url.path().split('/'); QString last_path_segment = url_path_parts.takeLast(); if (url_path_parts.size() >= 1 && url_path_parts.first().isEmpty()) url_path_parts.removeFirst(); // drop empty first segment (from leading / ) if (url_path_parts.size() >= 1) url_path_parts.removeLast(); // drop the next to last path segment auto url_template = QStringLiteral("%1://%2/%3%4"); auto url_compact = url_path_parts.isEmpty() ? url_template.arg(url.scheme(), url.host(), QStringList({ "...", last_path_segment }).join('/'), url.query()) : url_template.arg(url.scheme(), url.host(), QStringList({ url_path_parts.join('/'), "...", last_path_segment }).join('/'), url.query()); // remove url parts one by one if it's still too long while (url_compact.length() > max_len && url_path_parts.size() >= 1) { url_path_parts.removeLast(); // drop the next to last path segment url_compact = url_path_parts.isEmpty() ? url_template.arg(url.scheme(), url.host(), QStringList({ "...", last_path_segment }).join('/'), url.query()) : url_template.arg(url.scheme(), url.host(), QStringList({ url_path_parts.join('/'), "...", last_path_segment }).join('/'), url.query()); } if ((url_compact.length() >= max_len) && hard_limit) { // still too long, truncate normally url_compact = QString(str_url); auto to_remove = url_compact.length() - max_len + 3; url_compact.remove(url_compact.length() - to_remove - 1, to_remove); url_compact.append("..."); } return url_compact; } static const QStringList s_units_si{ "KB", "MB", "GB", "TB" }; static const QStringList s_units_kibi{ "KiB", "MiB", "GiB", "TiB" }; QString StringUtils::humanReadableFileSize(double bytes, bool use_si, int decimal_points) { const QStringList units = use_si ? s_units_si : s_units_kibi; const int scale = use_si ? 1000 : 1024; int u = -1; double r = pow(10, decimal_points); do { bytes /= scale; u++; } while (round(abs(bytes) * r) / r >= scale && u < units.length() - 1); return QString::number(bytes, 'f', 2) + " " + units[u]; } QString StringUtils::getRandomAlphaNumeric() { return QUuid::createUuid().toString(QUuid::Id128); } QPair<QString, QString> StringUtils::splitFirst(const QString& s, const QString& sep, Qt::CaseSensitivity cs) { QString left, right; auto index = s.indexOf(sep, 0, cs); left = s.mid(0, index); right = s.mid(index + sep.length()); return qMakePair(left, right); } QPair<QString, QString> StringUtils::splitFirst(const QString& s, QChar sep, Qt::CaseSensitivity cs) { QString left, right; auto index = s.indexOf(sep, 0, cs); left = s.mid(0, index); right = s.mid(left.length() + 1); return qMakePair(left, right); } QPair<QString, QString> StringUtils::splitFirst(const QString& s, const QRegularExpression& re) { QString left, right; QRegularExpressionMatch match; auto index = s.indexOf(re, 0, &match); left = s.mid(0, index); auto end = match.hasMatch() ? left.length() + match.capturedLength() : left.length() + 1; right = s.mid(end); return qMakePair(left, right); } static const QRegularExpression ulMatcher("<\\s*/\\s*ul\\s*>"); QString StringUtils::htmlListPatch(QString htmlStr) { int pos = htmlStr.indexOf(ulMatcher); int imgPos; while (pos != -1) { pos = htmlStr.indexOf(">", pos) + 1; // Get the size of the </ul> tag. Add one for zeroeth index imgPos = htmlStr.indexOf("<img ", pos); if (imgPos == -1) break; // no image after the tag auto textBetween = htmlStr.mid(pos, imgPos - pos).trimmed(); // trim all white spaces if (textBetween.isEmpty()) htmlStr.insert(pos, "<br>"); pos = htmlStr.indexOf(ulMatcher, pos); } return htmlStr; }
8,763
C++
.cpp
200
36.285
138
0.608818
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,902
ApplicationMessage.cpp
PrismLauncher_PrismLauncher/launcher/ApplicationMessage.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 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 "ApplicationMessage.h" #include <QJsonDocument> #include <QJsonObject> #include "Json.h" void ApplicationMessage::parse(const QByteArray& input) { auto doc = Json::requireDocument(input, "ApplicationMessage"); auto root = Json::requireObject(doc, "ApplicationMessage"); command = root.value("command").toString(); args.clear(); auto parsedArgs = root.value("args").toObject(); for (auto iter = parsedArgs.constBegin(); iter != parsedArgs.constEnd(); iter++) { args.insert(iter.key(), iter.value().toString()); } } QByteArray ApplicationMessage::serialize() { QJsonObject root; root.insert("command", command); QJsonObject outArgs; for (auto iter = args.constBegin(); iter != args.constEnd(); iter++) { outArgs.insert(iter.key(), iter.value()); } root.insert("args", outArgs); return Json::toText(root); }
2,386
C++
.cpp
60
36.916667
86
0.716688
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,903
GZip.cpp
PrismLauncher_PrismLauncher/launcher/GZip.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 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 "GZip.h" #include <zlib.h> #include <QByteArray> bool GZip::unzip(const QByteArray& compressedBytes, QByteArray& uncompressedBytes) { if (compressedBytes.size() == 0) { uncompressedBytes = compressedBytes; return true; } unsigned uncompLength = compressedBytes.size(); uncompressedBytes.clear(); uncompressedBytes.resize(uncompLength); z_stream strm; memset(&strm, 0, sizeof(strm)); strm.next_in = (Bytef*)compressedBytes.data(); strm.avail_in = compressedBytes.size(); bool done = false; if (inflateInit2(&strm, (16 + MAX_WBITS)) != Z_OK) { return false; } int err = Z_OK; while (!done) { // If our output buffer is too small if (strm.total_out >= uncompLength) { uncompressedBytes.resize(uncompLength * 2); uncompLength *= 2; } strm.next_out = reinterpret_cast<Bytef*>((uncompressedBytes.data() + strm.total_out)); strm.avail_out = uncompLength - strm.total_out; // Inflate another chunk. err = inflate(&strm, Z_SYNC_FLUSH); if (err == Z_STREAM_END) done = true; else if (err != Z_OK) { break; } } if (inflateEnd(&strm) != Z_OK || !done) { return false; } uncompressedBytes.resize(strm.total_out); return true; } bool GZip::zip(const QByteArray& uncompressedBytes, QByteArray& compressedBytes) { if (uncompressedBytes.size() == 0) { compressedBytes = uncompressedBytes; return true; } unsigned compLength = qMin(uncompressedBytes.size(), 16); compressedBytes.clear(); compressedBytes.resize(compLength); z_stream zs; memset(&zs, 0, sizeof(zs)); if (deflateInit2(&zs, Z_DEFAULT_COMPRESSION, Z_DEFLATED, (16 + MAX_WBITS), 8, Z_DEFAULT_STRATEGY) != Z_OK) { return false; } zs.next_in = (Bytef*)uncompressedBytes.data(); zs.avail_in = uncompressedBytes.size(); int ret; compressedBytes.resize(uncompressedBytes.size()); unsigned offset = 0; unsigned temp = 0; do { auto remaining = compressedBytes.size() - offset; if (remaining < 1) { compressedBytes.resize(compressedBytes.size() * 2); } zs.next_out = reinterpret_cast<Bytef*>((compressedBytes.data() + offset)); temp = zs.avail_out = compressedBytes.size() - offset; ret = deflate(&zs, Z_FINISH); offset += temp - zs.avail_out; } while (ret == Z_OK); compressedBytes.resize(offset); if (deflateEnd(&zs) != Z_OK) { return false; } if (ret != Z_STREAM_END) { return false; } return true; }
4,199
C++
.cpp
116
30.974138
112
0.660182
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
28,904
LaunchController.cpp
PrismLauncher_PrismLauncher/launcher/LaunchController.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * Copyright (C) 2023 TheKodeToad <TheKodeToad@proton.me> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 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 "LaunchController.h" #include "Application.h" #include "launch/steps/PrintServers.h" #include "minecraft/auth/AccountData.h" #include "minecraft/auth/AccountList.h" #include "ui/InstanceWindow.h" #include "ui/MainWindow.h" #include "ui/dialogs/CustomMessageBox.h" #include "ui/dialogs/MSALoginDialog.h" #include "ui/dialogs/ProfileSelectDialog.h" #include "ui/dialogs/ProfileSetupDialog.h" #include "ui/dialogs/ProgressDialog.h" #include <QHostAddress> #include <QHostInfo> #include <QInputDialog> #include <QLineEdit> #include <QList> #include <QPushButton> #include <QRegularExpression> #include <QStringList> #include "BuildConfig.h" #include "JavaCommon.h" #include "launch/steps/TextPrint.h" #include "tasks/Task.h" LaunchController::LaunchController() : Task() {} void LaunchController::executeTask() { if (!m_instance) { emitFailed(tr("No instance specified!")); return; } if (!JavaCommon::checkJVMArgs(m_instance->settings()->get("JvmArgs").toString(), m_parentWidget)) { emitFailed(tr("Invalid Java arguments specified. Please fix this first.")); return; } login(); } void LaunchController::decideAccount() { if (m_accountToUse) { return; } // Find an account to use. auto accounts = APPLICATION->accounts(); if (accounts->count() <= 0 || !accounts->anyAccountIsValid()) { // Tell the user they need to log in at least one account in order to play. auto reply = CustomMessageBox::selectable(m_parentWidget, tr("No Accounts"), tr("In order to play Minecraft, you must have at least one Microsoft " "account which owns Minecraft logged in. " "Would you like to open the account manager to add an account now?"), QMessageBox::Information, QMessageBox::Yes | QMessageBox::No) ->exec(); if (reply == QMessageBox::Yes) { // Open the account manager. APPLICATION->ShowGlobalSettings(m_parentWidget, "accounts"); } else if (reply == QMessageBox::No) { // Do not open "profile select" dialog. return; } } // Select the account to use. If the instance has a specific account set, that will be used. Otherwise, the default account will be used auto instanceAccountId = m_instance->settings()->get("InstanceAccountId").toString(); auto instanceAccountIndex = accounts->findAccountByProfileId(instanceAccountId); if (instanceAccountIndex == -1 || instanceAccountId.isEmpty()) { m_accountToUse = accounts->defaultAccount(); } else { m_accountToUse = accounts->at(instanceAccountIndex); } if (!m_accountToUse) { // If no default account is set, ask the user which one to use. ProfileSelectDialog selectDialog(tr("Which account would you like to use?"), ProfileSelectDialog::GlobalDefaultCheckbox, m_parentWidget); selectDialog.exec(); // Launch the instance with the selected account. m_accountToUse = selectDialog.selectedAccount(); // If the user said to use the account as default, do that. if (selectDialog.useAsGlobalDefault() && m_accountToUse) { accounts->setDefaultAccount(m_accountToUse); } } } bool LaunchController::askPlayDemo() { QMessageBox box(m_parentWidget); box.setWindowTitle(tr("Play demo?")); box.setText( tr("This account does not own Minecraft.\nYou need to purchase the game first to play it.\n\nDo you want to play " "the demo?")); box.setIcon(QMessageBox::Warning); auto demoButton = box.addButton(tr("Play Demo"), QMessageBox::ButtonRole::YesRole); auto cancelButton = box.addButton(tr("Cancel"), QMessageBox::ButtonRole::NoRole); box.setDefaultButton(cancelButton); box.exec(); return box.clickedButton() == demoButton; } QString LaunchController::askOfflineName(QString playerName, bool demo, bool& ok) { // we ask the user for a player name QString message = tr("Choose your offline mode player name."); if (demo) { message = tr("Choose your demo mode player name."); } QString lastOfflinePlayerName = APPLICATION->settings()->get("LastOfflinePlayerName").toString(); QString usedname = lastOfflinePlayerName.isEmpty() ? playerName : lastOfflinePlayerName; QString name = QInputDialog::getText(m_parentWidget, tr("Player name"), message, QLineEdit::Normal, usedname, &ok); if (!ok) return {}; if (name.length()) { usedname = name; APPLICATION->settings()->set("LastOfflinePlayerName", usedname); } return usedname; } void LaunchController::login() { decideAccount(); if (!m_accountToUse) { // if no account is selected, ask about demo if (!m_demo) { m_demo = askPlayDemo(); } if (m_demo) { // we ask the user for a player name bool ok = false; auto name = askOfflineName("Player", m_demo, ok); if (ok) { m_session = std::make_shared<AuthSession>(); m_session->MakeDemo(name, MinecraftAccount::uuidFromUsername(name).toString().remove(QRegularExpression("[{}-]"))); launchInstance(); return; } } // if no account is selected, we bail emitFailed(tr("No account selected for launch.")); return; } // we loop until the user succeeds in logging in or gives up bool tryagain = true; unsigned int tries = 0; if ((m_accountToUse->accountType() != AccountType::Offline && m_accountToUse->accountState() == AccountState::Offline) || m_accountToUse->shouldRefresh()) { // Force account refresh on the account used to launch the instance updating the AccountState // only on first try and if it is not meant to be offline auto accounts = APPLICATION->accounts(); accounts->requestRefresh(m_accountToUse->internalId()); } while (tryagain) { if (tries > 0 && tries % 3 == 0) { auto result = QMessageBox::question(m_parentWidget, tr("Continue launch?"), tr("It looks like we couldn't launch after %1 tries. Do you want to continue trying?").arg(tries)); if (result == QMessageBox::No) { emitAborted(); return; } } tries++; m_session = std::make_shared<AuthSession>(); m_session->wants_online = m_online; m_session->demo = m_demo; m_accountToUse->fillSession(m_session); // Launch immediately in true offline mode if (m_accountToUse->accountType() == AccountType::Offline) { launchInstance(); return; } switch (m_accountToUse->accountState()) { case AccountState::Offline: { m_session->wants_online = false; } /* fallthrough */ case AccountState::Online: { if (!m_session->wants_online) { // we ask the user for a player name bool ok = false; QString name; if (m_offlineName.isEmpty()) { name = askOfflineName(m_session->player_name, m_session->demo, ok); if (!ok) { tryagain = false; break; } } else { name = m_offlineName; } m_session->MakeOffline(name); // offline flavored game from here :3 } if (m_accountToUse->ownsMinecraft()) { if (!m_accountToUse->hasProfile()) { // Now handle setting up a profile name here... ProfileSetupDialog dialog(m_accountToUse, m_parentWidget); if (dialog.exec() == QDialog::Accepted) { tryagain = true; continue; } else { emitFailed(tr("Received undetermined session status during login.")); return; } } // we own Minecraft, there is a profile, it's all ready to go! launchInstance(); return; } else { // play demo ? if (!m_session->demo) { m_session->demo = askPlayDemo(); } if (m_session->demo) { // play demo here launchInstance(); } else { emitFailed(tr("Launch cancelled - account does not own Minecraft.")); } } return; } case AccountState::Errored: // This means some sort of soft error that we can fix with a refresh ... so let's refresh. case AccountState::Unchecked: { m_accountToUse->refresh(); } /* fallthrough */ case AccountState::Working: { // refresh is in progress, we need to wait for it to finish to proceed. ProgressDialog progDialog(m_parentWidget); if (m_online) { progDialog.setSkipButton(true, tr("Play Offline")); } auto task = m_accountToUse->currentTask(); progDialog.execWithTask(task.get()); continue; } case AccountState::Expired: { if (reauthenticateCurrentAccount()) continue; return; } case AccountState::Disabled: { auto errorString = tr("The launcher's client identification has changed. Please remove this account and add it again."); QMessageBox::warning(m_parentWidget, tr("Client identification changed"), errorString, QMessageBox::StandardButton::Ok, QMessageBox::StandardButton::Ok); emitFailed(errorString); return; } case AccountState::Gone: { auto errorString = tr("The account no longer exists on the servers. It may have been migrated, in which case please add the new account " "you migrated this one to."); QMessageBox::warning(m_parentWidget, tr("Account gone"), errorString, QMessageBox::StandardButton::Ok, QMessageBox::StandardButton::Ok); emitFailed(errorString); return; } } } emitFailed(tr("Failed to launch.")); } bool LaunchController::reauthenticateCurrentAccount() { auto button = QMessageBox::warning(m_parentWidget, tr("Account refresh failed"), tr("The account has expired and needs to be reauthenticated. Do you want to reauthenticate this account?"), QMessageBox::StandardButton::Yes | QMessageBox::StandardButton::No, QMessageBox::StandardButton::Yes); if (button == QMessageBox::StandardButton::Yes) { auto accounts = APPLICATION->accounts(); bool isDefault = accounts->defaultAccount() == m_accountToUse; accounts->removeAccount(accounts->index(accounts->findAccountByProfileId(m_accountToUse->profileId()))); if (m_accountToUse->accountType() == AccountType::MSA) { auto newAccount = MSALoginDialog::newAccount(m_parentWidget); accounts->addAccount(newAccount); if (isDefault) { accounts->setDefaultAccount(newAccount); } m_accountToUse = nullptr; decideAccount(); return true; } emitFailed(tr("Account expired and re-login attempt failed")); } else { emitFailed(tr("The account has expired and needs to be reauthenticated")); } return false; } void LaunchController::launchInstance() { Q_ASSERT_X(m_instance != NULL, "launchInstance", "instance is NULL"); Q_ASSERT_X(m_session.get() != nullptr, "launchInstance", "session is NULL"); if (!m_instance->reloadSettings()) { QMessageBox::critical(m_parentWidget, tr("Error!"), tr("Couldn't load the instance profile.")); emitFailed(tr("Couldn't load the instance profile.")); return; } m_launcher = m_instance->createLaunchTask(m_session, m_targetToJoin); if (!m_launcher) { emitFailed(tr("Couldn't instantiate a launcher.")); return; } auto console = qobject_cast<InstanceWindow*>(m_parentWidget); auto showConsole = m_instance->settings()->get("ShowConsole").toBool(); if (!console && showConsole) { APPLICATION->showInstanceWindow(m_instance); } connect(m_launcher.get(), &LaunchTask::readyForLaunch, this, &LaunchController::readyForLaunch); connect(m_launcher.get(), &LaunchTask::succeeded, this, &LaunchController::onSucceeded); connect(m_launcher.get(), &LaunchTask::failed, this, &LaunchController::onFailed); connect(m_launcher.get(), &LaunchTask::requestProgress, this, &LaunchController::onProgressRequested); // Prepend Online and Auth Status QString online_mode; if (m_session->wants_online) { online_mode = "online"; // Prepend Server Status QStringList servers = { "login.microsoftonline.com", "session.minecraft.net", "textures.minecraft.net", "api.mojang.com" }; m_launcher->prependStep(makeShared<PrintServers>(m_launcher.get(), servers)); } else { online_mode = m_demo ? "demo" : "offline"; } m_launcher->prependStep( makeShared<TextPrint>(m_launcher.get(), "Launched instance in " + online_mode + " mode\n", MessageLevel::Launcher)); // Prepend Version { auto versionString = QString("%1 version: %2 (%3)") .arg(BuildConfig.LAUNCHER_DISPLAYNAME, BuildConfig.printableVersionString(), BuildConfig.BUILD_PLATFORM); m_launcher->prependStep(makeShared<TextPrint>(m_launcher.get(), versionString + "\n\n", MessageLevel::Launcher)); } m_launcher->start(); } void LaunchController::readyForLaunch() { if (!m_profiler) { m_launcher->proceed(); return; } QString error; if (!m_profiler->check(&error)) { m_launcher->abort(); emitFailed("Profiler startup failed!"); QMessageBox::critical(m_parentWidget, tr("Error!"), tr("Profiler check for %1 failed: %2").arg(m_profiler->name(), error)); return; } BaseProfiler* profilerInstance = m_profiler->createProfiler(m_launcher->instance(), this); connect(profilerInstance, &BaseProfiler::readyToLaunch, [this](const QString& message) { QMessageBox msg(m_parentWidget); msg.setText(tr("The game launch is delayed until you press the " "button. This is the right time to setup the profiler, as the " "profiler server is running now.\n\n%1") .arg(message)); msg.setWindowTitle(tr("Waiting.")); msg.setIcon(QMessageBox::Information); msg.addButton(tr("&Launch"), QMessageBox::AcceptRole); msg.exec(); m_launcher->proceed(); }); connect(profilerInstance, &BaseProfiler::abortLaunch, [this](const QString& message) { QMessageBox msg; msg.setText(tr("Couldn't start the profiler: %1").arg(message)); msg.setWindowTitle(tr("Error")); msg.setIcon(QMessageBox::Critical); msg.addButton(QMessageBox::Ok); msg.setModal(true); msg.exec(); m_launcher->abort(); emitFailed("Profiler startup failed!"); }); profilerInstance->beginProfiling(m_launcher); } void LaunchController::onSucceeded() { emitSucceeded(); } void LaunchController::onFailed(QString reason) { if (m_instance->settings()->get("ShowConsoleOnError").toBool()) { APPLICATION->showInstanceWindow(m_instance, "console"); } emitFailed(reason); } void LaunchController::onProgressRequested(Task* task) { ProgressDialog progDialog(m_parentWidget); progDialog.setSkipButton(true, tr("Abort")); m_launcher->proceed(); progDialog.execWithTask(task); } bool LaunchController::abort() { if (!m_launcher) { return true; } if (!m_launcher->canAbort()) { return false; } auto response = CustomMessageBox::selectable(m_parentWidget, 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) { return m_launcher->abort(); } return false; }
19,083
C++
.cpp
436
33.681193
140
0.603989
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
28,905
main.cpp
PrismLauncher_PrismLauncher/launcher/main.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 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 "Application.h" // #define BREAK_INFINITE_LOOP // #define BREAK_EXCEPTION // #define BREAK_RETURN #ifdef BREAK_INFINITE_LOOP #include <chrono> #include <thread> #endif int main(int argc, char* argv[]) { #ifdef BREAK_INFINITE_LOOP while (true) { std::this_thread::sleep_for(std::chrono::milliseconds(250)); } #endif #ifdef BREAK_EXCEPTION throw 42; #endif #ifdef BREAK_RETURN return 42; #endif #if QT_VERSION <= QT_VERSION_CHECK(6, 0, 0) QApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QGuiApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); #endif // initialize Qt Application app(argc, argv); switch (app.status()) { case Application::StartingUp: case Application::Initialized: { Q_INIT_RESOURCE(multimc); Q_INIT_RESOURCE(backgrounds); Q_INIT_RESOURCE(documents); Q_INIT_RESOURCE(prismlauncher); Q_INIT_RESOURCE(pe_dark); Q_INIT_RESOURCE(pe_light); Q_INIT_RESOURCE(pe_blue); Q_INIT_RESOURCE(pe_colored); Q_INIT_RESOURCE(breeze_dark); Q_INIT_RESOURCE(breeze_light); Q_INIT_RESOURCE(OSX); Q_INIT_RESOURCE(iOS); Q_INIT_RESOURCE(flat); Q_INIT_RESOURCE(flat_white); return app.exec(); } case Application::Failed: return 1; case Application::Succeeded: return 0; default: return -1; } }
3,014
C++
.cpp
88
29.25
80
0.674777
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
28,906
WindowsConsole.cpp
PrismLauncher_PrismLauncher/launcher/WindowsConsole.cpp
/* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Rachel Powers <508861+Ryex@users.noreply.github.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #include <fcntl.h> #include <io.h> #include <stdio.h> #include <windows.h> #include <iostream> void RedirectHandle(DWORD handle, FILE* stream, const char* mode) { HANDLE stdHandle = GetStdHandle(handle); if (stdHandle != INVALID_HANDLE_VALUE) { int fileDescriptor = _open_osfhandle((intptr_t)stdHandle, _O_TEXT); if (fileDescriptor != -1) { FILE* file = _fdopen(fileDescriptor, mode); if (file != NULL) { int dup2Result = _dup2(_fileno(file), _fileno(stream)); if (dup2Result == 0) { setvbuf(stream, NULL, _IONBF, 0); } } } } } // taken from https://stackoverflow.com/a/25927081 // getting a proper output to console with redirection support on windows is apparently hell void BindCrtHandlesToStdHandles(bool bindStdIn, bool bindStdOut, bool bindStdErr) { // Re-initialize the C runtime "FILE" handles with clean handles bound to "nul". We do this because it has been // observed that the file number of our standard handle file objects can be assigned internally to a value of -2 // when not bound to a valid target, which represents some kind of unknown internal invalid state. In this state our // call to "_dup2" fails, as it specifically tests to ensure that the target file number isn't equal to this value // before allowing the operation to continue. We can resolve this issue by first "re-opening" the target files to // use the "nul" device, which will place them into a valid state, after which we can redirect them to our target // using the "_dup2" function. if (bindStdIn) { FILE* dummyFile; freopen_s(&dummyFile, "nul", "r", stdin); } if (bindStdOut) { FILE* dummyFile; freopen_s(&dummyFile, "nul", "w", stdout); } if (bindStdErr) { FILE* dummyFile; freopen_s(&dummyFile, "nul", "w", stderr); } // Redirect unbuffered stdin from the current standard input handle if (bindStdIn) { RedirectHandle(STD_INPUT_HANDLE, stdin, "r"); } // Redirect unbuffered stdout to the current standard output handle if (bindStdOut) { RedirectHandle(STD_OUTPUT_HANDLE, stdout, "w"); } // Redirect unbuffered stderr to the current standard error handle if (bindStdErr) { RedirectHandle(STD_ERROR_HANDLE, stderr, "w"); } // Clear the error state for each of the C++ standard stream objects. We need to do this, as attempts to access the // standard streams before they refer to a valid target will cause the iostream objects to enter an error state. In // versions of Visual Studio after 2005, this seems to always occur during startup regardless of whether anything // has been read from or written to the targets or not. if (bindStdIn) { std::wcin.clear(); std::cin.clear(); } if (bindStdOut) { std::wcout.clear(); std::cout.clear(); } if (bindStdErr) { std::wcerr.clear(); std::cerr.clear(); } } bool AttachWindowsConsole() { auto stdinType = GetFileType(GetStdHandle(STD_INPUT_HANDLE)); auto stdoutType = GetFileType(GetStdHandle(STD_OUTPUT_HANDLE)); auto stderrType = GetFileType(GetStdHandle(STD_ERROR_HANDLE)); bool bindStdIn = false; bool bindStdOut = false; bool bindStdErr = false; if (stdinType == FILE_TYPE_CHAR || stdinType == FILE_TYPE_UNKNOWN) { bindStdIn = true; } if (stdoutType == FILE_TYPE_CHAR || stdoutType == FILE_TYPE_UNKNOWN) { bindStdOut = true; } if (stderrType == FILE_TYPE_CHAR || stderrType == FILE_TYPE_UNKNOWN) { bindStdErr = true; } if (AttachConsole(ATTACH_PARENT_PROCESS)) { BindCrtHandlesToStdHandles(bindStdIn, bindStdOut, bindStdErr); return true; } return false; }
4,679
C++
.cpp
116
34.887931
120
0.677873
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,907
DesktopServices.cpp
PrismLauncher_PrismLauncher/launcher/DesktopServices.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 dada513 <dada513@protonmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2022 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 "DesktopServices.h" #include <QDebug> #include <QDesktopServices> #include <QDir> #include <QProcess> #include "FileSystem.h" namespace DesktopServices { bool openPath(const QFileInfo& path, bool ensureFolderPathExists) { qDebug() << "Opening path" << path; if (ensureFolderPathExists) { FS::ensureFolderPathExists(path); } return openUrl(QUrl::fromLocalFile(QFileInfo(path).absoluteFilePath())); } bool openPath(const QString& path, bool ensureFolderPathExists) { return openPath(QFileInfo(path), ensureFolderPathExists); } bool run(const QString& application, const QStringList& args, const QString& workingDirectory, qint64* pid) { qDebug() << "Running" << application << "with args" << args.join(' '); return QProcess::startDetached(application, args, workingDirectory, pid); } bool openUrl(const QUrl& url) { qDebug() << "Opening URL" << url.toString(); return QDesktopServices::openUrl(url); } bool isFlatpak() { #ifdef Q_OS_LINUX return QFile::exists("/.flatpak-info"); #else return false; #endif } bool isSnap() { #ifdef Q_OS_LINUX return getenv("SNAP"); #else return false; #endif } } // namespace DesktopServices
2,689
C++
.cpp
80
31.375
107
0.734435
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,908
InstanceTask.cpp
PrismLauncher_PrismLauncher/launcher/InstanceTask.cpp
#include "InstanceTask.h" #include "Application.h" #include "settings/SettingsObject.h" #include "ui/dialogs/CustomMessageBox.h" #include <QPushButton> InstanceNameChange askForChangingInstanceName(QWidget* parent, const QString& old_name, const QString& new_name) { auto dialog = CustomMessageBox::selectable(parent, QObject::tr("Change instance name"), QObject::tr("The instance's name seems to include the old version. Would you like to update it?\n\n" "Old name: %1\n" "New name: %2") .arg(old_name, new_name), QMessageBox::Question, QMessageBox::No | QMessageBox::Yes); auto result = dialog->exec(); if (result == QMessageBox::Yes) return InstanceNameChange::ShouldChange; return InstanceNameChange::ShouldKeep; } ShouldUpdate askIfShouldUpdate(QWidget* parent, QString original_version_name) { if (APPLICATION->settings()->get("SkipModpackUpdatePrompt").toBool()) return ShouldUpdate::SkipUpdating; auto info = CustomMessageBox::selectable( parent, QObject::tr("Similar modpack was found!"), QObject::tr( "One or more of your instances are from this same modpack%1. Do you want to create a " "separate instance, or update the existing one?\n\nNOTE: Make sure you made a backup of your important instance data before " "updating, as worlds can be corrupted and some configuration may be lost (due to pack overrides).") .arg(original_version_name), QMessageBox::Information, QMessageBox::Cancel); QAbstractButton* update = info->addButton(QObject::tr("Update existing instance"), QMessageBox::AcceptRole); QAbstractButton* skip = info->addButton(QObject::tr("Create new instance"), QMessageBox::ResetRole); info->exec(); if (info->clickedButton() == update) return ShouldUpdate::Update; if (info->clickedButton() == skip) return ShouldUpdate::SkipUpdating; return ShouldUpdate::Cancel; } QString InstanceName::name() const { if (!m_modified_name.isEmpty()) return modifiedName(); if (!m_original_version.isEmpty()) return QString("%1 %2").arg(m_original_name, m_original_version); return m_original_name; } QString InstanceName::originalName() const { return m_original_name; } QString InstanceName::modifiedName() const { if (!m_modified_name.isEmpty()) return m_modified_name; return m_original_name; } QString InstanceName::version() const { return m_original_version; } void InstanceName::setName(InstanceName& other) { m_original_name = other.m_original_name; m_original_version = other.m_original_version; m_modified_name = other.m_modified_name; } InstanceTask::InstanceTask() : Task(), InstanceName() {}
2,968
C++
.cpp
69
35.463768
137
0.667476
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,909
SysInfo.cpp
PrismLauncher_PrismLauncher/launcher/SysInfo.cpp
#include <QDebug> #include <QString> #include "sys.h" #ifdef Q_OS_MACOS #include <sys/sysctl.h> #endif #include <QFile> #include <QMap> #include <QProcess> #include <QStandardPaths> #ifdef Q_OS_MACOS bool rosettaDetect() { int ret = 0; size_t size = sizeof(ret); if (sysctlbyname("sysctl.proc_translated", &ret, &size, NULL, 0) == -1) { return false; } return ret == 1; } #endif namespace SysInfo { QString currentSystem() { #if defined(Q_OS_LINUX) return "linux"; #elif defined(Q_OS_MACOS) return "osx"; #elif defined(Q_OS_WINDOWS) return "windows"; #elif defined(Q_OS_FREEBSD) return "freebsd"; #elif defined(Q_OS_OPENBSD) return "openbsd"; #else return "unknown"; #endif } QString useQTForArch() { #if defined(Q_OS_MACOS) && !defined(Q_PROCESSOR_ARM) if (rosettaDetect()) { return "arm64"; } else { return "x86_64"; } #endif return QSysInfo::currentCpuArchitecture(); } int suitableMaxMem() { float totalRAM = (float)Sys::getSystemRam() / (float)Sys::mebibyte; int maxMemoryAlloc; // If totalRAM < 6GB, use (totalRAM / 1.5), else 4GB if (totalRAM < (4096 * 1.5)) maxMemoryAlloc = (int)(totalRAM / 1.5); else maxMemoryAlloc = 4096; return maxMemoryAlloc; } QString getSupportedJavaArchitecture() { auto sys = currentSystem(); auto arch = useQTForArch(); if (sys == "windows") { if (arch == "x86_64") return "windows-x64"; if (arch == "i386") return "windows-x86"; // Unknown, maybe arm, appending arch return "windows-" + arch; } if (sys == "osx") { if (arch == "arm64") return "mac-os-arm64"; if (arch.contains("64")) return "mac-os-x64"; if (arch.contains("86")) return "mac-os-x86"; // Unknown, maybe something new, appending arch return "mac-os-" + arch; } else if (sys == "linux") { if (arch == "x86_64") return "linux-x64"; if (arch == "i386") return "linux-x86"; // will work for arm32 arm(64) return "linux-" + arch; } return {}; } } // namespace SysInfo
2,217
C++
.cpp
92
19.282609
77
0.598678
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,910
Commandline.cpp
PrismLauncher_PrismLauncher/launcher/Commandline.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Authors: Orochimarufan <orochimarufan.x3@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "Commandline.h" /** * @file libutil/src/cmdutils.cpp */ namespace Commandline { // commandline splitter QStringList splitArgs(QString args) { QStringList argv; QString current; bool escape = false; QChar inquotes; for (int i = 0; i < args.length(); i++) { QChar cchar = args.at(i); // \ escaped if (escape) { current += cchar; escape = false; // in "quotes" } else if (!inquotes.isNull()) { if (cchar == '\\') escape = true; else if (cchar == inquotes) inquotes = QChar::Null; else current += cchar; // otherwise } else { if (cchar == ' ') { if (!current.isEmpty()) { argv << current; current.clear(); } } else if (cchar == '"' || cchar == '\'') inquotes = cchar; else current += cchar; } } if (!current.isEmpty()) argv << current; return argv; } } // namespace Commandline
2,707
C++
.cpp
80
27.825
80
0.616323
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,911
MMCTime.cpp
PrismLauncher_PrismLauncher/launcher/MMCTime.cpp
/* * Copyright 2015 Petr Mrazek <peterix@gmail.com> * Copyright 2021 Jamie Mansfield <jmansfield@cadixdev.org> * * 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 <MMCTime.h> #include <qobject.h> #include <QDateTime> #include <QObject> #include <QTextStream> QString Time::prettifyDuration(int64_t duration, bool noDays) { int seconds = (int)(duration % 60); duration /= 60; int minutes = (int)(duration % 60); duration /= 60; int hours = (int)(noDays ? duration : (duration % 24)); int days = (int)(noDays ? 0 : (duration / 24)); if ((hours == 0) && (days == 0)) { return QObject::tr("%1min %2s").arg(minutes).arg(seconds); } if (days == 0) { return QObject::tr("%1h %2min").arg(hours).arg(minutes); } return QObject::tr("%1d %2h %3min").arg(days).arg(hours).arg(minutes); } QString Time::humanReadableDuration(double duration, int precision) { using days = std::chrono::duration<int, std::ratio<86400>>; QString outStr; QTextStream os(&outStr); bool neg = false; if (duration < 0) { neg = true; // flag duration *= -1; // invert } auto std_duration = std::chrono::duration<double>(duration); auto d = std::chrono::duration_cast<days>(std_duration); std_duration -= d; auto h = std::chrono::duration_cast<std::chrono::hours>(std_duration); std_duration -= h; auto m = std::chrono::duration_cast<std::chrono::minutes>(std_duration); std_duration -= m; auto s = std::chrono::duration_cast<std::chrono::seconds>(std_duration); std_duration -= s; auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(std_duration); auto dc = d.count(); auto hc = h.count(); auto mc = m.count(); auto sc = s.count(); auto msc = ms.count(); if (neg) { os << '-'; } if (dc) { os << dc << QObject::tr("days"); } if (hc) { if (dc) os << " "; os << qSetFieldWidth(2) << hc << QObject::tr("h"); // hours } if (mc) { if (dc || hc) os << " "; os << qSetFieldWidth(2) << mc << QObject::tr("m"); // minutes } if (dc || hc || mc || sc) { if (dc || hc || mc) os << " "; os << qSetFieldWidth(2) << sc << QObject::tr("s"); // seconds } if ((msc && (precision > 0)) || !(dc || hc || mc || sc)) { if (dc || hc || mc || sc) os << " "; os << qSetFieldWidth(0) << qSetRealNumberPrecision(precision) << msc << QObject::tr("ms"); // miliseconds } os.flush(); return outStr; }
3,130
C++
.cpp
91
29.340659
114
0.595906
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,912
FileSystem.cpp
PrismLauncher_PrismLauncher/launcher/FileSystem.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * Copyright (C) 2022 TheKodeToad <TheKodeToad@proton.me> * Copyright (C) 2022 Rachel Powers <508861+Ryex@users.noreply.github.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 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 "FileSystem.h" #include <QPair> #include "BuildConfig.h" #include <QDebug> #include <QDir> #include <QDirIterator> #include <QFile> #include <QFileInfo> #include <QStandardPaths> #include <QStorageInfo> #include <QTextStream> #include <QUrl> #include <QtNetwork> #include <system_error> #include "DesktopServices.h" #include "PSaveFile.h" #include "StringUtils.h" #if defined Q_OS_WIN32 #define NOMINMAX #define WIN32_LEAN_AND_MEAN #include <objbase.h> #include <objidl.h> #include <shlguid.h> #include <shlobj.h> #include <shobjidl.h> #include <sys/utime.h> #include <versionhelpers.h> #include <windows.h> #include <winnls.h> #include <string> // for ShellExecute #include <Shellapi.h> #include <objbase.h> #include <shlobj.h> #else #include <utime.h> #endif // Snippet from https://github.com/gulrak/filesystem#using-it-as-single-file-header #ifdef __APPLE__ #include <Availability.h> // for deployment target to support pre-catalina targets without std::fs #endif // __APPLE__ #if ((defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) || (defined(__cplusplus) && __cplusplus >= 201703L)) && defined(__has_include) #if __has_include(<filesystem>) && (!defined(__MAC_OS_X_VERSION_MIN_REQUIRED) || __MAC_OS_X_VERSION_MIN_REQUIRED >= 101500) #define GHC_USE_STD_FS #include <filesystem> namespace fs = std::filesystem; #endif // MacOS min version check #endif // Other OSes version check #ifndef GHC_USE_STD_FS #include <ghc/filesystem.hpp> namespace fs = ghc::filesystem; #endif // clone #if defined(Q_OS_LINUX) #include <errno.h> #include <fcntl.h> /* Definition of FICLONE* constants */ #include <linux/fs.h> #include <sys/ioctl.h> #include <unistd.h> #elif defined(Q_OS_MACOS) #include <sys/attr.h> #include <sys/clonefile.h> #elif defined(Q_OS_WIN) // winbtrfs clone vs rundll32 shellbtrfs.dll,ReflinkCopy #include <fileapi.h> #include <stdio.h> #include <tchar.h> #include <windows.h> // refs #include <winioctl.h> #if defined(__MINGW32__) #include <crtdbg.h> #endif #endif #if defined(Q_OS_WIN) #if defined(__MINGW32__) struct _DUPLICATE_EXTENTS_DATA { HANDLE FileHandle; LARGE_INTEGER SourceFileOffset; LARGE_INTEGER TargetFileOffset; LARGE_INTEGER ByteCount; }; using DUPLICATE_EXTENTS_DATA = _DUPLICATE_EXTENTS_DATA; using PDUPLICATE_EXTENTS_DATA = _DUPLICATE_EXTENTS_DATA*; struct _FSCTL_GET_INTEGRITY_INFORMATION_BUFFER { WORD ChecksumAlgorithm; // Checksum algorithm. e.g. CHECKSUM_TYPE_UNCHANGED, CHECKSUM_TYPE_NONE, CHECKSUM_TYPE_CRC32 WORD Reserved; // Must be 0 DWORD Flags; // FSCTL_INTEGRITY_FLAG_xxx DWORD ChecksumChunkSizeInBytes; DWORD ClusterSizeInBytes; }; using FSCTL_GET_INTEGRITY_INFORMATION_BUFFER = _FSCTL_GET_INTEGRITY_INFORMATION_BUFFER; using PFSCTL_GET_INTEGRITY_INFORMATION_BUFFER = _FSCTL_GET_INTEGRITY_INFORMATION_BUFFER*; struct _FSCTL_SET_INTEGRITY_INFORMATION_BUFFER { WORD ChecksumAlgorithm; // Checksum algorithm. e.g. CHECKSUM_TYPE_UNCHANGED, CHECKSUM_TYPE_NONE, CHECKSUM_TYPE_CRC32 WORD Reserved; // Must be 0 DWORD Flags; // FSCTL_INTEGRITY_FLAG_xxx }; using FSCTL_SET_INTEGRITY_INFORMATION_BUFFER = _FSCTL_SET_INTEGRITY_INFORMATION_BUFFER; using PFSCTL_SET_INTEGRITY_INFORMATION_BUFFER = _FSCTL_SET_INTEGRITY_INFORMATION_BUFFER*; #endif #ifndef FSCTL_DUPLICATE_EXTENTS_TO_FILE #define FSCTL_DUPLICATE_EXTENTS_TO_FILE CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 209, METHOD_BUFFERED, FILE_WRITE_DATA) #endif #ifndef FSCTL_GET_INTEGRITY_INFORMATION #define FSCTL_GET_INTEGRITY_INFORMATION \ CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 159, METHOD_BUFFERED, FILE_ANY_ACCESS) // FSCTL_GET_INTEGRITY_INFORMATION_BUFFER #endif #ifndef FSCTL_SET_INTEGRITY_INFORMATION #define FSCTL_SET_INTEGRITY_INFORMATION \ CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 160, METHOD_BUFFERED, FILE_READ_DATA | FILE_WRITE_DATA) // FSCTL_SET_INTEGRITY_INFORMATION_BUFFER #endif #ifndef ERROR_NOT_CAPABLE #define ERROR_NOT_CAPABLE 775L #endif #ifndef ERROR_BLOCK_TOO_MANY_REFERENCES #define ERROR_BLOCK_TOO_MANY_REFERENCES 347L #endif #endif namespace FS { void ensureExists(const QDir& dir) { if (!QDir().mkpath(dir.absolutePath())) { throw FileSystemException("Unable to create folder " + dir.dirName() + " (" + dir.absolutePath() + ")"); } } void write(const QString& filename, const QByteArray& data) { ensureExists(QFileInfo(filename).dir()); PSaveFile file(filename); if (!file.open(PSaveFile::WriteOnly)) { throw FileSystemException("Couldn't open " + filename + " for writing: " + file.errorString()); } if (data.size() != file.write(data)) { throw FileSystemException("Error writing data to " + filename + ": " + file.errorString()); } if (!file.commit()) { throw FileSystemException("Error while committing data to " + filename + ": " + file.errorString()); } } void appendSafe(const QString& filename, const QByteArray& data) { ensureExists(QFileInfo(filename).dir()); QByteArray buffer; try { buffer = read(filename); } catch (FileSystemException&) { buffer = QByteArray(); } buffer.append(data); PSaveFile file(filename); if (!file.open(PSaveFile::WriteOnly)) { throw FileSystemException("Couldn't open " + filename + " for writing: " + file.errorString()); } if (buffer.size() != file.write(buffer)) { throw FileSystemException("Error writing data to " + filename + ": " + file.errorString()); } if (!file.commit()) { throw FileSystemException("Error while committing data to " + filename + ": " + file.errorString()); } } void append(const QString& filename, const QByteArray& data) { ensureExists(QFileInfo(filename).dir()); QFile file(filename); if (!file.open(QFile::Append)) { throw FileSystemException("Couldn't open " + filename + " for writing: " + file.errorString()); } if (data.size() != file.write(data)) { throw FileSystemException("Error writing data to " + filename + ": " + file.errorString()); } } QByteArray read(const QString& filename) { QFile file(filename); if (!file.open(QFile::ReadOnly)) { throw FileSystemException("Unable to open " + filename + " for reading: " + file.errorString()); } const qint64 size = file.size(); QByteArray data(int(size), 0); const qint64 ret = file.read(data.data(), size); if (ret == -1 || ret != size) { throw FileSystemException("Error reading data from " + filename + ": " + file.errorString()); } return data; } bool updateTimestamp(const QString& filename) { #ifdef Q_OS_WIN32 std::wstring filename_utf_16 = filename.toStdWString(); return (_wutime64(filename_utf_16.c_str(), nullptr) == 0); #else QByteArray filenameBA = QFile::encodeName(filename); return (utime(filenameBA.data(), nullptr) == 0); #endif } bool ensureFilePathExists(QString filenamepath) { QFileInfo a(filenamepath); QDir dir; QString ensuredPath = a.path(); bool success = dir.mkpath(ensuredPath); return success; } bool ensureFolderPathExists(const QFileInfo folderPath) { QDir dir; QString ensuredPath = folderPath.filePath(); if (folderPath.exists()) return true; bool success = dir.mkpath(ensuredPath); return success; } bool ensureFolderPathExists(const QString folderPathName) { return ensureFolderPathExists(QFileInfo(folderPathName)); } bool copyFileAttributes(QString src, QString dst) { #ifdef Q_OS_WIN32 auto attrs = GetFileAttributesW(src.toStdWString().c_str()); if (attrs == INVALID_FILE_ATTRIBUTES) return false; return SetFileAttributesW(dst.toStdWString().c_str(), attrs); #endif return true; } // needs folders to exists void copyFolderAttributes(QString src, QString dst, QString relative) { auto path = PathCombine(src, relative); QDir dsrc(src); while ((path = QFileInfo(path).path()).length() >= src.length()) { auto dst_path = PathCombine(dst, dsrc.relativeFilePath(path)); copyFileAttributes(path, dst_path); } } /** * @brief Copies a directory and it's contents from src to dest * @param offset subdirectory form src to copy to dest * @return if there was an error during the filecopy */ bool copy::operator()(const QString& offset, bool dryRun) { using copy_opts = fs::copy_options; m_copied = 0; // reset counter m_failedPaths.clear(); // NOTE always deep copy on windows. the alternatives are too messy. #if defined Q_OS_WIN32 m_followSymlinks = true; #endif auto src = PathCombine(m_src.absolutePath(), offset); auto dst = PathCombine(m_dst.absolutePath(), offset); std::error_code err; fs::copy_options opt = copy_opts::none; // The default behavior is to follow symlinks if (!m_followSymlinks) opt |= copy_opts::copy_symlinks; if (m_overwrite) opt |= copy_opts::overwrite_existing; // Function that'll do the actual copying auto copy_file = [this, dryRun, src, dst, opt, &err](QString src_path, QString relative_dst_path) { if (m_matcher && (m_matcher->matches(relative_dst_path) != m_whitelist)) return; auto dst_path = PathCombine(dst, relative_dst_path); if (!dryRun) { ensureFilePathExists(dst_path); #ifdef Q_OS_WIN32 copyFolderAttributes(src, dst, relative_dst_path); #endif fs::copy(StringUtils::toStdString(src_path), StringUtils::toStdString(dst_path), opt, err); } if (err) { qWarning() << "Failed to copy files:" << QString::fromStdString(err.message()); qDebug() << "Source file:" << src_path; qDebug() << "Destination file:" << dst_path; m_failedPaths.append(dst_path); emit copyFailed(relative_dst_path); return; } m_copied++; emit fileCopied(relative_dst_path); }; // We can't use copy_opts::recursive because we need to take into account the // blacklisted paths, so we iterate over the source directory, and if there's no blacklist // match, we copy the file. QDir src_dir(src); QDirIterator source_it(src, QDir::Filter::Files | QDir::Filter::Hidden, QDirIterator::Subdirectories); while (source_it.hasNext()) { auto src_path = source_it.next(); auto relative_path = src_dir.relativeFilePath(src_path); copy_file(src_path, relative_path); } // If the root src is not a directory, the previous iterator won't run. if (!fs::is_directory(StringUtils::toStdString(src))) copy_file(src, ""); return err.value() == 0; } /// qDebug print support for the LinkPair struct QDebug operator<<(QDebug debug, const LinkPair& lp) { QDebugStateSaver saver(debug); debug.nospace() << "LinkPair{ src: " << lp.src << " , dst: " << lp.dst << " }"; return debug; } bool create_link::operator()(const QString& offset, bool dryRun) { m_linked = 0; // reset counter m_path_results.clear(); m_links_to_make.clear(); m_path_results.clear(); make_link_list(offset); if (!dryRun) return make_links(); return true; } /** * @brief Make a list of all the links to make * @param offset subdirectory of src to link to dest */ void create_link::make_link_list(const QString& offset) { for (auto pair : m_path_pairs) { const QString& srcPath = pair.src; const QString& dstPath = pair.dst; auto src = PathCombine(QDir(srcPath).absolutePath(), offset); auto dst = PathCombine(QDir(dstPath).absolutePath(), offset); // you can't hard link a directory so make sure if we deal with a directory we do so recursively if (m_useHardLinks) m_recursive = true; // Function that'll do the actual linking auto link_file = [this, dst](QString src_path, QString relative_dst_path) { if (m_matcher && (m_matcher->matches(relative_dst_path) != m_whitelist)) { qDebug() << "path" << relative_dst_path << "in black list or not in whitelist"; return; } auto dst_path = PathCombine(dst, relative_dst_path); LinkPair link = { src_path, dst_path }; m_links_to_make.append(link); }; if ((!m_recursive) || !fs::is_directory(StringUtils::toStdString(src))) { if (m_debug) qDebug() << "linking single file or dir:" << src << "to" << dst; link_file(src, ""); } else { if (m_debug) qDebug() << "linking recursively:" << src << "to" << dst << ", max_depth:" << m_max_depth; QDir src_dir(src); QDirIterator source_it(src, QDir::Filter::Files | QDir::Filter::Hidden, QDirIterator::Subdirectories); QStringList linkedPaths; while (source_it.hasNext()) { auto src_path = source_it.next(); auto relative_path = src_dir.relativeFilePath(src_path); if (m_max_depth >= 0 && pathDepth(relative_path) > m_max_depth) { relative_path = pathTruncate(relative_path, m_max_depth); src_path = src_dir.filePath(relative_path); if (linkedPaths.contains(src_path)) { continue; } } linkedPaths.append(src_path); link_file(src_path, relative_path); } } } } bool create_link::make_links() { for (auto link : m_links_to_make) { QString src_path = link.src; QString dst_path = link.dst; auto src_path_std = StringUtils::toStdString(link.src); auto dst_path_std = StringUtils::toStdString(link.dst); ensureFilePathExists(dst_path); if (m_useHardLinks) { if (m_debug) qDebug() << "making hard link:" << src_path << "to" << dst_path; fs::create_hard_link(src_path_std, dst_path_std, m_os_err); } else if (fs::is_directory(src_path_std)) { if (m_debug) qDebug() << "making directory_symlink:" << src_path << "to" << dst_path; fs::create_directory_symlink(src_path_std, dst_path_std, m_os_err); } else { if (m_debug) qDebug() << "making symlink:" << src_path << "to" << dst_path; fs::create_symlink(src_path_std, dst_path_std, m_os_err); } if (m_os_err) { qWarning() << "Failed to link files:" << QString::fromStdString(m_os_err.message()); qDebug() << "Source file:" << src_path; qDebug() << "Destination file:" << dst_path; qDebug() << "Error category:" << m_os_err.category().name(); qDebug() << "Error code:" << m_os_err.value(); emit linkFailed(src_path, dst_path, QString::fromStdString(m_os_err.message()), m_os_err.value()); } else { m_linked++; emit fileLinked(src_path, dst_path); } if (m_os_err) return false; } return true; } void create_link::runPrivileged(const QString& offset) { m_linked = 0; // reset counter m_path_results.clear(); m_links_to_make.clear(); bool gotResults = false; make_link_list(offset); QString serverName = BuildConfig.LAUNCHER_APP_BINARY_NAME + "_filelink_server" + StringUtils::getRandomAlphaNumeric(); connect(&m_linkServer, &QLocalServer::newConnection, this, [this, &gotResults]() { qDebug() << "Client connected, sending out pairs"; // construct block of data to send QByteArray block; QDataStream out(&block, QIODevice::WriteOnly); qint32 blocksize = quint32(sizeof(quint32)); for (auto link : m_links_to_make) { blocksize += quint32(link.src.size()); blocksize += quint32(link.dst.size()); } qDebug() << "About to write block of size:" << blocksize; out << blocksize; out << quint32(m_links_to_make.length()); for (auto link : m_links_to_make) { out << link.src; out << link.dst; } QLocalSocket* clientConnection = m_linkServer.nextPendingConnection(); connect(clientConnection, &QLocalSocket::disconnected, clientConnection, &QLocalSocket::deleteLater); connect(clientConnection, &QLocalSocket::readyRead, this, [&, clientConnection]() { QDataStream in; quint32 blockSize = 0; in.setDevice(clientConnection); qDebug() << "Reading path results from client"; qDebug() << "bytes available" << clientConnection->bytesAvailable(); // Relies on the fact that QDataStream serializes a quint32 into // sizeof(quint32) bytes if (clientConnection->bytesAvailable() < (int)sizeof(quint32)) return; qDebug() << "reading block size"; in >> blockSize; qDebug() << "blocksize is" << blockSize; qDebug() << "bytes available" << clientConnection->bytesAvailable(); if (clientConnection->bytesAvailable() < blockSize || in.atEnd()) return; quint32 numResults; in >> numResults; qDebug() << "numResults" << numResults; for (quint32 i = 0; i < numResults; i++) { FS::LinkResult result; in >> result.src; in >> result.dst; in >> result.err_msg; qint32 err_value; in >> err_value; result.err_value = err_value; if (result.err_value) { qDebug() << "privileged link fail" << result.src << "to" << result.dst << "code" << result.err_value << result.err_msg; emit linkFailed(result.src, result.dst, result.err_msg, result.err_value); } else { qDebug() << "privileged link success" << result.src << "to" << result.dst; m_linked++; emit fileLinked(result.src, result.dst); } m_path_results.append(result); } gotResults = true; qDebug() << "results received, closing connection"; clientConnection->close(); }); qint64 byteswritten = clientConnection->write(block); bool bytesflushed = clientConnection->flush(); qDebug() << "block flushed" << byteswritten << bytesflushed; }); qDebug() << "Listening on pipe" << serverName; if (!m_linkServer.listen(serverName)) { qDebug() << "Unable to start local pipe server on" << serverName << ":" << m_linkServer.errorString(); return; } ExternalLinkFileProcess* linkFileProcess = new ExternalLinkFileProcess(serverName, m_useHardLinks, this); connect(linkFileProcess, &ExternalLinkFileProcess::processExited, this, [this, gotResults]() { emit finishedPrivileged(gotResults); }); connect(linkFileProcess, &ExternalLinkFileProcess::finished, linkFileProcess, &QObject::deleteLater); linkFileProcess->start(); } void ExternalLinkFileProcess::runLinkFile() { QString fileLinkExe = PathCombine(QCoreApplication::instance()->applicationDirPath(), BuildConfig.LAUNCHER_APP_BINARY_NAME + "_filelink"); QString params = "-s " + m_server; params += " -H " + QVariant(m_useHardLinks).toString(); #if defined Q_OS_WIN32 SHELLEXECUTEINFO ShExecInfo; fileLinkExe = fileLinkExe + ".exe"; qDebug() << "Running: runas" << fileLinkExe << params; LPCWSTR programNameWin = (const wchar_t*)fileLinkExe.utf16(); LPCWSTR paramsWin = (const wchar_t*)params.utf16(); // https://learn.microsoft.com/en-us/windows/win32/api/shellapi/ns-shellapi-shellexecuteinfoa ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO); ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS; ShExecInfo.hwnd = NULL; // Optional. A handle to the owner window, used to display and position any UI that the system might produce // while executing this function. ShExecInfo.lpVerb = L"runas"; // elevate to admin, show UAC ShExecInfo.lpFile = programNameWin; ShExecInfo.lpParameters = paramsWin; ShExecInfo.lpDirectory = NULL; ShExecInfo.nShow = SW_HIDE; ShExecInfo.hInstApp = NULL; ShellExecuteEx(&ShExecInfo); WaitForSingleObject(ShExecInfo.hProcess, INFINITE); CloseHandle(ShExecInfo.hProcess); #endif qDebug() << "Process exited"; } bool moveByCopy(const QString& source, const QString& dest) { if (!copy(source, dest)()) { // copy qDebug() << "Copy of" << source << "to" << dest << "failed!"; return false; } if (!deletePath(source)) { // remove original qDebug() << "Deletion of" << source << "failed!"; return false; }; return true; } bool move(const QString& source, const QString& dest) { std::error_code err; ensureFilePathExists(dest); fs::rename(StringUtils::toStdString(source), StringUtils::toStdString(dest), err); if (err.value() != 0) { if (moveByCopy(source, dest)) return true; qDebug() << "Move of" << source << "to" << dest << "failed!"; qWarning() << "Failed to move file:" << QString::fromStdString(err.message()) << QString::number(err.value()); return false; } return true; } bool deletePath(QString path) { std::error_code err; fs::remove_all(StringUtils::toStdString(path), err); if (err) { qWarning() << "Failed to remove files:" << QString::fromStdString(err.message()); } return err.value() == 0; } bool trash(QString path, QString* pathInTrash) { #if QT_VERSION < QT_VERSION_CHECK(5, 15, 0) return false; #else // FIXME: Figure out trash in Flatpak. Qt seemingly doesn't use the Trash portal if (DesktopServices::isFlatpak()) return false; #if defined Q_OS_WIN32 if (IsWindowsServer()) return false; #endif return QFile::moveToTrash(path, pathInTrash); #endif } QString PathCombine(const QString& path1, const QString& path2) { if (!path1.size()) return path2; if (!path2.size()) return path1; return QDir::cleanPath(path1 + QDir::separator() + path2); } QString PathCombine(const QString& path1, const QString& path2, const QString& path3) { return PathCombine(PathCombine(path1, path2), path3); } QString PathCombine(const QString& path1, const QString& path2, const QString& path3, const QString& path4) { return PathCombine(PathCombine(path1, path2, path3), path4); } QString AbsolutePath(const QString& path) { return QFileInfo(path).absolutePath(); } int pathDepth(const QString& path) { if (path.isEmpty()) return 0; QFileInfo info(path); #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) auto parts = QDir::toNativeSeparators(info.path()).split(QDir::separator(), QString::SkipEmptyParts); #else auto parts = QDir::toNativeSeparators(info.path()).split(QDir::separator(), Qt::SkipEmptyParts); #endif int numParts = parts.length(); numParts -= parts.count("."); numParts -= parts.count("..") * 2; return numParts; } QString pathTruncate(const QString& path, int depth) { if (path.isEmpty() || (depth < 0)) return ""; QString trunc = QFileInfo(path).path(); if (pathDepth(trunc) > depth) { return pathTruncate(trunc, depth); } #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) auto parts = QDir::toNativeSeparators(trunc).split(QDir::separator(), QString::SkipEmptyParts); #else auto parts = QDir::toNativeSeparators(trunc).split(QDir::separator(), Qt::SkipEmptyParts); #endif if (parts.startsWith(".") && !path.startsWith(".")) { parts.removeFirst(); } if (QDir::toNativeSeparators(path).startsWith(QDir::separator())) { parts.prepend(""); } trunc = parts.join(QDir::separator()); return trunc; } QString ResolveExecutable(QString path) { if (path.isEmpty()) { return QString(); } if (!path.contains('/')) { path = QStandardPaths::findExecutable(path); } QFileInfo pathInfo(path); if (!pathInfo.exists() || !pathInfo.isExecutable()) { return QString(); } return pathInfo.absoluteFilePath(); } /** * Normalize path * * Any paths inside the current folder will be normalized to relative paths (to current) * Other paths will be made absolute */ QString NormalizePath(QString path) { QDir a = QDir::currentPath(); QString currentAbsolute = a.absolutePath(); QDir b(path); QString newAbsolute = b.absolutePath(); if (newAbsolute.startsWith(currentAbsolute)) { return a.relativeFilePath(newAbsolute); } else { return newAbsolute; } } static const QString BAD_WIN_CHARS = "<>:\"|?*\r\n"; static const QString BAD_NTFS_CHARS = "<>:\"|?*"; static const QString BAD_HFS_CHARS = ":"; static const QString BAD_FILENAME_CHARS = BAD_WIN_CHARS + "\\/"; QString RemoveInvalidFilenameChars(QString string, QChar replaceWith) { for (int i = 0; i < string.length(); i++) if (string.at(i) < ' ' || BAD_FILENAME_CHARS.contains(string.at(i))) string[i] = replaceWith; return string; } QString RemoveInvalidPathChars(QString path, QChar replaceWith) { QString invalidChars; #ifdef Q_OS_WIN invalidChars = BAD_WIN_CHARS; #endif // the null character is ignored in this check as it was not a problem until now switch (statFS(path).fsType) { case FilesystemType::FAT: // similar to NTFS /* fallthrough */ case FilesystemType::NTFS: /* fallthrough */ case FilesystemType::REFS: // similar to NTFS(should be available only on windows) invalidChars += BAD_NTFS_CHARS; break; // case FilesystemType::EXT: // case FilesystemType::EXT_2_OLD: // case FilesystemType::EXT_2_3_4: // case FilesystemType::XFS: // case FilesystemType::BTRFS: // case FilesystemType::NFS: // case FilesystemType::ZFS: case FilesystemType::APFS: /* fallthrough */ case FilesystemType::HFS: /* fallthrough */ case FilesystemType::HFSPLUS: /* fallthrough */ case FilesystemType::HFSX: invalidChars += BAD_HFS_CHARS; break; // case FilesystemType::FUSEBLK: // case FilesystemType::F2FS: // case FilesystemType::UNKNOWN: default: break; } if (invalidChars.size() != 0) { for (int i = 0; i < path.length(); i++) { if (path.at(i) < ' ' || invalidChars.contains(path.at(i))) { path[i] = replaceWith; } } } return path; } QString DirNameFromString(QString string, QString inDir) { int num = 0; QString baseName = RemoveInvalidFilenameChars(string, '-'); QString dirName; do { if (num == 0) { dirName = baseName; } else { dirName = baseName + "(" + QString::number(num) + ")"; } // If it's over 9000 if (num > 9000) return ""; num++; } while (QFileInfo(PathCombine(inDir, dirName)).exists()); return dirName; } // Does the folder path contain any '!'? If yes, return true, otherwise false. // (This is a problem for Java) bool checkProblemticPathJava(QDir folder) { QString pathfoldername = folder.absolutePath(); return pathfoldername.contains("!", Qt::CaseInsensitive); } QString getDesktopDir() { return QStandardPaths::writableLocation(QStandardPaths::DesktopLocation); } // Cross-platform Shortcut creation bool createShortcut(QString destination, QString target, QStringList args, QString name, QString icon) { if (destination.isEmpty()) { destination = PathCombine(getDesktopDir(), RemoveInvalidFilenameChars(name)); } if (!ensureFilePathExists(destination)) { qWarning() << "Destination path can't be created!"; return false; } #if defined(Q_OS_MACOS) // Create the Application QDir applicationDirectory = QStandardPaths::writableLocation(QStandardPaths::ApplicationsLocation) + "/" + BuildConfig.LAUNCHER_NAME + " Instances/"; if (!applicationDirectory.mkpath(".")) { qWarning() << "Couldn't create application directory"; return false; } QDir application = applicationDirectory.path() + "/" + name + ".app/"; if (application.exists()) { qWarning() << "Application already exists!"; return false; } if (!application.mkpath(".")) { qWarning() << "Couldn't create application"; return false; } QDir content = application.path() + "/Contents/"; QDir resources = content.path() + "/Resources/"; QDir binaryDir = content.path() + "/MacOS/"; QFile info = content.path() + "/Info.plist"; if (!(content.mkpath(".") && resources.mkpath(".") && binaryDir.mkpath("."))) { qWarning() << "Couldn't create directories within application"; return false; } info.open(QIODevice::WriteOnly | QIODevice::Text); QFile(icon).rename(resources.path() + "/Icon.icns"); // Create the Command file QString exec = binaryDir.path() + "/Run.command"; QFile f(exec); f.open(QIODevice::WriteOnly | QIODevice::Text); QTextStream stream(&f); QString argstring; if (!args.empty()) argstring = " \"" + args.join("\" \"") + "\""; stream << "#!/bin/bash" << "\n"; stream << "\"" << target << "\" " << argstring << "\n"; stream.flush(); f.close(); f.setPermissions(f.permissions() | QFileDevice::ExeOwner | QFileDevice::ExeGroup | QFileDevice::ExeOther); // Generate the Info.plist QTextStream infoStream(&info); infoStream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?> \n" "<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" " "\"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">" "<plist version=\"1.0\">\n" "<dict>\n" " <key>CFBundleExecutable</key>\n" " <string>Run.command</string>\n" // The path to the executable " <key>CFBundleIconFile</key>\n" " <string>Icon.icns</string>\n" " <key>CFBundleName</key>\n" " <string>" << name << "</string>\n" // Name of the application " <key>CFBundlePackageType</key>\n" " <string>APPL</string>\n" " <key>CFBundleShortVersionString</key>\n" " <string>1.0</string>\n" " <key>CFBundleVersion</key>\n" " <string>1.0</string>\n" "</dict>\n" "</plist>"; return true; #elif defined(Q_OS_LINUX) || defined(Q_OS_FREEBSD) || defined(Q_OS_OPENBSD) if (!destination.endsWith(".desktop")) // in case of isFlatpak destination is already populated destination += ".desktop"; QFile f(destination); 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 << "Categories=Game;ActionGame;AdventureGame;Simulation" << "\n"; stream << "Exec=\"" << target.toLocal8Bit() << "\"" << argstring.toLocal8Bit() << "\n"; stream << "Name=" << name.toLocal8Bit() << "\n"; if (!icon.isEmpty()) { stream << "Icon=" << icon.toLocal8Bit() << "\n"; } stream.flush(); f.close(); f.setPermissions(f.permissions() | QFileDevice::ExeOwner | QFileDevice::ExeGroup | QFileDevice::ExeOther); return true; #elif defined(Q_OS_WIN) QFileInfo targetInfo(target); if (!targetInfo.exists()) { qWarning() << "Target file does not exist!"; return false; } target = targetInfo.absoluteFilePath(); if (target.length() >= MAX_PATH) { qWarning() << "Target file path is too long!"; return false; } if (!icon.isEmpty() && icon.length() >= MAX_PATH) { qWarning() << "Icon path is too long!"; return false; } destination += ".lnk"; if (destination.length() >= MAX_PATH) { qWarning() << "Destination path is too long!"; return false; } QString argStr; int argCount = args.count(); for (int i = 0; i < argCount; i++) { if (args[i].contains(' ')) { argStr.append('"').append(args[i]).append('"'); } else { argStr.append(args[i]); } if (i < argCount - 1) { argStr.append(" "); } } if (argStr.length() >= MAX_PATH) { qWarning() << "Arguments string is too long!"; return false; } HRESULT hres; // ...yes, you need to initialize the entire COM stack just to make a shortcut hres = CoInitialize(nullptr); if (FAILED(hres)) { qWarning() << "Failed to initialize COM!"; return false; } WCHAR wsz[MAX_PATH]; IShellLink* psl; // create an IShellLink instance - this stores the shortcut's attributes hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (LPVOID*)&psl); if (SUCCEEDED(hres)) { wmemset(wsz, 0, MAX_PATH); target.toWCharArray(wsz); psl->SetPath(wsz); wmemset(wsz, 0, MAX_PATH); argStr.toWCharArray(wsz); psl->SetArguments(wsz); wmemset(wsz, 0, MAX_PATH); targetInfo.absolutePath().toWCharArray(wsz); psl->SetWorkingDirectory(wsz); // "Starts in" attribute if (!icon.isEmpty()) { wmemset(wsz, 0, MAX_PATH); icon.toWCharArray(wsz); psl->SetIconLocation(wsz, 0); } // query an IPersistFile interface from our IShellLink instance // this is the interface that will actually let us save the shortcut to disk! IPersistFile* ppf; hres = psl->QueryInterface(IID_IPersistFile, (LPVOID*)&ppf); if (SUCCEEDED(hres)) { wmemset(wsz, 0, MAX_PATH); destination.toWCharArray(wsz); hres = ppf->Save(wsz, TRUE); if (FAILED(hres)) { qWarning() << "IPresistFile->Save() failed"; qWarning() << "hres = " << hres; } ppf->Release(); } else { qWarning() << "Failed to query IPersistFile interface from IShellLink instance"; qWarning() << "hres = " << hres; } psl->Release(); } else { qWarning() << "Failed to create IShellLink instance"; qWarning() << "hres = " << hres; } // go away COM, nobody likes you CoUninitialize(); return SUCCEEDED(hres); #else qWarning("Desktop Shortcuts not supported on your platform!"); return false; #endif } bool overrideFolder(QString overwritten_path, QString override_path) { using copy_opts = fs::copy_options; if (!FS::ensureFolderPathExists(overwritten_path)) return false; std::error_code err; fs::copy_options opt = copy_opts::recursive | copy_opts::overwrite_existing; // FIXME: hello traveller! Apparently std::copy does NOT overwrite existing files on GNU libstdc++ on Windows? fs::copy(StringUtils::toStdString(override_path), StringUtils::toStdString(overwritten_path), opt, err); if (err) { qCritical() << QString("Failed to apply override from %1 to %2").arg(override_path, overwritten_path); qCritical() << "Reason:" << QString::fromStdString(err.message()); } return err.value() == 0; } QString getFilesystemTypeName(FilesystemType type) { auto iter = s_filesystem_type_names.constFind(type); if (iter != s_filesystem_type_names.constEnd()) { return iter.value().constFirst(); } return getFilesystemTypeName(FilesystemType::UNKNOWN); } FilesystemType getFilesystemTypeFuzzy(const QString& name) { for (auto iter = s_filesystem_type_names.constBegin(); iter != s_filesystem_type_names.constEnd(); ++iter) { auto fs_names = iter.value(); for (auto fs_name : fs_names) { if (name.toUpper().contains(fs_name.toUpper())) return iter.key(); } } return FilesystemType::UNKNOWN; } FilesystemType getFilesystemType(const QString& name) { for (auto iter = s_filesystem_type_names.constBegin(); iter != s_filesystem_type_names.constEnd(); ++iter) { auto fs_names = iter.value(); if (fs_names.contains(name.toUpper())) return iter.key(); } return FilesystemType::UNKNOWN; } /** * @brief path to the near ancestor that exists * */ QString nearestExistentAncestor(const QString& path) { if (QFileInfo::exists(path)) return path; QDir dir(path); if (!dir.makeAbsolute()) return {}; do { dir.setPath(QDir::cleanPath(dir.filePath(QStringLiteral("..")))); } while (!dir.exists() && !dir.isRoot()); return dir.exists() ? dir.path() : QString(); } /** * @brief colect information about the filesystem under a file * */ FilesystemInfo statFS(const QString& path) { FilesystemInfo info; QStorageInfo storage_info(nearestExistentAncestor(path)); info.fsTypeName = storage_info.fileSystemType(); info.fsType = getFilesystemTypeFuzzy(info.fsTypeName); info.blockSize = storage_info.blockSize(); info.bytesAvailable = storage_info.bytesAvailable(); info.bytesFree = storage_info.bytesFree(); info.bytesTotal = storage_info.bytesTotal(); info.name = storage_info.name(); info.rootPath = storage_info.rootPath(); return info; } /** * @brief if the Filesystem is reflink/clone capable * */ bool canCloneOnFS(const QString& path) { FilesystemInfo info = statFS(path); return canCloneOnFS(info); } bool canCloneOnFS(const FilesystemInfo& info) { return canCloneOnFS(info.fsType); } bool canCloneOnFS(FilesystemType type) { return s_clone_filesystems.contains(type); } /** * @brief if the Filesystem is reflink/clone capable and both paths are on the same device * */ bool canClone(const QString& src, const QString& dst) { auto srcVInfo = statFS(src); auto dstVInfo = statFS(dst); bool sameDevice = srcVInfo.rootPath == dstVInfo.rootPath; return sameDevice && canCloneOnFS(srcVInfo) && canCloneOnFS(dstVInfo); } /** * @brief reflink/clones a directory and it's contents from src to dest * @param offset subdirectory form src to copy to dest * @return if there was an error during the filecopy */ bool clone::operator()(const QString& offset, bool dryRun) { if (!canClone(m_src.absolutePath(), m_dst.absolutePath())) { qWarning() << "Can not clone: not same device or not clone/reflink filesystem"; qDebug() << "Source path:" << m_src.absolutePath(); qDebug() << "Destination path:" << m_dst.absolutePath(); emit cloneFailed(m_src.absolutePath(), m_dst.absolutePath()); return false; } m_cloned = 0; // reset counter m_failedClones.clear(); auto src = PathCombine(m_src.absolutePath(), offset); auto dst = PathCombine(m_dst.absolutePath(), offset); std::error_code err; // Function that'll do the actual cloneing auto cloneFile = [this, dryRun, dst, &err](QString src_path, QString relative_dst_path) { if (m_matcher && (m_matcher->matches(relative_dst_path) != m_whitelist)) return; auto dst_path = PathCombine(dst, relative_dst_path); if (!dryRun) { ensureFilePathExists(dst_path); clone_file(src_path, dst_path, err); } if (err) { qDebug() << "Failed to clone files: error" << err.value() << "message" << QString::fromStdString(err.message()); qDebug() << "Source file:" << src_path; qDebug() << "Destination file:" << dst_path; m_failedClones.append(qMakePair(src_path, dst_path)); emit cloneFailed(src_path, dst_path); return; } m_cloned++; emit fileCloned(src_path, dst_path); }; // We can't use copy_opts::recursive because we need to take into account the // blacklisted paths, so we iterate over the source directory, and if there's no blacklist // match, we copy the file. QDir src_dir(src); QDirIterator source_it(src, QDir::Filter::Files | QDir::Filter::Hidden, QDirIterator::Subdirectories); while (source_it.hasNext()) { auto src_path = source_it.next(); auto relative_path = src_dir.relativeFilePath(src_path); cloneFile(src_path, relative_path); } // If the root src is not a directory, the previous iterator won't run. if (!fs::is_directory(StringUtils::toStdString(src))) cloneFile(src, ""); return err.value() == 0; } /** * @brief clone/reflink file from src to dst * */ bool clone_file(const QString& src, const QString& dst, std::error_code& ec) { auto src_path = StringUtils::toStdString(QDir::toNativeSeparators(QFileInfo(src).absoluteFilePath())); auto dst_path = StringUtils::toStdString(QDir::toNativeSeparators(QFileInfo(dst).absoluteFilePath())); FilesystemInfo srcinfo = statFS(src); FilesystemInfo dstinfo = statFS(dst); if ((srcinfo.rootPath != dstinfo.rootPath) || (srcinfo.fsType != dstinfo.fsType)) { ec = std::make_error_code(std::errc::not_supported); qWarning() << "reflink/clone must be to the same device and filesystem! src and dst root filesystems do not match."; return false; } #if defined(Q_OS_WIN) if (!win_ioctl_clone(src_path, dst_path, ec)) { qDebug() << "failed win_ioctl_clone"; qWarning() << "clone/reflink not supported on windows outside of btrfs or ReFS!"; qWarning() << "check out https://github.com/maharmstone/btrfs for btrfs support!"; return false; } #elif defined(Q_OS_LINUX) if (!linux_ficlone(src_path, dst_path, ec)) { qDebug() << "failed linux_ficlone:"; return false; } #elif defined(Q_OS_MACOS) if (!macos_bsd_clonefile(src_path, dst_path, ec)) { qDebug() << "failed macos_bsd_clonefile:"; return false; } #else qWarning() << "clone/reflink not supported! unknown OS"; ec = std::make_error_code(std::errc::not_supported); return false; #endif return true; } #if defined(Q_OS_WIN) static long RoundUpToPowerOf2(long originalValue, long roundingMultiplePowerOf2) { long mask = roundingMultiplePowerOf2 - 1; return (originalValue + mask) & ~mask; } bool win_ioctl_clone(const std::wstring& src_path, const std::wstring& dst_path, std::error_code& ec) { /** * This algorithm inspired from https://github.com/0xbadfca11/reflink * LICENSE MIT * * Additional references * https://learn.microsoft.com/en-us/windows/win32/api/winioctl/ni-winioctl-fsctl_duplicate_extents_to_file * https://github.com/microsoft/CopyOnWrite/blob/main/lib/Windows/WindowsCopyOnWriteFilesystem.cs#L94 */ HANDLE hSourceFile = CreateFileW(src_path.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr); if (hSourceFile == INVALID_HANDLE_VALUE) { ec = std::error_code(GetLastError(), std::system_category()); qDebug() << "Failed to open source file" << src_path.c_str(); return false; } ULONG fs_flags; if (!GetVolumeInformationByHandleW(hSourceFile, nullptr, 0, nullptr, nullptr, &fs_flags, nullptr, 0)) { ec = std::error_code(GetLastError(), std::system_category()); qDebug() << "Failed to get Filesystem information for " << src_path.c_str(); CloseHandle(hSourceFile); return false; } if (!(fs_flags & FILE_SUPPORTS_BLOCK_REFCOUNTING)) { SetLastError(ERROR_NOT_CAPABLE); ec = std::error_code(GetLastError(), std::system_category()); qWarning() << "Filesystem at " << src_path.c_str() << " does not support reflink"; CloseHandle(hSourceFile); return false; } FILE_END_OF_FILE_INFO sourceFileLength; if (!GetFileSizeEx(hSourceFile, &sourceFileLength.EndOfFile)) { ec = std::error_code(GetLastError(), std::system_category()); qDebug() << "Failed to size of source file" << src_path.c_str(); CloseHandle(hSourceFile); return false; } FILE_BASIC_INFO sourceFileBasicInfo; if (!GetFileInformationByHandleEx(hSourceFile, FileBasicInfo, &sourceFileBasicInfo, sizeof(sourceFileBasicInfo))) { ec = std::error_code(GetLastError(), std::system_category()); qDebug() << "Failed to source file info" << src_path.c_str(); CloseHandle(hSourceFile); return false; } ULONG junk; FSCTL_GET_INTEGRITY_INFORMATION_BUFFER sourceFileIntegrity; if (!DeviceIoControl(hSourceFile, FSCTL_GET_INTEGRITY_INFORMATION, nullptr, 0, &sourceFileIntegrity, sizeof(sourceFileIntegrity), &junk, nullptr)) { ec = std::error_code(GetLastError(), std::system_category()); qDebug() << "Failed to source file integrity info" << src_path.c_str(); CloseHandle(hSourceFile); return false; } HANDLE hDestFile = CreateFileW(dst_path.c_str(), GENERIC_READ | GENERIC_WRITE | DELETE, 0, nullptr, CREATE_NEW, 0, hSourceFile); if (hDestFile == INVALID_HANDLE_VALUE) { ec = std::error_code(GetLastError(), std::system_category()); qDebug() << "Failed to open dest file" << dst_path.c_str(); CloseHandle(hSourceFile); return false; } FILE_DISPOSITION_INFO destFileDispose = { TRUE }; if (!SetFileInformationByHandle(hDestFile, FileDispositionInfo, &destFileDispose, sizeof(destFileDispose))) { ec = std::error_code(GetLastError(), std::system_category()); qDebug() << "Failed to set dest file info" << dst_path.c_str(); CloseHandle(hSourceFile); CloseHandle(hDestFile); return false; } if (!DeviceIoControl(hDestFile, FSCTL_SET_SPARSE, nullptr, 0, nullptr, 0, &junk, nullptr)) { ec = std::error_code(GetLastError(), std::system_category()); qDebug() << "Failed to set dest sparseness" << dst_path.c_str(); CloseHandle(hSourceFile); CloseHandle(hDestFile); return false; } FSCTL_SET_INTEGRITY_INFORMATION_BUFFER setDestFileintegrity = { sourceFileIntegrity.ChecksumAlgorithm, sourceFileIntegrity.Reserved, sourceFileIntegrity.Flags }; if (!DeviceIoControl(hDestFile, FSCTL_SET_INTEGRITY_INFORMATION, &setDestFileintegrity, sizeof(setDestFileintegrity), nullptr, 0, nullptr, nullptr)) { ec = std::error_code(GetLastError(), std::system_category()); qDebug() << "Failed to set dest file integrity info" << dst_path.c_str(); CloseHandle(hSourceFile); CloseHandle(hDestFile); return false; } if (!SetFileInformationByHandle(hDestFile, FileEndOfFileInfo, &sourceFileLength, sizeof(sourceFileLength))) { ec = std::error_code(GetLastError(), std::system_category()); qDebug() << "Failed to set dest file size" << dst_path.c_str(); CloseHandle(hSourceFile); CloseHandle(hDestFile); return false; } const LONG64 splitThreshold = (1LL << 32) - sourceFileIntegrity.ClusterSizeInBytes; DUPLICATE_EXTENTS_DATA dupExtent; dupExtent.FileHandle = hSourceFile; for (LONG64 offset = 0, remain = RoundUpToPowerOf2(sourceFileLength.EndOfFile.QuadPart, sourceFileIntegrity.ClusterSizeInBytes); remain > 0; offset += splitThreshold, remain -= splitThreshold) { dupExtent.SourceFileOffset.QuadPart = dupExtent.TargetFileOffset.QuadPart = offset; dupExtent.ByteCount.QuadPart = std::min(splitThreshold, remain); if (!DeviceIoControl(hDestFile, FSCTL_DUPLICATE_EXTENTS_TO_FILE, &dupExtent, sizeof(dupExtent), nullptr, 0, &junk, nullptr)) { DWORD err = GetLastError(); QString additionalMessage; if (err == ERROR_BLOCK_TOO_MANY_REFERENCES) { static const int MaxClonesPerFile = 8175; additionalMessage = QString( " This is ERROR_BLOCK_TOO_MANY_REFERENCES and may mean you have surpassed the maximum " "allowed %1 references for a single file. " "See " "https://docs.microsoft.com/en-us/windows-server/storage/refs/block-cloning#functionality-restrictions-and-remarks") .arg(MaxClonesPerFile); } ec = std::error_code(err, std::system_category()); qDebug() << "Failed copy-on-write cloning of" << src_path.c_str() << "to" << dst_path.c_str() << "with error" << err << additionalMessage; CloseHandle(hSourceFile); CloseHandle(hDestFile); return false; } } if (!(sourceFileBasicInfo.FileAttributes & FILE_ATTRIBUTE_SPARSE_FILE)) { FILE_SET_SPARSE_BUFFER setDestSparse = { FALSE }; if (!DeviceIoControl(hDestFile, FSCTL_SET_SPARSE, &setDestSparse, sizeof(setDestSparse), nullptr, 0, &junk, nullptr)) { qDebug() << "Failed to set dest file sparseness" << dst_path.c_str(); CloseHandle(hSourceFile); CloseHandle(hDestFile); return false; } } sourceFileBasicInfo.CreationTime.QuadPart = 0; if (!SetFileInformationByHandle(hDestFile, FileBasicInfo, &sourceFileBasicInfo, sizeof(sourceFileBasicInfo))) { qDebug() << "Failed to set dest file creation time" << dst_path.c_str(); CloseHandle(hSourceFile); CloseHandle(hDestFile); return false; } if (!FlushFileBuffers(hDestFile)) { qDebug() << "Failed to flush dest file buffer" << dst_path.c_str(); CloseHandle(hSourceFile); CloseHandle(hDestFile); return false; } destFileDispose = { FALSE }; bool result = !!SetFileInformationByHandle(hDestFile, FileDispositionInfo, &destFileDispose, sizeof(destFileDispose)); CloseHandle(hSourceFile); CloseHandle(hDestFile); return result; } #elif defined(Q_OS_LINUX) bool linux_ficlone(const std::string& src_path, const std::string& dst_path, std::error_code& ec) { // https://man7.org/linux/man-pages/man2/ioctl_ficlone.2.html int src_fd = open(src_path.c_str(), O_RDONLY); if (src_fd == -1) { qDebug() << "Failed to open file:" << src_path.c_str(); qDebug() << "Error:" << strerror(errno); ec = std::make_error_code(static_cast<std::errc>(errno)); return false; } int dst_fd = open(dst_path.c_str(), O_CREAT | O_WRONLY | O_TRUNC, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); if (dst_fd == -1) { qDebug() << "Failed to open file:" << dst_path.c_str(); qDebug() << "Error:" << strerror(errno); ec = std::make_error_code(static_cast<std::errc>(errno)); close(src_fd); return false; } // attempt to clone if (ioctl(dst_fd, FICLONE, src_fd) == -1) { qDebug() << "Failed to clone file:" << src_path.c_str() << "to" << dst_path.c_str(); qDebug() << "Error:" << strerror(errno); ec = std::make_error_code(static_cast<std::errc>(errno)); close(src_fd); close(dst_fd); return false; } if (close(src_fd)) { qDebug() << "Failed to close file:" << src_path.c_str(); qDebug() << "Error:" << strerror(errno); } if (close(dst_fd)) { qDebug() << "Failed to close file:" << dst_path.c_str(); qDebug() << "Error:" << strerror(errno); } return true; } #elif defined(Q_OS_MACOS) bool macos_bsd_clonefile(const std::string& src_path, const std::string& dst_path, std::error_code& ec) { // clonefile(const char * src, const char * dst, int flags); // https://www.manpagez.com/man/2/clonefile/ qDebug() << "attempting file clone via clonefile" << src_path.c_str() << "to" << dst_path.c_str(); if (clonefile(src_path.c_str(), dst_path.c_str(), 0) == -1) { qDebug() << "Failed to clone file:" << src_path.c_str() << "to" << dst_path.c_str(); qDebug() << "Error:" << strerror(errno); ec = std::make_error_code(static_cast<std::errc>(errno)); return false; } return true; } #endif /** * @brief if the Filesystem is symlink capable * */ bool canLinkOnFS(const QString& path) { FilesystemInfo info = statFS(path); return canLinkOnFS(info); } bool canLinkOnFS(const FilesystemInfo& info) { return canLinkOnFS(info.fsType); } bool canLinkOnFS(FilesystemType type) { return !s_non_link_filesystems.contains(type); } /** * @brief if the Filesystem is symlink capable on both ends * */ bool canLink(const QString& src, const QString& dst) { return canLinkOnFS(src) && canLinkOnFS(dst); } uintmax_t hardLinkCount(const QString& path) { std::error_code err; int count = fs::hard_link_count(StringUtils::toStdString(path), err); if (err) { qWarning() << "Failed to count hard links for" << path << ":" << QString::fromStdString(err.message()); count = 0; } return count; } #ifdef Q_OS_WIN // returns 8.3 file format from long path QString shortPathName(const QString& file) { auto input = file.toStdWString(); std::wstring output; long length = GetShortPathNameW(input.c_str(), NULL, 0); if (length == 0) return {}; // NOTE: this resizing might seem weird... // when GetShortPathNameW fails, it returns length including null character // when it succeeds, it returns length excluding null character // See: https://msdn.microsoft.com/en-us/library/windows/desktop/aa364989(v=vs.85).aspx output.resize(length); if (GetShortPathNameW(input.c_str(), (LPWSTR)output.c_str(), length) == 0) return {}; output.resize(length - 1); QString ret = QString::fromStdWString(output); return ret; } // if the string survives roundtrip through local 8bit encoding... bool fitsInLocal8bit(const QString& string) { return string == QString::fromLocal8Bit(string.toLocal8Bit()); } QString getPathNameInLocal8bit(const QString& file) { if (!fitsInLocal8bit(file)) { auto path = shortPathName(file); if (!path.isEmpty()) { return path; } // in case shortPathName fails just return the path as is } return file; } #endif QString getUniqueResourceName(const QString& filePath) { auto newFileName = filePath; if (!newFileName.endsWith(".disabled")) { return newFileName; // prioritize enabled mods } newFileName.chop(9); if (!QFile::exists(newFileName)) { return filePath; } QFileInfo fileInfo(filePath); auto baseName = fileInfo.completeBaseName(); auto path = fileInfo.absolutePath(); int counter = 1; do { if (counter == 1) { newFileName = FS::PathCombine(path, baseName + ".duplicate"); } else { newFileName = FS::PathCombine(path, baseName + ".duplicate" + QString::number(counter)); } counter++; } while (QFile::exists(newFileName)); return newFileName; } } // namespace FS
57,433
C++
.cpp
1,464
32.883197
140
0.64107
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,913
Markdown.cpp
PrismLauncher_PrismLauncher/launcher/Markdown.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2023 Joshua Goins <josh@redstrate.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "Markdown.h" QString markdownToHTML(const QString& markdown) { const QByteArray markdownData = markdown.toUtf8(); char* buffer = cmark_markdown_to_html(markdownData.constData(), markdownData.length(), CMARK_OPT_NOBREAKS | CMARK_OPT_UNSAFE); QString htmlStr(buffer); free(buffer); return htmlStr; }
1,071
C++
.cpp
26
38.692308
130
0.74928
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,914
ResourceDownloadTask.cpp
PrismLauncher_PrismLauncher/launcher/ResourceDownloadTask.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022-2023 flowln <flowlnlnln@gmail.com> * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "ResourceDownloadTask.h" #include "Application.h" #include "minecraft/mod/ModFolderModel.h" #include "minecraft/mod/ResourceFolderModel.h" #include "modplatform/helpers/HashUtils.h" #include "net/ApiDownload.h" #include "net/ChecksumValidator.h" ResourceDownloadTask::ResourceDownloadTask(ModPlatform::IndexedPack::Ptr pack, ModPlatform::IndexedVersion version, const std::shared_ptr<ResourceFolderModel> packs, bool is_indexed, QString custom_target_folder) : m_pack(std::move(pack)), m_pack_version(std::move(version)), m_pack_model(packs), m_custom_target_folder(custom_target_folder) { if (is_indexed) { m_update_task.reset(new LocalResourceUpdateTask(m_pack_model->indexDir(), *m_pack, m_pack_version)); connect(m_update_task.get(), &LocalResourceUpdateTask::hasOldResource, this, &ResourceDownloadTask::hasOldResource); addTask(m_update_task); } m_filesNetJob.reset(new NetJob(tr("Resource download"), APPLICATION->network())); m_filesNetJob->setStatus(tr("Downloading resource:\n%1").arg(m_pack_version.downloadUrl)); QDir dir{ m_pack_model->dir() }; { // FIXME: Make this more generic. May require adding additional info to IndexedVersion, // or adquiring a reference to the base instance. if (!m_custom_target_folder.isEmpty()) { dir.cdUp(); dir.cd(m_custom_target_folder); } } auto action = Net::ApiDownload::makeFile(m_pack_version.downloadUrl, dir.absoluteFilePath(getFilename())); if (!m_pack_version.hash_type.isEmpty() && !m_pack_version.hash.isEmpty()) { switch (Hashing::algorithmFromString(m_pack_version.hash_type)) { case Hashing::Algorithm::Md4: action->addValidator(new Net::ChecksumValidator(QCryptographicHash::Algorithm::Md4, m_pack_version.hash)); break; case Hashing::Algorithm::Md5: action->addValidator(new Net::ChecksumValidator(QCryptographicHash::Algorithm::Md5, m_pack_version.hash)); break; case Hashing::Algorithm::Sha1: action->addValidator(new Net::ChecksumValidator(QCryptographicHash::Algorithm::Sha1, m_pack_version.hash)); break; case Hashing::Algorithm::Sha256: action->addValidator(new Net::ChecksumValidator(QCryptographicHash::Algorithm::Sha256, m_pack_version.hash)); break; case Hashing::Algorithm::Sha512: action->addValidator(new Net::ChecksumValidator(QCryptographicHash::Algorithm::Sha512, m_pack_version.hash)); break; default: break; } } m_filesNetJob->addNetAction(action); connect(m_filesNetJob.get(), &NetJob::succeeded, this, &ResourceDownloadTask::downloadSucceeded); connect(m_filesNetJob.get(), &NetJob::progress, this, &ResourceDownloadTask::downloadProgressChanged); connect(m_filesNetJob.get(), &NetJob::stepProgress, this, &ResourceDownloadTask::propagateStepProgress); connect(m_filesNetJob.get(), &NetJob::failed, this, &ResourceDownloadTask::downloadFailed); addTask(m_filesNetJob); } void ResourceDownloadTask::downloadSucceeded() { m_filesNetJob.reset(); auto name = std::get<0>(to_delete); auto filename = std::get<1>(to_delete); if (!name.isEmpty() && filename != m_pack_version.fileName) m_pack_model->uninstallResource(filename, true); } void ResourceDownloadTask::downloadFailed(QString reason) { emitFailed(reason); m_filesNetJob.reset(); } void ResourceDownloadTask::downloadProgressChanged(qint64 current, qint64 total) { emit progress(current, total); } // This indirection is done so that we don't delete a mod before being sure it was // downloaded successfully! void ResourceDownloadTask::hasOldResource(QString name, QString filename) { to_delete = { name, filename }; }
4,908
C++
.cpp
100
41.54
132
0.68398
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,915
LoggedProcess.cpp
PrismLauncher_PrismLauncher/launcher/LoggedProcess.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022,2023 Sefa Eyeoglu <contact@scrumplex.net> * Copyright (c) 2023 flowln <flowlnlnln@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 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 "LoggedProcess.h" #include <QDebug> #include <QTextDecoder> #include "MessageLevel.h" LoggedProcess::LoggedProcess(const QTextCodec* output_codec, QObject* parent) : QProcess(parent), m_err_decoder(output_codec), m_out_decoder(output_codec) { // QProcess has a strange interface... let's map a lot of those into a few. connect(this, &QProcess::readyReadStandardOutput, this, &LoggedProcess::on_stdOut); connect(this, &QProcess::readyReadStandardError, this, &LoggedProcess::on_stdErr); connect(this, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), this, &LoggedProcess::on_exit); connect(this, &QProcess::errorOccurred, this, &LoggedProcess::on_error); connect(this, &QProcess::stateChanged, this, &LoggedProcess::on_stateChange); } LoggedProcess::~LoggedProcess() { if (m_is_detachable) { setProcessState(QProcess::NotRunning); } } QStringList LoggedProcess::reprocess(const QByteArray& data, QTextDecoder& decoder) { auto str = decoder.toUnicode(data); if (!m_leftover_line.isEmpty()) { str.prepend(m_leftover_line); m_leftover_line = ""; } auto lines = str.remove(QChar::CarriageReturn).split(QChar::LineFeed); m_leftover_line = lines.takeLast(); return lines; } void LoggedProcess::on_stdErr() { auto lines = reprocess(readAllStandardError(), m_err_decoder); emit log(lines, MessageLevel::StdErr); } void LoggedProcess::on_stdOut() { auto lines = reprocess(readAllStandardOutput(), m_out_decoder); emit log(lines, MessageLevel::StdOut); } void LoggedProcess::on_exit(int exit_code, QProcess::ExitStatus status) { // save the exit code m_exit_code = exit_code; // based on state, send signals if (!m_is_aborting) { if (status == QProcess::NormalExit) { //: Message displayed on instance exit emit log({ tr("Process exited with code %1.").arg(exit_code) }, MessageLevel::Launcher); changeState(LoggedProcess::Finished); } else { //: Message displayed on instance crashed if (exit_code == -1) emit log({ tr("Process crashed.") }, MessageLevel::Launcher); else emit log({ tr("Process crashed with exitcode %1.").arg(exit_code) }, MessageLevel::Launcher); changeState(LoggedProcess::Crashed); } } else { //: Message displayed after the instance exits due to kill request emit log({ tr("Process was killed by user.") }, MessageLevel::Error); changeState(LoggedProcess::Aborted); } } void LoggedProcess::on_error(QProcess::ProcessError error) { switch (error) { case QProcess::FailedToStart: { emit log({ tr("The process failed to start.") }, MessageLevel::Fatal); changeState(LoggedProcess::FailedToStart); break; } // we'll just ignore those... never needed them case QProcess::Crashed: case QProcess::ReadError: case QProcess::Timedout: case QProcess::UnknownError: case QProcess::WriteError: break; } } void LoggedProcess::kill() { m_is_aborting = true; QProcess::kill(); } int LoggedProcess::exitCode() const { return m_exit_code; } void LoggedProcess::changeState(LoggedProcess::State state) { if (state == m_state) return; m_state = state; emit stateChanged(m_state); } LoggedProcess::State LoggedProcess::state() const { return m_state; } void LoggedProcess::on_stateChange(QProcess::ProcessState state) { switch (state) { case QProcess::NotRunning: break; // let's not - there are too many that handle this already. case QProcess::Starting: { if (m_state != LoggedProcess::NotRunning) { qWarning() << "Wrong state change for process from state" << m_state << "to" << (int)LoggedProcess::Starting; } changeState(LoggedProcess::Starting); return; } case QProcess::Running: { if (m_state != LoggedProcess::Starting) { qWarning() << "Wrong state change for process from state" << m_state << "to" << (int)LoggedProcess::Running; } changeState(LoggedProcess::Running); return; } } } void LoggedProcess::setDetachable(bool detachable) { m_is_detachable = detachable; }
5,998
C++
.cpp
162
31.783951
125
0.674459
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,916
DataMigrationTask.cpp
PrismLauncher_PrismLauncher/launcher/DataMigrationTask.cpp
// SPDX-FileCopyrightText: 2022 Sefa Eyeoglu <contact@scrumplex.net> // // SPDX-License-Identifier: GPL-3.0-only #include "DataMigrationTask.h" #include "FileSystem.h" #include <QDirIterator> #include <QFileInfo> #include <QMap> #include <QtConcurrent> DataMigrationTask::DataMigrationTask(const QString& sourcePath, const QString& targetPath, const IPathMatcher::Ptr pathMatcher) : Task(), m_sourcePath(sourcePath), m_targetPath(targetPath), m_pathMatcher(pathMatcher), m_copy(sourcePath, targetPath) { m_copy.matcher(m_pathMatcher.get()).whitelist(true); } void DataMigrationTask::executeTask() { setStatus(tr("Scanning files...")); // 1. Scan // Check how many files we gotta copy m_copyFuture = QtConcurrent::run(QThreadPool::globalInstance(), [this] { return m_copy(true); // dry run to collect amount of files }); connect(&m_copyFutureWatcher, &QFutureWatcher<bool>::finished, this, &DataMigrationTask::dryRunFinished); connect(&m_copyFutureWatcher, &QFutureWatcher<bool>::canceled, this, &DataMigrationTask::dryRunAborted); m_copyFutureWatcher.setFuture(m_copyFuture); } void DataMigrationTask::dryRunFinished() { disconnect(&m_copyFutureWatcher, &QFutureWatcher<bool>::finished, this, &DataMigrationTask::dryRunFinished); disconnect(&m_copyFutureWatcher, &QFutureWatcher<bool>::canceled, this, &DataMigrationTask::dryRunAborted); #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)) if (!m_copyFuture.isValid() || !m_copyFuture.result()) { #else if (!m_copyFuture.result()) { #endif emitFailed(tr("Failed to scan source path.")); return; } // 2. Copy // Actually copy all files now. m_toCopy = m_copy.totalCopied(); connect(&m_copy, &FS::copy::fileCopied, [&, this](const QString& relativeName) { QString shortenedName = relativeName; // shorten the filename to hopefully fit into one line if (shortenedName.length() > 50) shortenedName = relativeName.left(20) + "…" + relativeName.right(29); setProgress(m_copy.totalCopied(), m_toCopy); setStatus(tr("Copying %1…").arg(shortenedName)); }); m_copyFuture = QtConcurrent::run(QThreadPool::globalInstance(), [this] { return m_copy(false); // actually copy now }); connect(&m_copyFutureWatcher, &QFutureWatcher<bool>::finished, this, &DataMigrationTask::copyFinished); connect(&m_copyFutureWatcher, &QFutureWatcher<bool>::canceled, this, &DataMigrationTask::copyAborted); m_copyFutureWatcher.setFuture(m_copyFuture); } void DataMigrationTask::dryRunAborted() { emitFailed(tr("Aborted")); } void DataMigrationTask::copyFinished() { disconnect(&m_copyFutureWatcher, &QFutureWatcher<bool>::finished, this, &DataMigrationTask::copyFinished); disconnect(&m_copyFutureWatcher, &QFutureWatcher<bool>::canceled, this, &DataMigrationTask::copyAborted); #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)) if (!m_copyFuture.isValid() || !m_copyFuture.result()) { #else if (!m_copyFuture.result()) { #endif emitFailed(tr("Some paths could not be copied!")); return; } emitSucceeded(); } void DataMigrationTask::copyAborted() { emitFailed(tr("Aborted")); }
3,239
C++
.cpp
78
37.307692
127
0.716423
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,917
JavaCommon.cpp
PrismLauncher_PrismLauncher/launcher/JavaCommon.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 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 "JavaCommon.h" #include "java/JavaUtils.h" #include "ui/dialogs/CustomMessageBox.h" #include <QRegularExpression> bool JavaCommon::checkJVMArgs(QString jvmargs, QWidget* parent) { if (jvmargs.contains("-XX:PermSize=") || jvmargs.contains(QRegularExpression("-Xm[sx]")) || jvmargs.contains("-XX-MaxHeapSize") || jvmargs.contains("-XX:InitialHeapSize")) { auto warnStr = QObject::tr( "You tried to manually set a JVM memory option (using \"-XX:PermSize\", \"-XX-MaxHeapSize\", \"-XX:InitialHeapSize\", \"-Xmx\" " "or \"-Xms\").\n" "There are dedicated boxes for these in the settings (Java tab, in the Memory group at the top).\n" "This message will be displayed until you remove them from the JVM arguments."); CustomMessageBox::selectable(parent, QObject::tr("JVM arguments warning"), warnStr, QMessageBox::Warning)->exec(); return false; } // block lunacy with passing required version to the JVM if (jvmargs.contains(QRegularExpression("-version:.*"))) { auto warnStr = QObject::tr( "You tried to pass required Java version argument to the JVM (using \"-version:xxx\"). This is not safe and will not be " "allowed.\n" "This message will be displayed until you remove this from the JVM arguments."); CustomMessageBox::selectable(parent, QObject::tr("JVM arguments warning"), warnStr, QMessageBox::Warning)->exec(); return false; } return true; } void JavaCommon::javaWasOk(QWidget* parent, const JavaChecker::Result& result) { QString text; text += QObject::tr( "Java test succeeded!<br />Platform reported: %1<br />Java version " "reported: %2<br />Java vendor " "reported: %3<br />") .arg(result.realPlatform, result.javaVersion.toString(), result.javaVendor); if (result.errorLog.size()) { auto htmlError = result.errorLog; htmlError.replace('\n', "<br />"); text += QObject::tr("<br />Warnings:<br /><font color=\"orange\">%1</font>").arg(htmlError); } CustomMessageBox::selectable(parent, QObject::tr("Java test success"), text, QMessageBox::Information)->show(); } void JavaCommon::javaArgsWereBad(QWidget* parent, const JavaChecker::Result& result) { auto htmlError = result.errorLog; QString text; htmlError.replace('\n', "<br />"); text += QObject::tr("The specified Java binary didn't work with the arguments you provided:<br />"); text += QString("<font color=\"red\">%1</font>").arg(htmlError); CustomMessageBox::selectable(parent, QObject::tr("Java test failure"), text, QMessageBox::Warning)->show(); } void JavaCommon::javaBinaryWasBad(QWidget* parent, const JavaChecker::Result& result) { QString text; text += QObject::tr( "The specified Java binary didn't work.<br />You should use the auto-detect feature, " "or set the path to the Java executable.<br />"); CustomMessageBox::selectable(parent, QObject::tr("Java test failure"), text, QMessageBox::Warning)->show(); } void JavaCommon::javaCheckNotFound(QWidget* parent) { QString text; text += QObject::tr("Java checker library could not be found. Please check your installation."); CustomMessageBox::selectable(parent, QObject::tr("Java test failure"), text, QMessageBox::Warning)->show(); } void JavaCommon::TestCheck::run() { if (!JavaCommon::checkJVMArgs(m_args, m_parent)) { emit finished(); return; } if (JavaUtils::getJavaCheckPath().isEmpty()) { javaCheckNotFound(m_parent); emit finished(); return; } checker.reset(new JavaChecker(m_path, "", 0, 0, 0, 0)); connect(checker.get(), &JavaChecker::checkFinished, this, &JavaCommon::TestCheck::checkFinished); checker->start(); } void JavaCommon::TestCheck::checkFinished(const JavaChecker::Result& result) { if (result.validity != JavaChecker::Result::Validity::Valid) { javaBinaryWasBad(m_parent, result); emit finished(); return; } checker.reset(new JavaChecker(m_path, m_args, m_maxMem, m_maxMem, result.javaVersion.requiresPermGen() ? m_permGen : 0, 0)); connect(checker.get(), &JavaChecker::checkFinished, this, &JavaCommon::TestCheck::checkFinishedWithArgs); checker->start(); } void JavaCommon::TestCheck::checkFinishedWithArgs(const JavaChecker::Result& result) { if (result.validity == JavaChecker::Result::Validity::Valid) { javaWasOk(m_parent, result); emit finished(); return; } javaArgsWereBad(m_parent, result); emit finished(); }
6,170
C++
.cpp
135
40.777778
140
0.687137
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
28,918
InstanceCopyTask.cpp
PrismLauncher_PrismLauncher/launcher/InstanceCopyTask.cpp
#include "InstanceCopyTask.h" #include <QDebug> #include <QtConcurrentRun> #include <memory> #include "FileSystem.h" #include "NullInstance.h" #include "pathmatcher/RegexpMatcher.h" #include "settings/INISettingsObject.h" #include "tasks/Task.h" InstanceCopyTask::InstanceCopyTask(InstancePtr origInstance, const InstanceCopyPrefs& prefs) { m_origInstance = origInstance; m_keepPlaytime = prefs.isKeepPlaytimeEnabled(); m_useLinks = prefs.isUseSymLinksEnabled(); m_linkRecursively = prefs.isLinkRecursivelyEnabled(); m_useHardLinks = prefs.isLinkRecursivelyEnabled() && prefs.isUseHardLinksEnabled(); m_copySaves = prefs.isLinkRecursivelyEnabled() && prefs.isDontLinkSavesEnabled() && prefs.isCopySavesEnabled(); m_useClone = prefs.isUseCloneEnabled(); QString filters = prefs.getSelectedFiltersAsRegex(); if (m_useLinks || m_useHardLinks) { if (!filters.isEmpty()) filters += "|"; filters += "instance.cfg"; } qDebug() << "CopyFilters:" << filters; if (!filters.isEmpty()) { // Set regex filter: // FIXME: get this from the original instance type... auto matcherReal = new RegexpMatcher(filters); matcherReal->caseSensitive(false); m_matcher.reset(matcherReal); } } void InstanceCopyTask::executeTask() { setStatus(tr("Copying instance %1").arg(m_origInstance->name())); m_copyFuture = QtConcurrent::run(QThreadPool::globalInstance(), [this] { if (m_useClone) { FS::clone folderClone(m_origInstance->instanceRoot(), m_stagingPath); folderClone.matcher(m_matcher.get()); folderClone(true); setProgress(0, folderClone.totalCloned()); connect(&folderClone, &FS::clone::fileCloned, [this](QString src, QString dst) { setProgress(m_progress + 1, m_progressTotal); }); return folderClone(); } if (m_useLinks || m_useHardLinks) { std::unique_ptr<FS::copy> savesCopy; if (m_copySaves) { QFileInfo mcDir(FS::PathCombine(m_stagingPath, "minecraft")); QFileInfo dotMCDir(FS::PathCombine(m_stagingPath, ".minecraft")); QString staging_mc_dir; if (dotMCDir.exists() && !mcDir.exists()) staging_mc_dir = dotMCDir.filePath(); else staging_mc_dir = mcDir.filePath(); savesCopy = std::make_unique<FS::copy>(FS::PathCombine(m_origInstance->gameRoot(), "saves"), FS::PathCombine(staging_mc_dir, "saves")); savesCopy->followSymlinks(true); (*savesCopy)(true); setProgress(0, savesCopy->totalCopied()); connect(savesCopy.get(), &FS::copy::fileCopied, [this](QString src) { setProgress(m_progress + 1, m_progressTotal); }); } FS::create_link folderLink(m_origInstance->instanceRoot(), m_stagingPath); int depth = m_linkRecursively ? -1 : 0; // we need to at least link the top level instead of the instance folder folderLink.linkRecursively(true).setMaxDepth(depth).useHardLinks(m_useHardLinks).matcher(m_matcher.get()); folderLink(true); setProgress(0, m_progressTotal + folderLink.totalToLink()); connect(&folderLink, &FS::create_link::fileLinked, [this](QString src, QString dst) { setProgress(m_progress + 1, m_progressTotal); }); bool there_were_errors = false; if (!folderLink()) { #if defined Q_OS_WIN32 if (!m_useHardLinks) { setProgress(0, m_progressTotal); qDebug() << "EXPECTED: Link failure, Windows requires permissions for symlinks"; qDebug() << "attempting to run with privelage"; QEventLoop loop; bool got_priv_results = false; connect(&folderLink, &FS::create_link::finishedPrivileged, this, [&got_priv_results, &loop](bool gotResults) { if (!gotResults) { qDebug() << "Privileged run exited without results!"; } got_priv_results = gotResults; loop.quit(); }); folderLink.runPrivileged(); loop.exec(); // wait for the finished signal for (auto result : folderLink.getResults()) { if (result.err_value != 0) { there_were_errors = true; } } if (savesCopy) { there_were_errors |= !(*savesCopy)(); } return got_priv_results && !there_were_errors; } #else qDebug() << "Link Failed!" << folderLink.getOSError().value() << folderLink.getOSError().message().c_str(); #endif return false; } if (savesCopy) { there_were_errors |= !(*savesCopy)(); } return !there_were_errors; } FS::copy folderCopy(m_origInstance->instanceRoot(), m_stagingPath); folderCopy.followSymlinks(false).matcher(m_matcher.get()); folderCopy(true); setProgress(0, folderCopy.totalCopied()); connect(&folderCopy, &FS::copy::fileCopied, [this](QString src) { setProgress(m_progress + 1, m_progressTotal); }); return folderCopy(); }); connect(&m_copyFutureWatcher, &QFutureWatcher<bool>::finished, this, &InstanceCopyTask::copyFinished); connect(&m_copyFutureWatcher, &QFutureWatcher<bool>::canceled, this, &InstanceCopyTask::copyAborted); m_copyFutureWatcher.setFuture(m_copyFuture); } void InstanceCopyTask::copyFinished() { auto successful = m_copyFuture.result(); if (!successful) { emitFailed(tr("Instance folder copy failed.")); return; } // FIXME: shouldn't this be able to report errors? auto instanceSettings = std::make_shared<INISettingsObject>(FS::PathCombine(m_stagingPath, "instance.cfg")); InstancePtr inst(new NullInstance(m_globalSettings, instanceSettings, m_stagingPath)); inst->setName(name()); inst->setIconKey(m_instIcon); if (!m_keepPlaytime) { inst->resetTimePlayed(); } if (m_useLinks) { inst->addLinkedInstanceId(m_origInstance->id()); auto allowed_symlinks_file = QFileInfo(FS::PathCombine(inst->gameRoot(), "allowed_symlinks.txt")); QByteArray allowed_symlinks; if (allowed_symlinks_file.exists()) { allowed_symlinks.append(FS::read(allowed_symlinks_file.filePath())); if (allowed_symlinks.right(1) != "\n") allowed_symlinks.append("\n"); // we want to be on a new line } allowed_symlinks.append(m_origInstance->gameRoot().toUtf8()); allowed_symlinks.append("\n"); if (allowed_symlinks_file.isSymLink()) FS::deletePath( allowed_symlinks_file .filePath()); // we dont want to modify the original. also make sure the resulting file is not itself a link. try { FS::write(allowed_symlinks_file.filePath(), allowed_symlinks); } catch (const FS::FileSystemException& e) { qCritical() << "Failed to write symlink :" << e.cause(); } } emitSucceeded(); } void InstanceCopyTask::copyAborted() { emitFailed(tr("Instance folder copy has been aborted.")); return; } bool InstanceCopyTask::abort() { if (m_copyFutureWatcher.isRunning()) { m_copyFutureWatcher.cancel(); // NOTE: Here we don't do `emitAborted()` because it will be done when `m_copyFutureWatcher` actually cancels, which may not occur // immediately. return true; } return false; }
8,033
C++
.cpp
172
35.755814
138
0.598749
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,919
Application.cpp
PrismLauncher_PrismLauncher/launcher/Application.cpp
// SPDX-FileCopyrightText: 2022 Sefa Eyeoglu <contact@scrumplex.net> // // SPDX-License-Identifier: GPL-3.0-only AND Apache-2.0 /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * Copyright (C) 2022 Lenny McLennington <lenny@sneed.church> * Copyright (C) 2022 Tayou <git@tayou.org> * Copyright (C) 2023 TheKodeToad <TheKodeToad@proton.me> * Copyright (C) 2023 Rachel Powers <508861+Ryex@users.noreply.github.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 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 "Application.h" #include "BuildConfig.h" #include "DataMigrationTask.h" #include "java/JavaInstallList.h" #include "net/PasteUpload.h" #include "pathmatcher/MultiMatcher.h" #include "pathmatcher/SimplePrefixMatcher.h" #include "tasks/Task.h" #include "tools/GenericProfiler.h" #include "ui/InstanceWindow.h" #include "ui/MainWindow.h" #include "ui/dialogs/ProgressDialog.h" #include "ui/instanceview/AccessibleInstanceView.h" #include "ui/pages/BasePageProvider.h" #include "ui/pages/global/APIPage.h" #include "ui/pages/global/AccountListPage.h" #include "ui/pages/global/CustomCommandsPage.h" #include "ui/pages/global/EnvironmentVariablesPage.h" #include "ui/pages/global/ExternalToolsPage.h" #include "ui/pages/global/JavaPage.h" #include "ui/pages/global/LanguagePage.h" #include "ui/pages/global/LauncherPage.h" #include "ui/pages/global/MinecraftPage.h" #include "ui/pages/global/ProxyPage.h" #include "ui/setupwizard/AutoJavaWizardPage.h" #include "ui/setupwizard/JavaWizardPage.h" #include "ui/setupwizard/LanguageWizardPage.h" #include "ui/setupwizard/LoginWizardPage.h" #include "ui/setupwizard/PasteWizardPage.h" #include "ui/setupwizard/SetupWizard.h" #include "ui/setupwizard/ThemeWizardPage.h" #include "ui/dialogs/CustomMessageBox.h" #include "ui/pagedialog/PageDialog.h" #include "ui/themes/ThemeManager.h" #include "ApplicationMessage.h" #include <iostream> #include <mutex> #include <QAccessible> #include <QCommandLineParser> #include <QDebug> #include <QDir> #include <QFileInfo> #include <QFileOpenEvent> #include <QIcon> #include <QLibraryInfo> #include <QList> #include <QNetworkAccessManager> #include <QStringList> #include <QStyleFactory> #include <QTranslator> #include <QWindow> #include "InstanceList.h" #include "MTPixmapCache.h" #include <minecraft/auth/AccountList.h> #include "icons/IconList.h" #include "net/HttpMetaCache.h" #include "java/JavaInstallList.h" #include "updater/ExternalUpdater.h" #include "tools/JProfiler.h" #include "tools/JVisualVM.h" #include "tools/MCEditTool.h" #include "settings/INISettingsObject.h" #include "settings/Setting.h" #include "meta/Index.h" #include "translations/TranslationsModel.h" #include <DesktopServices.h> #include <FileSystem.h> #include <LocalPeer.h> #include <stdlib.h> #include <sys.h> #include "SysInfo.h" #ifdef Q_OS_LINUX #include <dlfcn.h> #include "MangoHud.h" #include "gamemode_client.h" #endif #if defined(Q_OS_LINUX) #include <sys/statvfs.h> #endif #if defined(Q_OS_FREEBSD) || defined(Q_OS_OPENBSD) #include <sys/mount.h> #include <sys/types.h> #endif #if defined(Q_OS_MAC) #if defined(SPARKLE_ENABLED) #include "updater/MacSparkleUpdater.h" #endif #else #include "updater/PrismExternalUpdater.h" #endif #if defined Q_OS_WIN32 #include <windows.h> #include "WindowsConsole.h" #endif #define STRINGIFY(x) #x #define TOSTRING(x) STRINGIFY(x) static const QLatin1String liveCheckFile("live.check"); PixmapCache* PixmapCache::s_instance = nullptr; namespace { /** This is used so that we can output to the log file in addition to the CLI. */ void appDebugOutput(QtMsgType type, const QMessageLogContext& context, const QString& msg) { static std::mutex loggerMutex; const std::lock_guard<std::mutex> lock(loggerMutex); // synchronized, QFile logFile is not thread-safe QString out = qFormatLogMessage(type, context, msg); out += QChar::LineFeed; APPLICATION->logFile->write(out.toUtf8()); APPLICATION->logFile->flush(); QTextStream(stderr) << out.toLocal8Bit(); fflush(stderr); } } // namespace std::tuple<QDateTime, QString, QString, QString, QString> read_lock_File(const QString& path) { auto contents = QString(FS::read(path)); auto lines = contents.split('\n'); QDateTime timestamp; QString from, to, target, data_path; for (auto line : lines) { auto index = line.indexOf("="); if (index < 0) continue; auto left = line.left(index); auto right = line.mid(index + 1); if (left.toLower() == "timestamp") { timestamp = QDateTime::fromString(right, Qt::ISODate); } else if (left.toLower() == "from") { from = right; } else if (left.toLower() == "to") { to = right; } else if (left.toLower() == "target") { target = right; } else if (left.toLower() == "data_path") { data_path = right; } } return std::make_tuple(timestamp, from, to, target, data_path); } Application::Application(int& argc, char** argv) : QApplication(argc, argv) { #if defined Q_OS_WIN32 // attach the parent console if stdout not already captured if (AttachWindowsConsole()) { consoleAttached = true; } #endif setOrganizationName(BuildConfig.LAUNCHER_NAME); setOrganizationDomain(BuildConfig.LAUNCHER_DOMAIN); setApplicationName(BuildConfig.LAUNCHER_NAME); setApplicationDisplayName(QString("%1 %2").arg(BuildConfig.LAUNCHER_DISPLAYNAME, BuildConfig.printableVersionString())); setApplicationVersion(BuildConfig.printableVersionString() + "\n" + BuildConfig.GIT_COMMIT); setDesktopFileName(BuildConfig.LAUNCHER_DESKTOPFILENAME); startTime = QDateTime::currentDateTime(); // Don't quit on hiding the last window this->setQuitOnLastWindowClosed(false); this->setQuitLockEnabled(false); // Commandline parsing QCommandLineParser parser; parser.setApplicationDescription(BuildConfig.LAUNCHER_DISPLAYNAME); parser.addOptions( { { { "d", "dir" }, "Use a custom path as application root (use '.' for current directory)", "directory" }, { { "l", "launch" }, "Launch the specified instance (by instance ID)", "instance" }, { { "s", "server" }, "Join the specified server on launch (only valid in combination with --launch)", "address" }, { { "w", "world" }, "Join the specified world on launch (only valid in combination with --launch)", "world" }, { { "a", "profile" }, "Use the account specified by its profile name (only valid in combination with --launch)", "profile" }, { { "o", "offline" }, "Launch offline, with given player name (only valid in combination with --launch)", "offline" }, { "alive", "Write a small '" + liveCheckFile + "' file after the launcher starts" }, { { "I", "import" }, "Import instance or resource from specified local path or URL", "url" }, { "show", "Opens the window for the specified instance (by instance ID)", "show" } }); // Has to be positional for some OS to handle that properly parser.addPositionalArgument("URL", "Import the resource(s) at the given URL(s) (same as -I / --import)", "[URL...]"); parser.addHelpOption(); parser.addVersionOption(); parser.process(arguments()); m_instanceIdToLaunch = parser.value("launch"); m_serverToJoin = parser.value("server"); m_worldToJoin = parser.value("world"); m_profileToUse = parser.value("profile"); if (parser.isSet("offline")) { m_offline = true; m_offlineName = parser.value("offline"); } m_liveCheck = parser.isSet("alive"); m_instanceIdToShowWindowOf = parser.value("show"); for (auto url : parser.values("import")) { m_urlsToImport.append(normalizeImportUrl(url)); } // treat unspecified positional arguments as import urls for (auto url : parser.positionalArguments()) { m_urlsToImport.append(normalizeImportUrl(url)); } // error if --launch is missing with --server or --profile if ((!m_serverToJoin.isEmpty() || !m_worldToJoin.isEmpty() || !m_profileToUse.isEmpty() || m_offline) && m_instanceIdToLaunch.isEmpty()) { std::cerr << "--server, --profile and --offline can only be used in combination with --launch!" << std::endl; m_status = Application::Failed; return; } QString origcwdPath = QDir::currentPath(); QString binPath = applicationDirPath(); { // Root path is used for updates and portable data #if defined(Q_OS_LINUX) || defined(Q_OS_FREEBSD) || defined(Q_OS_OPENBSD) QDir foo(FS::PathCombine(binPath, "..")); // typically portable-root or /usr m_rootPath = foo.absolutePath(); #elif defined(Q_OS_WIN32) m_rootPath = binPath; #elif defined(Q_OS_MAC) QDir foo(FS::PathCombine(binPath, "../..")); m_rootPath = foo.absolutePath(); // on macOS, touch the root to force Finder to reload the .app metadata (and fix any icon change issues) FS::updateTimestamp(m_rootPath); #endif } QString adjustedBy; QString dataPath; // change folder QString dataDirEnv; QString dirParam = parser.value("dir"); if (!dirParam.isEmpty()) { // the dir param. it makes multimc data path point to whatever the user specified // on command line adjustedBy = "Command line"; dataPath = dirParam; } else if (dataDirEnv = QProcessEnvironment::systemEnvironment().value(QString("%1_DATA_DIR").arg(BuildConfig.LAUNCHER_NAME.toUpper())); !dataDirEnv.isEmpty()) { adjustedBy = "System environment"; dataPath = dataDirEnv; } else { QDir foo; if (DesktopServices::isSnap()) { foo = QDir(getenv("SNAP_USER_COMMON")); } else { foo = QDir(FS::PathCombine(QStandardPaths::writableLocation(QStandardPaths::AppDataLocation), "..")); } dataPath = foo.absolutePath(); adjustedBy = "Persistent data path"; #ifndef Q_OS_MACOS if (auto portableUserData = FS::PathCombine(m_rootPath, "UserData"); QDir(portableUserData).exists()) { dataPath = portableUserData; adjustedBy = "Portable user data path"; m_portable = true; } else if (QFile::exists(FS::PathCombine(m_rootPath, "portable.txt"))) { dataPath = m_rootPath; adjustedBy = "Portable data path"; m_portable = true; } #endif } if (!FS::ensureFolderPathExists(dataPath)) { showFatalErrorMessage( "The launcher data folder could not be created.", QString("The launcher data folder could not be created.\n" "\n" "Make sure you have the right permissions to the launcher data folder and any folder needed to access it.\n" "(%1)\n" "\n" "The launcher cannot continue until you fix this problem.") .arg(dataPath)); return; } if (!QDir::setCurrent(dataPath)) { showFatalErrorMessage("The launcher data folder could not be opened.", QString("The launcher data folder could not be opened.\n" "\n" "Make sure you have the right permissions to the launcher data folder.\n" "(%1)\n" "\n" "The launcher cannot continue until you fix this problem.") .arg(dataPath)); return; } m_dataPath = dataPath; /* * Establish the mechanism for communication with an already running PrismLauncher that uses the same data path. * If there is one, tell it what the user actually wanted to do and exit. * We want to initialize this before logging to avoid messing with the log of a potential already running copy. */ auto appID = ApplicationId::fromPathAndVersion(QDir::currentPath(), BuildConfig.printableVersionString()); { // FIXME: you can run the same binaries with multiple data dirs and they won't clash. This could cause issues for updates. m_peerInstance = new LocalPeer(this, appID); connect(m_peerInstance, &LocalPeer::messageReceived, this, &Application::messageReceived); if (m_peerInstance->isClient()) { int timeout = 2000; if (m_instanceIdToLaunch.isEmpty()) { ApplicationMessage activate; activate.command = "activate"; m_peerInstance->sendMessage(activate.serialize(), timeout); if (!m_urlsToImport.isEmpty()) { for (auto url : m_urlsToImport) { ApplicationMessage import; import.command = "import"; import.args.insert("url", url.toString()); m_peerInstance->sendMessage(import.serialize(), timeout); } } } else { ApplicationMessage launch; launch.command = "launch"; launch.args["id"] = m_instanceIdToLaunch; if (!m_serverToJoin.isEmpty()) { launch.args["server"] = m_serverToJoin; } else if (!m_worldToJoin.isEmpty()) { launch.args["world"] = m_worldToJoin; } if (!m_profileToUse.isEmpty()) { launch.args["profile"] = m_profileToUse; } if (m_offline) { launch.args["offline_enabled"] = "true"; launch.args["offline_name"] = m_offlineName; } m_peerInstance->sendMessage(launch.serialize(), timeout); } m_status = Application::Succeeded; return; } } // init the logger { static const QString baseLogFile = BuildConfig.LAUNCHER_NAME + "-%0.log"; static const QString logBase = FS::PathCombine("logs", baseLogFile); if (FS::ensureFolderPathExists("logs")) { // if this did not fail for (auto i = 0; i <= 4; i++) if (auto oldName = baseLogFile.arg(i); QFile::exists(oldName)) // do not pointlessly delete new files if the old ones are not there FS::move(oldName, logBase.arg(i)); } for (auto i = 4; i > 0; i--) FS::move(logBase.arg(i - 1), logBase.arg(i)); logFile = std::unique_ptr<QFile>(new QFile(logBase.arg(0))); if (!logFile->open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate)) { showFatalErrorMessage("The launcher data folder is not writable!", QString("The launcher couldn't create a log file - the data folder is not writable.\n" "\n" "Make sure you have write permissions to the data folder.\n" "(%1)\n" "\n" "The launcher cannot continue until you fix this problem.") .arg(dataPath)); return; } qInstallMessageHandler(appDebugOutput); qSetMessagePattern( "%{time process}" " " "%{if-debug}D%{endif}" "%{if-info}I%{endif}" "%{if-warning}W%{endif}" "%{if-critical}C%{endif}" "%{if-fatal}F%{endif}" " " "|" " " "%{if-category}[%{category}]: %{endif}" "%{message}"); bool foundLoggingRules = false; auto logRulesFile = QStringLiteral("qtlogging.ini"); auto logRulesPath = FS::PathCombine(dataPath, logRulesFile); qDebug() << "Testing" << logRulesPath << "..."; foundLoggingRules = QFile::exists(logRulesPath); // search the dataPath() // seach app data standard path if (!foundLoggingRules && !isPortable() && dirParam.isEmpty() && dataDirEnv.isEmpty()) { logRulesPath = QStandardPaths::locate(QStandardPaths::AppDataLocation, FS::PathCombine("..", logRulesFile)); if (!logRulesPath.isEmpty()) { qDebug() << "Found" << logRulesPath << "..."; foundLoggingRules = true; } } // seach root path if (!foundLoggingRules) { #if defined(Q_OS_LINUX) || defined(Q_OS_FREEBSD) || defined(Q_OS_OPENBSD) logRulesPath = FS::PathCombine(m_rootPath, "share", BuildConfig.LAUNCHER_NAME, logRulesFile); #else logRulesPath = FS::PathCombine(m_rootPath, logRulesFile); #endif qDebug() << "Testing" << logRulesPath << "..."; foundLoggingRules = QFile::exists(logRulesPath); } if (foundLoggingRules) { // load and set logging rules qDebug() << "Loading logging rules from:" << logRulesPath; QSettings loggingRules(logRulesPath, QSettings::IniFormat); loggingRules.beginGroup("Rules"); QStringList rule_names = loggingRules.childKeys(); QStringList rules; qDebug() << "Setting log rules:"; for (auto rule_name : rule_names) { auto rule = QString("%1=%2").arg(rule_name).arg(loggingRules.value(rule_name).toString()); rules.append(rule); qDebug() << " " << rule; } auto rules_str = rules.join("\n"); QLoggingCategory::setFilterRules(rules_str); } qDebug() << "<> Log initialized."; } { bool migrated = false; if (!migrated) migrated = handleDataMigration( dataPath, FS::PathCombine(QStandardPaths::writableLocation(QStandardPaths::AppDataLocation), "../../PolyMC"), "PolyMC", "polymc.cfg"); if (!migrated) migrated = handleDataMigration( dataPath, FS::PathCombine(QStandardPaths::writableLocation(QStandardPaths::AppDataLocation), "../../multimc"), "MultiMC", "multimc.cfg"); } { qDebug() << qPrintable(BuildConfig.LAUNCHER_DISPLAYNAME + ", " + QString(BuildConfig.LAUNCHER_COPYRIGHT).replace("\n", ", ")); qDebug() << "Version : " << BuildConfig.printableVersionString(); qDebug() << "Platform : " << BuildConfig.BUILD_PLATFORM; qDebug() << "Git commit : " << BuildConfig.GIT_COMMIT; qDebug() << "Git refspec : " << BuildConfig.GIT_REFSPEC; qDebug() << "Compiled for : " << BuildConfig.systemID(); qDebug() << "Compiled by : " << BuildConfig.compilerID(); qDebug() << "Build Artifact : " << BuildConfig.BUILD_ARTIFACT; qDebug() << "Updates Enabled : " << (updaterEnabled() ? "Yes" : "No"); if (adjustedBy.size()) { qDebug() << "Work dir before adjustment : " << origcwdPath; qDebug() << "Work dir after adjustment : " << QDir::currentPath(); qDebug() << "Adjusted by : " << adjustedBy; } else { qDebug() << "Work dir : " << QDir::currentPath(); } qDebug() << "Binary path : " << binPath; qDebug() << "Application root path : " << m_rootPath; if (!m_instanceIdToLaunch.isEmpty()) { qDebug() << "ID of instance to launch : " << m_instanceIdToLaunch; } if (!m_serverToJoin.isEmpty()) { qDebug() << "Address of server to join :" << m_serverToJoin; } else if (!m_worldToJoin.isEmpty()) { qDebug() << "Name of the world to join :" << m_worldToJoin; } qDebug() << "<> Paths set."; } if (m_liveCheck) { QFile check(liveCheckFile); if (check.open(QIODevice::WriteOnly | QIODevice::Truncate)) { auto payload = appID.toString().toUtf8(); if (check.write(payload) == payload.size()) { check.close(); } else { qWarning() << "Could not write into" << liveCheckFile << "!"; check.remove(); // also closes file! } } else { qWarning() << "Could not open" << liveCheckFile << "for writing!"; } } // Initialize application settings { // Provide a fallback for migration from PolyMC m_settings.reset(new INISettingsObject({ BuildConfig.LAUNCHER_CONFIGFILE, "polymc.cfg", "multimc.cfg" }, this)); // Theming m_settings->registerSetting("IconTheme", QString()); m_settings->registerSetting("ApplicationTheme", QString()); m_settings->registerSetting("BackgroundCat", QString("kitteh")); // Remembered state m_settings->registerSetting("LastUsedGroupForNewInstance", QString()); m_settings->registerSetting("MenuBarInsteadOfToolBar", false); m_settings->registerSetting("NumberOfConcurrentTasks", 10); m_settings->registerSetting("NumberOfConcurrentDownloads", 6); m_settings->registerSetting("NumberOfManualRetries", 1); m_settings->registerSetting("RequestTimeout", 60); QString defaultMonospace; int defaultSize = 11; #ifdef Q_OS_WIN32 defaultMonospace = "Courier"; defaultSize = 10; #elif defined(Q_OS_MAC) defaultMonospace = "Menlo"; #else defaultMonospace = "Monospace"; #endif // resolve the font so the default actually matches QFont consoleFont; consoleFont.setFamily(defaultMonospace); consoleFont.setStyleHint(QFont::Monospace); consoleFont.setFixedPitch(true); QFontInfo consoleFontInfo(consoleFont); QString resolvedDefaultMonospace = consoleFontInfo.family(); QFont resolvedFont(resolvedDefaultMonospace); qDebug() << "Detected default console font:" << resolvedDefaultMonospace << ", substitutions:" << resolvedFont.substitutions().join(','); m_settings->registerSetting("ConsoleFont", resolvedDefaultMonospace); m_settings->registerSetting("ConsoleFontSize", defaultSize); m_settings->registerSetting("ConsoleMaxLines", 100000); m_settings->registerSetting("ConsoleOverflowStop", true); // Folders m_settings->registerSetting("InstanceDir", "instances"); m_settings->registerSetting({ "CentralModsDir", "ModsDir" }, "mods"); m_settings->registerSetting("IconsDir", "icons"); m_settings->registerSetting("DownloadsDir", QStandardPaths::writableLocation(QStandardPaths::DownloadLocation)); m_settings->registerSetting("DownloadsDirWatchRecursive", false); m_settings->registerSetting("SkinsDir", "skins"); m_settings->registerSetting("JavaDir", "java"); // Editors m_settings->registerSetting("JsonEditor", QString()); // Language m_settings->registerSetting("Language", QString()); m_settings->registerSetting("UseSystemLocale", false); // Console m_settings->registerSetting("ShowConsole", false); m_settings->registerSetting("AutoCloseConsole", false); m_settings->registerSetting("ShowConsoleOnError", true); m_settings->registerSetting("LogPrePostOutput", true); // Window Size m_settings->registerSetting({ "LaunchMaximized", "MCWindowMaximize" }, false); m_settings->registerSetting({ "MinecraftWinWidth", "MCWindowWidth" }, 854); m_settings->registerSetting({ "MinecraftWinHeight", "MCWindowHeight" }, 480); // Proxy Settings m_settings->registerSetting("ProxyType", "None"); m_settings->registerSetting({ "ProxyAddr", "ProxyHostName" }, "127.0.0.1"); m_settings->registerSetting("ProxyPort", 8080); m_settings->registerSetting({ "ProxyUser", "ProxyUsername" }, ""); m_settings->registerSetting({ "ProxyPass", "ProxyPassword" }, ""); // Memory m_settings->registerSetting({ "MinMemAlloc", "MinMemoryAlloc" }, 512); m_settings->registerSetting({ "MaxMemAlloc", "MaxMemoryAlloc" }, SysInfo::suitableMaxMem()); m_settings->registerSetting("PermGen", 128); // Java Settings m_settings->registerSetting("JavaPath", ""); m_settings->registerSetting("JavaSignature", ""); m_settings->registerSetting("JavaArchitecture", ""); m_settings->registerSetting("JavaRealArchitecture", ""); m_settings->registerSetting("JavaVersion", ""); m_settings->registerSetting("JavaVendor", ""); m_settings->registerSetting("LastHostname", ""); m_settings->registerSetting("JvmArgs", ""); m_settings->registerSetting("IgnoreJavaCompatibility", false); m_settings->registerSetting("IgnoreJavaWizard", false); auto defaultEnableAutoJava = m_settings->get("JavaPath").toString().isEmpty(); m_settings->registerSetting("AutomaticJavaSwitch", defaultEnableAutoJava); m_settings->registerSetting("AutomaticJavaDownload", defaultEnableAutoJava); m_settings->registerSetting("UserAskedAboutAutomaticJavaDownload", false); // Legacy settings m_settings->registerSetting("OnlineFixes", false); // Native library workarounds m_settings->registerSetting("UseNativeOpenAL", false); m_settings->registerSetting("CustomOpenALPath", ""); m_settings->registerSetting("UseNativeGLFW", false); m_settings->registerSetting("CustomGLFWPath", ""); // Performance related options m_settings->registerSetting("EnableFeralGamemode", false); m_settings->registerSetting("EnableMangoHud", false); m_settings->registerSetting("UseDiscreteGpu", false); m_settings->registerSetting("UseZink", false); // Game time m_settings->registerSetting("ShowGameTime", true); m_settings->registerSetting("ShowGlobalGameTime", true); m_settings->registerSetting("RecordGameTime", true); m_settings->registerSetting("ShowGameTimeWithoutDays", false); // Minecraft mods m_settings->registerSetting("ModMetadataDisabled", false); m_settings->registerSetting("ModDependenciesDisabled", false); m_settings->registerSetting("SkipModpackUpdatePrompt", false); // Minecraft offline player name m_settings->registerSetting("LastOfflinePlayerName", ""); // Wrapper command for launch m_settings->registerSetting("WrapperCommand", ""); // Custom Commands m_settings->registerSetting({ "PreLaunchCommand", "PreLaunchCmd" }, ""); m_settings->registerSetting({ "PostExitCommand", "PostExitCmd" }, ""); // The cat m_settings->registerSetting("TheCat", false); m_settings->registerSetting("CatOpacity", 100); m_settings->registerSetting("StatusBarVisible", true); m_settings->registerSetting("ToolbarsLocked", false); m_settings->registerSetting("InstSortMode", "Name"); m_settings->registerSetting("SelectedInstance", QString()); // Window state and geometry m_settings->registerSetting("MainWindowState", ""); m_settings->registerSetting("MainWindowGeometry", ""); m_settings->registerSetting("ConsoleWindowState", ""); m_settings->registerSetting("ConsoleWindowGeometry", ""); m_settings->registerSetting("SettingsGeometry", ""); m_settings->registerSetting("PagedGeometry", ""); m_settings->registerSetting("NewInstanceGeometry", ""); m_settings->registerSetting("UpdateDialogGeometry", ""); m_settings->registerSetting("ModDownloadGeometry", ""); m_settings->registerSetting("RPDownloadGeometry", ""); m_settings->registerSetting("TPDownloadGeometry", ""); m_settings->registerSetting("ShaderDownloadGeometry", ""); // HACK: This code feels so stupid is there a less stupid way of doing this? { m_settings->registerSetting("PastebinURL", ""); m_settings->registerSetting("PastebinType", PasteUpload::PasteType::Mclogs); m_settings->registerSetting("PastebinCustomAPIBase", ""); QString pastebinURL = m_settings->get("PastebinURL").toString(); bool userHadDefaultPastebin = pastebinURL == "https://0x0.st"; if (!pastebinURL.isEmpty() && !userHadDefaultPastebin) { m_settings->set("PastebinType", PasteUpload::PasteType::NullPointer); m_settings->set("PastebinCustomAPIBase", pastebinURL); m_settings->reset("PastebinURL"); } bool ok; int pasteType = m_settings->get("PastebinType").toInt(&ok); // If PastebinType is invalid then reset the related settings. if (!ok || !(PasteUpload::PasteType::First <= pasteType && pasteType <= PasteUpload::PasteType::Last)) { m_settings->reset("PastebinType"); m_settings->reset("PastebinCustomAPIBase"); } } { // Meta URL m_settings->registerSetting("MetaURLOverride", ""); QUrl metaUrl(m_settings->get("MetaURLOverride").toString()); // get rid of invalid meta urls if (!metaUrl.isValid() || (metaUrl.scheme() != "http" && metaUrl.scheme() != "https")) m_settings->reset("MetaURLOverride"); } m_settings->registerSetting("CloseAfterLaunch", false); m_settings->registerSetting("QuitAfterGameStop", false); m_settings->registerSetting("Env", QVariant(QMap<QString, QVariant>())); // Custom Microsoft Authentication Client ID m_settings->registerSetting("MSAClientIDOverride", ""); // Custom Flame API Key { m_settings->registerSetting("CFKeyOverride", ""); m_settings->registerSetting("FlameKeyOverride", ""); QString flameKey = m_settings->get("CFKeyOverride").toString(); if (!flameKey.isEmpty()) m_settings->set("FlameKeyOverride", flameKey); m_settings->reset("CFKeyOverride"); } m_settings->registerSetting("ModrinthToken", ""); m_settings->registerSetting("UserAgentOverride", ""); // FTBApp instances m_settings->registerSetting("FTBAppInstancesPath", ""); // Custom Technic Client ID m_settings->registerSetting("TechnicClientID", ""); // Init page provider { m_globalSettingsProvider = std::make_shared<GenericPageProvider>(tr("Settings")); m_globalSettingsProvider->addPage<LauncherPage>(); m_globalSettingsProvider->addPage<MinecraftPage>(); m_globalSettingsProvider->addPage<JavaPage>(); m_globalSettingsProvider->addPage<LanguagePage>(); m_globalSettingsProvider->addPage<CustomCommandsPage>(); m_globalSettingsProvider->addPage<EnvironmentVariablesPage>(); m_globalSettingsProvider->addPage<ProxyPage>(); m_globalSettingsProvider->addPage<ExternalToolsPage>(); m_globalSettingsProvider->addPage<AccountListPage>(); m_globalSettingsProvider->addPage<APIPage>(); } PixmapCache::setInstance(new PixmapCache(this)); qDebug() << "<> Settings loaded."; } #ifndef QT_NO_ACCESSIBILITY QAccessible::installFactory(groupViewAccessibleFactory); #endif /* !QT_NO_ACCESSIBILITY */ // initialize network access and proxy setup { m_network.reset(new QNetworkAccessManager()); QString proxyTypeStr = settings()->get("ProxyType").toString(); QString addr = settings()->get("ProxyAddr").toString(); int port = settings()->get("ProxyPort").value<qint16>(); QString user = settings()->get("ProxyUser").toString(); QString pass = settings()->get("ProxyPass").toString(); updateProxySettings(proxyTypeStr, addr, port, user, pass); qDebug() << "<> Network done."; } // load translations { m_translations.reset(new TranslationsModel("translations")); auto bcp47Name = m_settings->get("Language").toString(); m_translations->selectLanguage(bcp47Name); qDebug() << "Your language is" << bcp47Name; qDebug() << "<> Translations loaded."; } // Instance icons { auto setting = APPLICATION->settings()->getSetting("IconsDir"); QStringList instFolders = { ":/icons/multimc/32x32/instances/", ":/icons/multimc/50x50/instances/", ":/icons/multimc/128x128/instances/", ":/icons/multimc/scalable/instances/" }; m_icons.reset(new IconList(instFolders, setting->get().toString())); connect(setting.get(), &Setting::SettingChanged, [this](const Setting&, QVariant value) { m_icons->directoryChanged(value.toString()); }); qDebug() << "<> Instance icons initialized."; } // Themes m_themeManager = std::make_unique<ThemeManager>(); // initialize and load all instances { auto InstDirSetting = m_settings->getSetting("InstanceDir"); // instance path: check for problems with '!' in instance path and warn the user in the log // and remember that we have to show him a dialog when the gui starts (if it does so) QString instDir = InstDirSetting->get().toString(); qDebug() << "Instance path : " << instDir; if (FS::checkProblemticPathJava(QDir(instDir))) { qWarning() << "Your instance path contains \'!\' and this is known to cause java problems!"; } m_instances.reset(new InstanceList(m_settings, instDir, this)); connect(InstDirSetting.get(), &Setting::SettingChanged, m_instances.get(), &InstanceList::on_InstFolderChanged); qDebug() << "Loading Instances..."; m_instances->loadList(); qDebug() << "<> Instances loaded."; } // and accounts { m_accounts.reset(new AccountList(this)); qDebug() << "Loading accounts..."; m_accounts->setListFilePath("accounts.json", true); m_accounts->loadList(); m_accounts->fillQueue(); qDebug() << "<> Accounts loaded."; } // init the http meta cache { m_metacache.reset(new HttpMetaCache("metacache")); m_metacache->addBase("asset_indexes", QDir("assets/indexes").absolutePath()); m_metacache->addBase("libraries", QDir("libraries").absolutePath()); m_metacache->addBase("fmllibs", QDir("mods/minecraftforge/libs").absolutePath()); m_metacache->addBase("general", QDir("cache").absolutePath()); m_metacache->addBase("ATLauncherPacks", QDir("cache/ATLauncherPacks").absolutePath()); m_metacache->addBase("FTBPacks", QDir("cache/FTBPacks").absolutePath()); m_metacache->addBase("TechnicPacks", QDir("cache/TechnicPacks").absolutePath()); m_metacache->addBase("FlamePacks", QDir("cache/FlamePacks").absolutePath()); m_metacache->addBase("FlameMods", QDir("cache/FlameMods").absolutePath()); m_metacache->addBase("ModrinthPacks", QDir("cache/ModrinthPacks").absolutePath()); m_metacache->addBase("ModrinthModpacks", QDir("cache/ModrinthModpacks").absolutePath()); m_metacache->addBase("translations", QDir("translations").absolutePath()); m_metacache->addBase("meta", QDir("meta").absolutePath()); m_metacache->addBase("java", QDir("cache/java").absolutePath()); m_metacache->Load(); qDebug() << "<> Cache initialized."; } // now we have network, download translation updates m_translations->downloadIndex(); // FIXME: what to do with these? m_profilers.insert("jprofiler", std::shared_ptr<BaseProfilerFactory>(new JProfilerFactory())); m_profilers.insert("jvisualvm", std::shared_ptr<BaseProfilerFactory>(new JVisualVMFactory())); m_profilers.insert("generic", std::shared_ptr<BaseProfilerFactory>(new GenericProfilerFactory())); for (auto profiler : m_profilers.values()) { profiler->registerSettings(m_settings); } // Create the MCEdit thing... why is this here? { m_mcedit.reset(new MCEditTool(m_settings)); } #ifdef Q_OS_MACOS connect(this, &Application::clickedOnDock, [this]() { this->showMainWindow(); }); #endif connect(this, &Application::aboutToQuit, [this]() { if (m_instances) { // save any remaining instance state m_instances->saveNow(); } if (logFile) { logFile->flush(); logFile->close(); } }); updateCapabilities(); detectLibraries(); // check update locks { auto update_log_path = FS::PathCombine(m_dataPath, "logs", "prism_launcher_update.log"); auto update_lock = QFileInfo(FS::PathCombine(m_dataPath, ".prism_launcher_update.lock")); if (update_lock.exists()) { auto [timestamp, from, to, target, data_path] = read_lock_File(update_lock.absoluteFilePath()); auto infoMsg = tr("This installation has a update lock file present at: %1\n" "\n" "Timestamp: %2\n" "Updating from version %3 to %4\n" "Target install path: %5\n" "Data Path: %6" "\n" "This likely means that a update attempt failed. Please ensure your installation is in working order before " "proceeding.\n" "Check the Prism Launcher updater log at: \n" "%7\n" "for details on the last update attempt.\n" "\n" "To delete this lock and proceed select \"Ignore\" below.") .arg(update_lock.absoluteFilePath()) .arg(timestamp.toString(Qt::ISODate), from, to, target, data_path) .arg(update_log_path); auto msgBox = QMessageBox(QMessageBox::Warning, tr("Update In Progress"), infoMsg, QMessageBox::Ignore | QMessageBox::Abort); msgBox.setDefaultButton(QMessageBox::Abort); msgBox.setModal(true); msgBox.setDetailedText(FS::read(update_log_path)); msgBox.setMinimumWidth(460); msgBox.adjustSize(); auto res = msgBox.exec(); switch (res) { case QMessageBox::Ignore: { FS::deletePath(update_lock.absoluteFilePath()); break; } case QMessageBox::Abort: [[fallthrough]]; default: { qDebug() << "Exiting because update lockfile is present"; QMetaObject::invokeMethod(this, []() { exit(1); }, Qt::QueuedConnection); return; } } } auto update_fail_marker = QFileInfo(FS::PathCombine(m_dataPath, ".prism_launcher_update.fail")); if (update_fail_marker.exists()) { auto infoMsg = tr("An update attempt failed\n" "\n" "Please ensure your installation is in working order before " "proceeding.\n" "Check the Prism Launcher updater log at: \n" "%1\n" "for details on the last update attempt.") .arg(update_log_path); auto msgBox = QMessageBox(QMessageBox::Warning, tr("Update Failed"), infoMsg, QMessageBox::Ignore | QMessageBox::Abort); msgBox.setDefaultButton(QMessageBox::Abort); msgBox.setModal(true); msgBox.setDetailedText(FS::read(update_log_path)); msgBox.setMinimumWidth(460); msgBox.adjustSize(); auto res = msgBox.exec(); switch (res) { case QMessageBox::Ignore: { FS::deletePath(update_fail_marker.absoluteFilePath()); break; } case QMessageBox::Abort: [[fallthrough]]; default: { qDebug() << "Exiting because update lockfile is present"; QMetaObject::invokeMethod(this, []() { exit(1); }, Qt::QueuedConnection); return; } } } auto update_success_marker = QFileInfo(FS::PathCombine(m_dataPath, ".prism_launcher_update.success")); if (update_success_marker.exists()) { auto infoMsg = tr("Update succeeded\n" "\n" "You are now running %1 .\n" "Check the Prism Launcher updater log at: \n" "%2\n" "for details.") .arg(BuildConfig.printableVersionString()) .arg(update_log_path); auto msgBox = new QMessageBox(QMessageBox::Information, tr("Update Succeeded"), infoMsg, QMessageBox::Ok); msgBox->setDefaultButton(QMessageBox::Ok); msgBox->setDetailedText(FS::read(update_log_path)); msgBox->setAttribute(Qt::WA_DeleteOnClose); msgBox->setMinimumWidth(460); msgBox->adjustSize(); msgBox->open(); FS::deletePath(update_success_marker.absoluteFilePath()); } } // notify user if /tmp is mounted with `noexec` (#1693) QString jvmArgs = m_settings->get("JvmArgs").toString(); if (jvmArgs.indexOf("java.io.tmpdir") == -1) { /* java.io.tmpdir is a valid workaround, so don't annoy */ bool is_tmp_noexec = false; #if defined(Q_OS_LINUX) struct statvfs tmp_stat; statvfs("/tmp", &tmp_stat); is_tmp_noexec = tmp_stat.f_flag & ST_NOEXEC; #elif defined(Q_OS_FREEBSD) || defined(Q_OS_OPENBSD) struct statfs tmp_stat; statfs("/tmp", &tmp_stat); is_tmp_noexec = tmp_stat.f_flags & MNT_NOEXEC; #endif if (is_tmp_noexec) { auto infoMsg = tr("Your /tmp directory is currently mounted with the 'noexec' flag enabled.\n" "Some versions of Minecraft may not launch.\n" "\n" "You may solve this issue by remounting /tmp as 'exec' or setting " "the java.io.tmpdir JVM argument to a writeable directory in a " "filesystem where the 'exec' flag is set (e.g., /home/user/.local/tmp)\n"); auto msgBox = new QMessageBox(QMessageBox::Information, tr("Incompatible system configuration"), infoMsg, QMessageBox::Ok); msgBox->setDefaultButton(QMessageBox::Ok); msgBox->setAttribute(Qt::WA_DeleteOnClose); msgBox->setMinimumWidth(460); msgBox->adjustSize(); msgBox->open(); } } if (createSetupWizard()) { return; } m_themeManager->applyCurrentlySelectedTheme(true); performMainStartupAction(); } bool Application::createSetupWizard() { bool javaRequired = [this]() { if (BuildConfig.JAVA_DOWNLOADER_ENABLED && settings()->get("AutomaticJavaDownload").toBool()) { return false; } bool ignoreJavaWizard = settings()->get("IgnoreJavaWizard").toBool(); if (ignoreJavaWizard) { return false; } QString currentHostName = QHostInfo::localHostName(); QString oldHostName = settings()->get("LastHostname").toString(); if (currentHostName != oldHostName) { settings()->set("LastHostname", currentHostName); return true; } QString currentJavaPath = settings()->get("JavaPath").toString(); QString actualPath = FS::ResolveExecutable(currentJavaPath); return actualPath.isNull(); }(); bool askjava = BuildConfig.JAVA_DOWNLOADER_ENABLED && !javaRequired && !settings()->get("AutomaticJavaDownload").toBool() && !settings()->get("AutomaticJavaSwitch").toBool() && !settings()->get("UserAskedAboutAutomaticJavaDownload").toBool(); bool languageRequired = settings()->get("Language").toString().isEmpty(); bool pasteInterventionRequired = settings()->get("PastebinURL") != ""; bool validWidgets = m_themeManager->isValidApplicationTheme(settings()->get("ApplicationTheme").toString()); bool validIcons = m_themeManager->isValidIconTheme(settings()->get("IconTheme").toString()); bool login = !m_accounts->anyAccountIsValid() && capabilities() & Application::SupportsMSA; bool themeInterventionRequired = !validWidgets || !validIcons; bool wizardRequired = javaRequired || languageRequired || pasteInterventionRequired || themeInterventionRequired || askjava || login; if (wizardRequired) { // set default theme after going into theme wizard if (!validIcons) settings()->set("IconTheme", QString("pe_colored")); if (!validWidgets) settings()->set("ApplicationTheme", QString("system")); m_themeManager->applyCurrentlySelectedTheme(true); m_setupWizard = new SetupWizard(nullptr); if (languageRequired) { m_setupWizard->addPage(new LanguageWizardPage(m_setupWizard)); } if (javaRequired) { m_setupWizard->addPage(new JavaWizardPage(m_setupWizard)); } else if (askjava) { m_setupWizard->addPage(new AutoJavaWizardPage(m_setupWizard)); } if (pasteInterventionRequired) { m_setupWizard->addPage(new PasteWizardPage(m_setupWizard)); } if (themeInterventionRequired) { m_setupWizard->addPage(new ThemeWizardPage(m_setupWizard)); } if (login) { m_setupWizard->addPage(new LoginWizardPage(m_setupWizard)); } connect(m_setupWizard, &QDialog::finished, this, &Application::setupWizardFinished); m_setupWizard->show(); } return wizardRequired || login; } bool Application::updaterEnabled() { #if defined(Q_OS_MAC) return BuildConfig.UPDATER_ENABLED; #else return BuildConfig.UPDATER_ENABLED && QFileInfo(FS::PathCombine(m_rootPath, updaterBinaryName())).isFile(); #endif } QString Application::updaterBinaryName() { auto exe_name = QStringLiteral("%1_updater").arg(BuildConfig.LAUNCHER_APP_BINARY_NAME); #if defined Q_OS_WIN32 exe_name.append(".exe"); #else exe_name.prepend("bin/"); #endif return exe_name; } bool Application::event(QEvent* event) { #ifdef Q_OS_MACOS if (event->type() == QEvent::ApplicationStateChange) { auto ev = static_cast<QApplicationStateChangeEvent*>(event); if (m_prevAppState == Qt::ApplicationActive && ev->applicationState() == Qt::ApplicationActive) { emit clickedOnDock(); } m_prevAppState = ev->applicationState(); } #endif if (event->type() == QEvent::FileOpen) { auto ev = static_cast<QFileOpenEvent*>(event); m_mainWindow->processURLs({ ev->url() }); } return QApplication::event(event); } void Application::setupWizardFinished(int status) { qDebug() << "Wizard result =" << status; performMainStartupAction(); } void Application::performMainStartupAction() { m_status = Application::Initialized; if (!m_instanceIdToLaunch.isEmpty()) { auto inst = instances()->getInstanceById(m_instanceIdToLaunch); if (inst) { MinecraftTarget::Ptr targetToJoin = nullptr; MinecraftAccountPtr accountToUse = nullptr; qDebug() << "<> Instance" << m_instanceIdToLaunch << "launching"; if (!m_serverToJoin.isEmpty()) { // FIXME: validate the server string targetToJoin.reset(new MinecraftTarget(MinecraftTarget::parse(m_serverToJoin, false))); qDebug() << " Launching with server" << m_serverToJoin; } else if (!m_worldToJoin.isEmpty()) { targetToJoin.reset(new MinecraftTarget(MinecraftTarget::parse(m_worldToJoin, true))); qDebug() << " Launching with world" << m_worldToJoin; } if (!m_profileToUse.isEmpty()) { accountToUse = accounts()->getAccountByProfileName(m_profileToUse); if (!accountToUse) { return; } qDebug() << " Launching with account" << m_profileToUse; } launch(inst, !m_offline, false, targetToJoin, accountToUse, m_offlineName); return; } } if (!m_instanceIdToShowWindowOf.isEmpty()) { auto inst = instances()->getInstanceById(m_instanceIdToShowWindowOf); if (inst) { qDebug() << "<> Showing window of instance " << m_instanceIdToShowWindowOf; showInstanceWindow(inst); return; } } if (!m_mainWindow) { // normal main window showMainWindow(false); qDebug() << "<> Main window shown."; } // initialize the updater if (updaterEnabled()) { qDebug() << "Initializing updater"; #ifdef Q_OS_MAC #if defined(SPARKLE_ENABLED) m_updater.reset(new MacSparkleUpdater()); #endif #else m_updater.reset(new PrismExternalUpdater(m_mainWindow, m_rootPath, m_dataPath)); #endif qDebug() << "<> Updater started."; } { // delete instances tmp dirctory auto instDir = m_settings->get("InstanceDir").toString(); const QString tempRoot = FS::PathCombine(instDir, ".tmp"); FS::deletePath(tempRoot); } if (!m_urlsToImport.isEmpty()) { qDebug() << "<> Importing from url:" << m_urlsToImport; m_mainWindow->processURLs(m_urlsToImport); } } void Application::showFatalErrorMessage(const QString& title, const QString& content) { m_status = Application::Failed; auto dialog = CustomMessageBox::selectable(nullptr, title, content, QMessageBox::Critical); dialog->exec(); } Application::~Application() { // Shut down logger by setting the logger function to nothing qInstallMessageHandler(nullptr); #if defined Q_OS_WIN32 // Detach from Windows console if (consoleAttached) { fclose(stdout); fclose(stdin); fclose(stderr); FreeConsole(); } #endif } void Application::messageReceived(const QByteArray& message) { ApplicationMessage received; received.parse(message); auto& command = received.command; if (status() != Initialized) { bool isLoginAtempt = false; if (command == "import") { QString url = received.args["url"]; isLoginAtempt = !url.isEmpty() && normalizeImportUrl(url).scheme() == BuildConfig.LAUNCHER_APP_BINARY_NAME; } if (!isLoginAtempt) { qDebug() << "Received message" << message << "while still initializing. It will be ignored."; return; } } if (command == "activate") { showMainWindow(); } else if (command == "import") { QString url = received.args["url"]; if (url.isEmpty()) { qWarning() << "Received" << command << "message without a zip path/URL."; return; } m_mainWindow->processURLs({ normalizeImportUrl(url) }); } else if (command == "launch") { QString id = received.args["id"]; QString server = received.args["server"]; QString world = received.args["world"]; QString profile = received.args["profile"]; bool offline = received.args["offline_enabled"] == "true"; QString offlineName = received.args["offline_name"]; InstancePtr instance; if (!id.isEmpty()) { instance = instances()->getInstanceById(id); if (!instance) { qWarning() << "Launch command requires an valid instance ID. " << id << "resolves to nothing."; return; } } else { qWarning() << "Launch command called without an instance ID..."; return; } MinecraftTarget::Ptr serverObject = nullptr; if (!server.isEmpty()) { serverObject = std::make_shared<MinecraftTarget>(MinecraftTarget::parse(server, false)); } else if (!world.isEmpty()) { serverObject = std::make_shared<MinecraftTarget>(MinecraftTarget::parse(world, true)); } MinecraftAccountPtr accountObject; if (!profile.isEmpty()) { accountObject = accounts()->getAccountByProfileName(profile); if (!accountObject) { qWarning() << "Launch command requires the specified profile to be valid. " << profile << "does not resolve to any account."; return; } } launch(instance, !offline, false, serverObject, accountObject, offlineName); } else { qWarning() << "Received invalid message" << message; } } std::shared_ptr<TranslationsModel> Application::translations() { return m_translations; } std::shared_ptr<JavaInstallList> Application::javalist() { if (!m_javalist) { m_javalist.reset(new JavaInstallList()); } return m_javalist; } QIcon Application::getThemedIcon(const QString& name) { if (name == "logo") { return QIcon(":/" + BuildConfig.LAUNCHER_SVGFILENAME); } return QIcon::fromTheme(name); } bool Application::openJsonEditor(const QString& filename) { const QString file = QDir::current().absoluteFilePath(filename); if (m_settings->get("JsonEditor").toString().isEmpty()) { return DesktopServices::openUrl(QUrl::fromLocalFile(file)); } else { // return DesktopServices::openFile(m_settings->get("JsonEditor").toString(), file); return DesktopServices::run(m_settings->get("JsonEditor").toString(), { file }); } } bool Application::launch(InstancePtr instance, bool online, bool demo, MinecraftTarget::Ptr targetToJoin, MinecraftAccountPtr accountToUse, const QString& offlineName) { if (m_updateRunning) { qDebug() << "Cannot launch instances while an update is running. Please try again when updates are completed."; } else if (instance->canLaunch()) { QMutexLocker locker(&m_instanceExtrasMutex); auto& extras = m_instanceExtras[instance->id()]; auto window = extras.window; if (window) { if (!window->saveAll()) { return false; } } auto& controller = extras.controller; controller.reset(new LaunchController()); controller->setInstance(instance); controller->setOnline(online); controller->setDemo(demo); controller->setProfiler(profilers().value(instance->settings()->get("Profiler").toString(), nullptr).get()); controller->setTargetToJoin(targetToJoin); controller->setAccountToUse(accountToUse); controller->setOfflineName(offlineName); if (window) { controller->setParentWidget(window); } else if (m_mainWindow) { controller->setParentWidget(m_mainWindow); } connect(controller.get(), &LaunchController::succeeded, this, &Application::controllerSucceeded); connect(controller.get(), &LaunchController::failed, this, &Application::controllerFailed); connect(controller.get(), &LaunchController::aborted, this, [this] { controllerFailed(tr("Aborted")); }); addRunningInstance(); QMetaObject::invokeMethod(controller.get(), &Task::start, Qt::QueuedConnection); return true; } else if (instance->isRunning()) { showInstanceWindow(instance, "console"); return true; } else if (instance->canEdit()) { showInstanceWindow(instance); return true; } return false; } bool Application::kill(InstancePtr instance) { if (!instance->isRunning()) { qWarning() << "Attempted to kill instance" << instance->id() << ", which isn't running."; return false; } QMutexLocker locker(&m_instanceExtrasMutex); auto& extras = m_instanceExtras[instance->id()]; // NOTE: copy of the shared pointer keeps it alive auto controller = extras.controller; locker.unlock(); if (controller) { return controller->abort(); } return true; } void Application::closeCurrentWindow() { if (focusWindow()) focusWindow()->close(); } void Application::addRunningInstance() { m_runningInstances++; if (m_runningInstances == 1) { emit updateAllowedChanged(false); } } void Application::subRunningInstance() { if (m_runningInstances == 0) { qCritical() << "Something went really wrong and we now have less than 0 running instances... WTF"; return; } m_runningInstances--; if (m_runningInstances == 0) { emit updateAllowedChanged(true); } } bool Application::shouldExitNow() const { return m_runningInstances == 0 && m_openWindows == 0; } bool Application::updatesAreAllowed() { return m_runningInstances == 0; } void Application::updateIsRunning(bool running) { m_updateRunning = running; } void Application::controllerSucceeded() { auto controller = qobject_cast<LaunchController*>(QObject::sender()); if (!controller) return; auto id = controller->id(); QMutexLocker locker(&m_instanceExtrasMutex); auto& extras = m_instanceExtras[id]; // on success, do... if (controller->instance()->settings()->get("AutoCloseConsole").toBool()) { if (extras.window) { QMetaObject::invokeMethod(extras.window, &QWidget::close, Qt::QueuedConnection); } } extras.controller.reset(); subRunningInstance(); // quit when there are no more windows. if (shouldExitNow()) { m_status = Status::Succeeded; exit(0); } } void Application::controllerFailed(const QString& error) { Q_UNUSED(error); auto controller = qobject_cast<LaunchController*>(QObject::sender()); if (!controller) return; auto id = controller->id(); QMutexLocker locker(&m_instanceExtrasMutex); auto& extras = m_instanceExtras[id]; // on failure, do... nothing extras.controller.reset(); subRunningInstance(); // quit when there are no more windows. if (shouldExitNow()) { m_status = Status::Failed; exit(1); } } void Application::ShowGlobalSettings(class QWidget* parent, QString open_page) { if (!m_globalSettingsProvider) { return; } emit globalSettingsAboutToOpen(); { SettingsObject::Lock lock(APPLICATION->settings()); PageDialog dlg(m_globalSettingsProvider.get(), open_page, parent); dlg.exec(); } emit globalSettingsClosed(); } MainWindow* Application::showMainWindow(bool minimized) { if (m_mainWindow) { m_mainWindow->setWindowState(m_mainWindow->windowState() & ~Qt::WindowMinimized); m_mainWindow->raise(); m_mainWindow->activateWindow(); } else { m_mainWindow = new MainWindow(); m_mainWindow->restoreState(QByteArray::fromBase64(APPLICATION->settings()->get("MainWindowState").toByteArray())); m_mainWindow->restoreGeometry(QByteArray::fromBase64(APPLICATION->settings()->get("MainWindowGeometry").toByteArray())); if (minimized) { m_mainWindow->showMinimized(); } else { m_mainWindow->show(); } m_mainWindow->checkInstancePathForProblems(); connect(this, &Application::updateAllowedChanged, m_mainWindow, &MainWindow::updatesAllowedChanged); connect(m_mainWindow, &MainWindow::isClosing, this, &Application::on_windowClose); m_openWindows++; } return m_mainWindow; } InstanceWindow* Application::showInstanceWindow(InstancePtr instance, QString page) { if (!instance) return nullptr; auto id = instance->id(); QMutexLocker locker(&m_instanceExtrasMutex); auto& extras = m_instanceExtras[id]; auto& window = extras.window; if (window) { // If the window is minimized on macOS or Windows, activate and bring it up #ifdef Q_OS_MACOS if (window->isMinimized()) { window->setWindowState(window->windowState() & ~Qt::WindowMinimized); } #elif defined(Q_OS_WIN) if (window->isMinimized()) { window->showNormal(); } #endif window->raise(); window->activateWindow(); } else { window = new InstanceWindow(instance); m_openWindows++; connect(window, &InstanceWindow::isClosing, this, &Application::on_windowClose); } if (!page.isEmpty()) { window->selectPage(page); } if (extras.controller) { extras.controller->setParentWidget(window); } return window; } void Application::on_windowClose() { m_openWindows--; auto instWindow = qobject_cast<InstanceWindow*>(QObject::sender()); if (instWindow) { QMutexLocker locker(&m_instanceExtrasMutex); auto& extras = m_instanceExtras[instWindow->instanceId()]; extras.window = nullptr; if (extras.controller) { extras.controller->setParentWidget(m_mainWindow); } } auto mainWindow = qobject_cast<MainWindow*>(QObject::sender()); if (mainWindow) { m_mainWindow = nullptr; } // quit when there are no more windows. if (shouldExitNow()) { exit(0); } } void Application::updateProxySettings(QString proxyTypeStr, QString addr, int port, QString user, QString password) { // Set the application proxy settings. if (proxyTypeStr == "SOCKS5") { QNetworkProxy::setApplicationProxy(QNetworkProxy(QNetworkProxy::Socks5Proxy, addr, port, user, password)); } else if (proxyTypeStr == "HTTP") { QNetworkProxy::setApplicationProxy(QNetworkProxy(QNetworkProxy::HttpProxy, addr, port, user, password)); } else if (proxyTypeStr == "None") { // If we have no proxy set, set no proxy and return. QNetworkProxy::setApplicationProxy(QNetworkProxy(QNetworkProxy::NoProxy)); } else { // If we have "Default" selected, set Qt to use the system proxy settings. QNetworkProxyFactory::setUseSystemConfiguration(true); } qDebug() << "Detecting proxy settings..."; QNetworkProxy proxy = QNetworkProxy::applicationProxy(); m_network->setProxy(proxy); QString proxyDesc; if (proxy.type() == QNetworkProxy::NoProxy) { qDebug() << "Using no proxy is an option!"; return; } switch (proxy.type()) { case QNetworkProxy::DefaultProxy: proxyDesc = "Default proxy: "; break; case QNetworkProxy::Socks5Proxy: proxyDesc = "Socks5 proxy: "; break; case QNetworkProxy::HttpProxy: proxyDesc = "HTTP proxy: "; break; case QNetworkProxy::HttpCachingProxy: proxyDesc = "HTTP caching: "; break; case QNetworkProxy::FtpCachingProxy: proxyDesc = "FTP caching: "; break; default: proxyDesc = "DERP proxy: "; break; } proxyDesc += QString("%1:%2").arg(proxy.hostName()).arg(proxy.port()); qDebug() << proxyDesc; } shared_qobject_ptr<HttpMetaCache> Application::metacache() { return m_metacache; } shared_qobject_ptr<QNetworkAccessManager> Application::network() { return m_network; } shared_qobject_ptr<Meta::Index> Application::metadataIndex() { if (!m_metadataIndex) { m_metadataIndex.reset(new Meta::Index()); } return m_metadataIndex; } void Application::updateCapabilities() { m_capabilities = None; if (!getMSAClientID().isEmpty()) m_capabilities |= SupportsMSA; if (!getFlameAPIKey().isEmpty()) m_capabilities |= SupportsFlame; #ifdef Q_OS_LINUX if (gamemode_query_status() >= 0) m_capabilities |= SupportsGameMode; if (!MangoHud::getLibraryString().isEmpty()) m_capabilities |= SupportsMangoHud; #endif } void Application::detectLibraries() { #ifdef Q_OS_LINUX m_detectedGLFWPath = MangoHud::findLibrary(BuildConfig.GLFW_LIBRARY_NAME); m_detectedOpenALPath = MangoHud::findLibrary(BuildConfig.OPENAL_LIBRARY_NAME); qDebug() << "Detected native libraries:" << m_detectedGLFWPath << m_detectedOpenALPath; #endif } QString Application::getJarPath(QString jarFile) { QStringList potentialPaths = { #if defined(Q_OS_LINUX) || defined(Q_OS_FREEBSD) || defined(Q_OS_OPENBSD) FS::PathCombine(m_rootPath, "share", BuildConfig.LAUNCHER_NAME), #endif FS::PathCombine(m_rootPath, "jars"), FS::PathCombine(applicationDirPath(), "jars"), FS::PathCombine(applicationDirPath(), "..", "jars") // from inside build dir, for debuging }; for (QString p : potentialPaths) { QString jarPath = FS::PathCombine(p, jarFile); if (QFileInfo(jarPath).isFile()) return jarPath; } return {}; } QString Application::getMSAClientID() { QString clientIDOverride = m_settings->get("MSAClientIDOverride").toString(); if (!clientIDOverride.isEmpty()) { return clientIDOverride; } return BuildConfig.MSA_CLIENT_ID; } QString Application::getFlameAPIKey() { QString keyOverride = m_settings->get("FlameKeyOverride").toString(); if (!keyOverride.isEmpty()) { return keyOverride; } return BuildConfig.FLAME_API_KEY; } QString Application::getModrinthAPIToken() { QString tokenOverride = m_settings->get("ModrinthToken").toString(); if (!tokenOverride.isEmpty()) return tokenOverride; return QString(); } QString Application::getUserAgent() { QString uaOverride = m_settings->get("UserAgentOverride").toString(); if (!uaOverride.isEmpty()) { return uaOverride.replace("$LAUNCHER_VER", BuildConfig.printableVersionString()); } return BuildConfig.USER_AGENT; } QString Application::getUserAgentUncached() { QString uaOverride = m_settings->get("UserAgentOverride").toString(); if (!uaOverride.isEmpty()) { uaOverride += " (Uncached)"; return uaOverride.replace("$LAUNCHER_VER", BuildConfig.printableVersionString()); } return BuildConfig.USER_AGENT_UNCACHED; } bool Application::handleDataMigration(const QString& currentData, const QString& oldData, const QString& name, const QString& configFile) const { QString nomigratePath = FS::PathCombine(currentData, name + "_nomigrate.txt"); QStringList configPaths = { FS::PathCombine(oldData, configFile), FS::PathCombine(oldData, BuildConfig.LAUNCHER_CONFIGFILE) }; QLocale locale; // Is there a valid config at the old location? bool configExists = false; for (QString configPath : configPaths) { configExists |= QFileInfo::exists(configPath); } if (!configExists || QFileInfo::exists(nomigratePath)) { qDebug() << "<> No migration needed from" << name; return false; } QString message; bool currentExists = QFileInfo::exists(FS::PathCombine(currentData, BuildConfig.LAUNCHER_CONFIGFILE)); if (currentExists) { message = tr("Old data from %1 was found, but you already have existing data for %2. Sadly you will need to migrate yourself. Do " "you want to be reminded of the pending data migration next time you start %2?") .arg(name, BuildConfig.LAUNCHER_DISPLAYNAME); } else { message = tr("It looks like you used %1 before. Do you want to migrate your data to the new location of %2?") .arg(name, BuildConfig.LAUNCHER_DISPLAYNAME); QFileInfo logInfo(FS::PathCombine(oldData, name + "-0.log")); if (logInfo.exists()) { QString lastModified = logInfo.lastModified().toString(locale.dateFormat()); message = tr("It looks like you used %1 on %2 before. Do you want to migrate your data to the new location of %3?") .arg(name, lastModified, BuildConfig.LAUNCHER_DISPLAYNAME); } } QMessageBox::StandardButton askMoveDialogue = QMessageBox::question(nullptr, BuildConfig.LAUNCHER_DISPLAYNAME, message, QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes); auto setDoNotMigrate = [&nomigratePath] { QFile file(nomigratePath); file.open(QIODevice::WriteOnly); }; // create no-migrate file if user doesn't want to migrate if (askMoveDialogue != QMessageBox::Yes) { qDebug() << "<> Migration declined for" << name; setDoNotMigrate(); return currentExists; // cancel further migrations, if we already have a data directory } if (!currentExists) { // Migrate! auto matcher = std::make_shared<MultiMatcher>(); matcher->add(std::make_shared<SimplePrefixMatcher>(configFile)); matcher->add(std::make_shared<SimplePrefixMatcher>( BuildConfig.LAUNCHER_CONFIGFILE)); // it's possible that we already used that directory before matcher->add(std::make_shared<SimplePrefixMatcher>("logs/")); matcher->add(std::make_shared<SimplePrefixMatcher>("accounts.json")); matcher->add(std::make_shared<SimplePrefixMatcher>("accounts/")); matcher->add(std::make_shared<SimplePrefixMatcher>("assets/")); matcher->add(std::make_shared<SimplePrefixMatcher>("icons/")); matcher->add(std::make_shared<SimplePrefixMatcher>("instances/")); matcher->add(std::make_shared<SimplePrefixMatcher>("libraries/")); matcher->add(std::make_shared<SimplePrefixMatcher>("mods/")); matcher->add(std::make_shared<SimplePrefixMatcher>("themes/")); ProgressDialog diag; DataMigrationTask task(oldData, currentData, matcher); if (diag.execWithTask(&task)) { qDebug() << "<> Migration succeeded"; setDoNotMigrate(); } else { QString reason = task.failReason(); QMessageBox::critical(nullptr, BuildConfig.LAUNCHER_DISPLAYNAME, tr("Migration failed! Reason: %1").arg(reason)); } } else { qWarning() << "<> Migration was skipped, due to existing data"; } return true; } void Application::triggerUpdateCheck() { if (m_updater) { qDebug() << "Checking for updates."; m_updater->setBetaAllowed(false); // There are no other channels than stable m_updater->checkForUpdates(); } else { qDebug() << "Updater not available."; } } QUrl Application::normalizeImportUrl(QString const& url) { auto local_file = QFileInfo(url); if (local_file.exists()) { return QUrl::fromLocalFile(local_file.absoluteFilePath()); } else { return QUrl::fromUserInput(url); } } const QString Application::javaPath() { return m_settings->get("JavaDir").toString(); } void Application::addQSavePath(QString path) { QMutexLocker locker(&m_qsaveResourcesMutex); m_qsaveResources[path] = m_qsaveResources.value(path, 0) + 1; } void Application::removeQSavePath(QString path) { QMutexLocker locker(&m_qsaveResourcesMutex); auto count = m_qsaveResources.value(path, 0) - 1; if (count <= 0) { m_qsaveResources.remove(path); } else { m_qsaveResources[path] = count; } } bool Application::checkQSavePath(QString path) { QMutexLocker locker(&m_qsaveResourcesMutex); for (auto partialPath : m_qsaveResources.keys()) { if (path.startsWith(partialPath) && m_qsaveResources.value(partialPath, 0) > 0) { return true; } } return false; }
74,131
C++
.cpp
1,690
35.289349
140
0.628435
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,920
MessageLevel.cpp
PrismLauncher_PrismLauncher/launcher/MessageLevel.cpp
#include "MessageLevel.h" MessageLevel::Enum MessageLevel::getLevel(const QString& levelName) { if (levelName == "Launcher") return MessageLevel::Launcher; else if (levelName == "Debug") return MessageLevel::Debug; else if (levelName == "Info") return MessageLevel::Info; else if (levelName == "Message") return MessageLevel::Message; else if (levelName == "Warning") return MessageLevel::Warning; else if (levelName == "Error") return MessageLevel::Error; else if (levelName == "Fatal") return MessageLevel::Fatal; // Skip PrePost, it's not exposed to !![]! // Also skip StdErr and StdOut else return MessageLevel::Unknown; } MessageLevel::Enum MessageLevel::fromLine(QString& line) { // Level prefix int endmark = line.indexOf("]!"); if (line.startsWith("!![") && endmark != -1) { auto level = MessageLevel::getLevel(line.left(endmark).mid(3)); line = line.mid(endmark + 2); return level; } return MessageLevel::Unknown; }
1,075
C++
.cpp
33
27.030303
71
0.644231
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
true
false
true
false
28,922
FastFileIconProvider.cpp
PrismLauncher_PrismLauncher/launcher/FastFileIconProvider.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2023 TheKodeToad <TheKodeToad@proton.me> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "FastFileIconProvider.h" #include <QApplication> #include <QStyle> QIcon FastFileIconProvider::icon(const QFileInfo& info) const { #if QT_VERSION >= QT_VERSION_CHECK(6, 4, 0) bool link = info.isSymbolicLink() || info.isAlias() || info.isShortcut(); #else // in versions prior to 6.4 we don't have access to isAlias bool link = info.isSymLink(); #endif QStyle::StandardPixmap icon; if (info.isDir()) { if (link) icon = QStyle::SP_DirLinkIcon; else icon = QStyle::SP_DirIcon; } else { if (link) icon = QStyle::SP_FileLinkIcon; else icon = QStyle::SP_FileIcon; } return QApplication::style()->standardIcon(icon); }
1,479
C++
.cpp
42
31.095238
77
0.692952
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,923
BaseVersionList.cpp
PrismLauncher_PrismLauncher/launcher/BaseVersionList.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "BaseVersionList.h" #include "BaseVersion.h" BaseVersionList::BaseVersionList(QObject* parent) : QAbstractListModel(parent) {} BaseVersion::Ptr BaseVersionList::findVersion(const QString& descriptor) { for (int i = 0; i < count(); i++) { if (at(i)->descriptor() == descriptor) return at(i); } return nullptr; } BaseVersion::Ptr BaseVersionList::getRecommended() const { if (count() <= 0) return nullptr; else return at(0); } QVariant BaseVersionList::data(const QModelIndex& index, int role) const { if (!index.isValid()) return QVariant(); if (index.row() > count()) return QVariant(); BaseVersion::Ptr version = at(index.row()); switch (role) { case VersionPointerRole: return QVariant::fromValue(version); case VersionRole: return version->name(); case VersionIdRole: return version->descriptor(); case TypeRole: return version->typeString(); case JavaMajorRole: { auto major = version->name(); if (major.startsWith("java")) { major = "Java " + major.mid(4); } return major; } default: return QVariant(); } } BaseVersionList::RoleList BaseVersionList::providesRoles() const { return { VersionPointerRole, VersionRole, VersionIdRole, TypeRole }; } int BaseVersionList::rowCount(const QModelIndex& parent) const { // Return count return parent.isValid() ? 0 : count(); } int BaseVersionList::columnCount(const QModelIndex& parent) const { return parent.isValid() ? 0 : 1; } QHash<int, QByteArray> BaseVersionList::roleNames() const { QHash<int, QByteArray> roles = QAbstractListModel::roleNames(); roles.insert(VersionRole, "version"); roles.insert(VersionIdRole, "versionId"); roles.insert(ParentVersionRole, "parentGameVersion"); roles.insert(RecommendedRole, "recommended"); roles.insert(LatestRole, "latest"); roles.insert(TypeRole, "type"); roles.insert(BranchRole, "branch"); roles.insert(PathRole, "path"); roles.insert(JavaNameRole, "javaName"); roles.insert(CPUArchitectureRole, "architecture"); roles.insert(JavaMajorRole, "javaMajor"); return roles; }
3,823
C++
.cpp
108
30.796296
81
0.68821
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
28,924
VersionProxyModel.cpp
PrismLauncher_PrismLauncher/launcher/VersionProxyModel.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * Copyright (C) 2023 TheKodeToad <TheKodeToad@proton.me> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 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 "VersionProxyModel.h" #include <Version.h> #include <meta/VersionList.h> #include <QPixmapCache> #include <QSortFilterProxyModel> #include "Application.h" class VersionFilterModel : public QSortFilterProxyModel { Q_OBJECT public: VersionFilterModel(VersionProxyModel* parent) : QSortFilterProxyModel(parent) { m_parent = parent; setSortRole(BaseVersionList::SortRole); sort(0, Qt::DescendingOrder); } bool filterAcceptsRow(int source_row, const QModelIndex& source_parent) const { const auto& filters = m_parent->filters(); const QString& search = m_parent->search(); const QModelIndex idx = sourceModel()->index(source_row, 0, source_parent); if (!search.isEmpty() && !sourceModel()->data(idx, BaseVersionList::VersionRole).toString().contains(search, Qt::CaseInsensitive)) return false; for (auto it = filters.begin(); it != filters.end(); ++it) { auto data = sourceModel()->data(idx, it.key()); auto match = data.toString(); if (!it.value()->accepts(match)) { return false; } } return true; } void filterChanged() { invalidateFilter(); } private: VersionProxyModel* m_parent; }; VersionProxyModel::VersionProxyModel(QObject* parent) : QAbstractProxyModel(parent) { filterModel = new VersionFilterModel(this); connect(filterModel, &QAbstractItemModel::dataChanged, this, &VersionProxyModel::sourceDataChanged); connect(filterModel, &QAbstractItemModel::rowsAboutToBeInserted, this, &VersionProxyModel::sourceRowsAboutToBeInserted); connect(filterModel, &QAbstractItemModel::rowsInserted, this, &VersionProxyModel::sourceRowsInserted); connect(filterModel, &QAbstractItemModel::rowsAboutToBeRemoved, this, &VersionProxyModel::sourceRowsAboutToBeRemoved); connect(filterModel, &QAbstractItemModel::rowsRemoved, this, &VersionProxyModel::sourceRowsRemoved); // FIXME: implement when needed /* connect(replacing, &QAbstractItemModel::rowsAboutToBeMoved, this, &VersionProxyModel::sourceRowsAboutToBeMoved); connect(replacing, &QAbstractItemModel::rowsMoved, this, &VersionProxyModel::sourceRowsMoved); connect(replacing, &QAbstractItemModel::layoutAboutToBeChanged, this, &VersionProxyModel::sourceLayoutAboutToBeChanged); connect(replacing, &QAbstractItemModel::layoutChanged, this, &VersionProxyModel::sourceLayoutChanged); */ connect(filterModel, &QAbstractItemModel::modelAboutToBeReset, this, &VersionProxyModel::sourceAboutToBeReset); connect(filterModel, &QAbstractItemModel::modelReset, this, &VersionProxyModel::sourceReset); QAbstractProxyModel::setSourceModel(filterModel); } QVariant VersionProxyModel::headerData(int section, Qt::Orientation orientation, int role) const { if (section < 0 || section >= m_columns.size()) return QVariant(); if (orientation != Qt::Horizontal) return QVariant(); auto column = m_columns[section]; if (role == Qt::DisplayRole) { switch (column) { case Name: return tr("Version"); case ParentVersion: return tr("Minecraft"); // FIXME: this should come from metadata case Branch: return tr("Branch"); case Type: return tr("Type"); case CPUArchitecture: return tr("Architecture"); case Path: return tr("Path"); case JavaName: return tr("Java Name"); case JavaMajor: return tr("Major Version"); case Time: return tr("Released"); } } else if (role == Qt::ToolTipRole) { switch (column) { case Name: return tr("The name of the version."); case ParentVersion: return tr("Minecraft version"); // FIXME: this should come from metadata case Branch: return tr("The version's branch"); case Type: return tr("The version's type"); case CPUArchitecture: return tr("CPU Architecture"); case Path: return tr("Filesystem path to this version"); case JavaName: return tr("The alternative name of the Java version"); case JavaMajor: return tr("The Java major version"); case Time: return tr("Release date of this version"); } } return QVariant(); } QVariant VersionProxyModel::data(const QModelIndex& index, int role) const { if (!index.isValid()) { return QVariant(); } auto column = m_columns[index.column()]; auto parentIndex = mapToSource(index); switch (role) { case Qt::DisplayRole: { switch (column) { case Name: { QString version = sourceModel()->data(parentIndex, BaseVersionList::VersionRole).toString(); if (version == m_currentVersion) { return tr("%1 (installed)").arg(version); } return version; } case ParentVersion: return sourceModel()->data(parentIndex, BaseVersionList::ParentVersionRole); case Branch: return sourceModel()->data(parentIndex, BaseVersionList::BranchRole); case Type: return sourceModel()->data(parentIndex, BaseVersionList::TypeRole); case CPUArchitecture: return sourceModel()->data(parentIndex, BaseVersionList::CPUArchitectureRole); case Path: return sourceModel()->data(parentIndex, BaseVersionList::PathRole); case JavaName: return sourceModel()->data(parentIndex, BaseVersionList::JavaNameRole); case JavaMajor: return sourceModel()->data(parentIndex, BaseVersionList::JavaMajorRole); case Time: return sourceModel()->data(parentIndex, Meta::VersionList::TimeRole).toDate(); default: return QVariant(); } } case Qt::ToolTipRole: { if (column == Name && hasRecommended) { auto value = sourceModel()->data(parentIndex, BaseVersionList::RecommendedRole); if (value.toBool()) { return tr("Recommended"); } else if (hasLatest) { auto value = sourceModel()->data(parentIndex, BaseVersionList::LatestRole); if (value.toBool()) { return tr("Latest"); } } } else { return sourceModel()->data(parentIndex, BaseVersionList::VersionIdRole); } } case Qt::DecorationRole: { switch (column) { case Name: { if (hasRecommended) { auto recommenced = sourceModel()->data(parentIndex, BaseVersionList::RecommendedRole); if (recommenced.toBool()) { return APPLICATION->getThemedIcon("star"); } else if (hasLatest) { auto latest = sourceModel()->data(parentIndex, BaseVersionList::LatestRole); if (latest.toBool()) { return APPLICATION->getThemedIcon("bug"); } } QPixmap pixmap; QPixmapCache::find("placeholder", &pixmap); if (!pixmap) { QPixmap px(16, 16); px.fill(Qt::transparent); QPixmapCache::insert("placeholder", px); return px; } return pixmap; } } default: { return QVariant(); } } } default: { if (roles.contains((BaseVersionList::ModelRoles)role)) { return sourceModel()->data(parentIndex, role); } return QVariant(); } } } QModelIndex VersionProxyModel::parent([[maybe_unused]] const QModelIndex& child) const { return QModelIndex(); } QModelIndex VersionProxyModel::mapFromSource(const QModelIndex& sourceIndex) const { if (sourceIndex.isValid()) { return index(sourceIndex.row(), 0); } return QModelIndex(); } QModelIndex VersionProxyModel::mapToSource(const QModelIndex& proxyIndex) const { if (proxyIndex.isValid()) { return sourceModel()->index(proxyIndex.row(), 0); } return QModelIndex(); } QModelIndex VersionProxyModel::index(int row, int column, const QModelIndex& parent) const { // no trees here... shoo if (parent.isValid()) { return QModelIndex(); } if (row < 0 || row >= sourceModel()->rowCount()) return QModelIndex(); if (column < 0 || column >= columnCount()) return QModelIndex(); return QAbstractItemModel::createIndex(row, column); } int VersionProxyModel::columnCount(const QModelIndex& parent) const { return parent.isValid() ? 0 : m_columns.size(); } int VersionProxyModel::rowCount(const QModelIndex& parent) const { if (sourceModel()) { return sourceModel()->rowCount(parent); } return 0; } void VersionProxyModel::sourceDataChanged(const QModelIndex& source_top_left, const QModelIndex& source_bottom_right) { if (source_top_left.parent() != source_bottom_right.parent()) return; // whole row is getting changed auto topLeft = createIndex(source_top_left.row(), 0); auto bottomRight = createIndex(source_bottom_right.row(), columnCount() - 1); emit dataChanged(topLeft, bottomRight); } void VersionProxyModel::setSourceModel(QAbstractItemModel* replacingRaw) { auto replacing = dynamic_cast<BaseVersionList*>(replacingRaw); beginResetModel(); m_columns.clear(); if (!replacing) { roles.clear(); filterModel->setSourceModel(replacing); return; } roles = replacing->providesRoles(); if (roles.contains(BaseVersionList::VersionRole)) { m_columns.push_back(Name); } /* if(roles.contains(BaseVersionList::ParentVersionRole)) { m_columns.push_back(ParentVersion); } */ if (roles.contains(BaseVersionList::CPUArchitectureRole)) { m_columns.push_back(CPUArchitecture); } if (roles.contains(BaseVersionList::PathRole)) { m_columns.push_back(Path); } if (roles.contains(BaseVersionList::JavaNameRole)) { m_columns.push_back(JavaName); } if (roles.contains(BaseVersionList::JavaMajorRole)) { m_columns.push_back(JavaMajor); } if (roles.contains(Meta::VersionList::TimeRole)) { m_columns.push_back(Time); } if (roles.contains(BaseVersionList::BranchRole)) { m_columns.push_back(Branch); } if (roles.contains(BaseVersionList::TypeRole)) { m_columns.push_back(Type); } if (roles.contains(BaseVersionList::RecommendedRole)) { hasRecommended = true; } if (roles.contains(BaseVersionList::LatestRole)) { hasLatest = true; } filterModel->setSourceModel(replacing); endResetModel(); } QModelIndex VersionProxyModel::getRecommended() const { if (!roles.contains(BaseVersionList::RecommendedRole)) { return index(0, 0); } int recommended = 0; for (int i = 0; i < rowCount(); i++) { auto value = sourceModel()->data(mapToSource(index(i, 0)), BaseVersionList::RecommendedRole); if (value.toBool()) { recommended = i; } } return index(recommended, 0); } QModelIndex VersionProxyModel::getVersion(const QString& version) const { int found = -1; for (int i = 0; i < rowCount(); i++) { auto value = sourceModel()->data(mapToSource(index(i, 0)), BaseVersionList::VersionRole); if (value.toString() == version) { found = i; } } if (found == -1) { return QModelIndex(); } return index(found, 0); } void VersionProxyModel::clearFilters() { m_filters.clear(); m_search.clear(); filterModel->filterChanged(); } void VersionProxyModel::setFilter(const BaseVersionList::ModelRoles column, Filter* f) { m_filters[column].reset(f); filterModel->filterChanged(); } void VersionProxyModel::setSearch(const QString& search) { m_search = search; filterModel->filterChanged(); } const VersionProxyModel::FilterMap& VersionProxyModel::filters() const { return m_filters; } const QString& VersionProxyModel::search() const { return m_search; } void VersionProxyModel::sourceAboutToBeReset() { beginResetModel(); } void VersionProxyModel::sourceReset() { endResetModel(); } void VersionProxyModel::sourceRowsAboutToBeInserted(const QModelIndex& parent, int first, int last) { beginInsertRows(parent, first, last); } void VersionProxyModel::sourceRowsInserted([[maybe_unused]] const QModelIndex& parent, [[maybe_unused]] int first, [[maybe_unused]] int last) { endInsertRows(); } void VersionProxyModel::sourceRowsAboutToBeRemoved(const QModelIndex& parent, int first, int last) { beginRemoveRows(parent, first, last); } void VersionProxyModel::sourceRowsRemoved([[maybe_unused]] const QModelIndex& parent, [[maybe_unused]] int first, [[maybe_unused]] int last) { endRemoveRows(); } void VersionProxyModel::setCurrentVersion(const QString& version) { m_currentVersion = version; } #include "VersionProxyModel.moc"
15,638
C++
.cpp
413
29.457627
140
0.626852
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
28,925
BaseInstance.cpp
PrismLauncher_PrismLauncher/launcher/BaseInstance.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * Copyright (c) 2022 Jamie Mansfield <jmansfield@cadixdev.org> * Copyright (C) 2023 TheKodeToad <TheKodeToad@proton.me> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "BaseInstance.h" #include <QDebug> #include <QDir> #include <QFileInfo> #include <QJsonDocument> #include <QJsonObject> #include <QRegularExpression> #include "settings/INISettingsObject.h" #include "settings/OverrideSetting.h" #include "settings/Setting.h" #include "BuildConfig.h" #include "Commandline.h" #include "FileSystem.h" BaseInstance::BaseInstance(SettingsObjectPtr globalSettings, SettingsObjectPtr settings, const QString& rootDir) : QObject() { m_settings = settings; m_global_settings = globalSettings; m_rootDir = rootDir; m_settings->registerSetting("name", "Unnamed Instance"); m_settings->registerSetting("iconKey", "default"); m_settings->registerSetting("notes", ""); m_settings->registerSetting("lastLaunchTime", 0); m_settings->registerSetting("totalTimePlayed", 0); if (m_settings->get("totalTimePlayed").toLongLong() < 0) m_settings->reset("totalTimePlayed"); m_settings->registerSetting("lastTimePlayed", 0); m_settings->registerSetting("linkedInstances", "[]"); // Game time override auto gameTimeOverride = m_settings->registerSetting("OverrideGameTime", false); m_settings->registerOverride(globalSettings->getSetting("ShowGameTime"), gameTimeOverride); m_settings->registerOverride(globalSettings->getSetting("RecordGameTime"), gameTimeOverride); // NOTE: Sometimees InstanceType is already registered, as it was used to identify the type of // a locally stored instance if (!m_settings->getSetting("InstanceType")) m_settings->registerSetting("InstanceType", ""); // Custom Commands auto commandSetting = m_settings->registerSetting({ "OverrideCommands", "OverrideLaunchCmd" }, false); m_settings->registerOverride(globalSettings->getSetting("PreLaunchCommand"), commandSetting); m_settings->registerOverride(globalSettings->getSetting("WrapperCommand"), commandSetting); m_settings->registerOverride(globalSettings->getSetting("PostExitCommand"), commandSetting); // Console auto consoleSetting = m_settings->registerSetting("OverrideConsole", false); m_settings->registerOverride(globalSettings->getSetting("ShowConsole"), consoleSetting); m_settings->registerOverride(globalSettings->getSetting("AutoCloseConsole"), consoleSetting); m_settings->registerOverride(globalSettings->getSetting("ShowConsoleOnError"), consoleSetting); m_settings->registerOverride(globalSettings->getSetting("LogPrePostOutput"), consoleSetting); m_settings->registerPassthrough(globalSettings->getSetting("ConsoleMaxLines"), nullptr); m_settings->registerPassthrough(globalSettings->getSetting("ConsoleOverflowStop"), nullptr); // Managed Packs m_settings->registerSetting("ManagedPack", false); m_settings->registerSetting("ManagedPackType", ""); m_settings->registerSetting("ManagedPackID", ""); m_settings->registerSetting("ManagedPackName", ""); m_settings->registerSetting("ManagedPackVersionID", ""); m_settings->registerSetting("ManagedPackVersionName", ""); m_settings->registerSetting("Profiler", ""); } QString BaseInstance::getPreLaunchCommand() { return settings()->get("PreLaunchCommand").toString(); } QString BaseInstance::getWrapperCommand() { return settings()->get("WrapperCommand").toString(); } QString BaseInstance::getPostExitCommand() { return settings()->get("PostExitCommand").toString(); } bool BaseInstance::isManagedPack() const { return m_settings->get("ManagedPack").toBool(); } QString BaseInstance::getManagedPackType() const { return m_settings->get("ManagedPackType").toString(); } QString BaseInstance::getManagedPackID() const { return m_settings->get("ManagedPackID").toString(); } QString BaseInstance::getManagedPackName() const { return m_settings->get("ManagedPackName").toString(); } QString BaseInstance::getManagedPackVersionID() const { return m_settings->get("ManagedPackVersionID").toString(); } QString BaseInstance::getManagedPackVersionName() const { return m_settings->get("ManagedPackVersionName").toString(); } void BaseInstance::setManagedPack(const QString& type, const QString& id, const QString& name, const QString& versionId, const QString& version) { m_settings->set("ManagedPack", true); m_settings->set("ManagedPackType", type); m_settings->set("ManagedPackID", id); m_settings->set("ManagedPackName", name); m_settings->set("ManagedPackVersionID", versionId); m_settings->set("ManagedPackVersionName", version); } void BaseInstance::copyManagedPack(BaseInstance& other) { m_settings->set("ManagedPack", other.isManagedPack()); m_settings->set("ManagedPackType", other.getManagedPackType()); m_settings->set("ManagedPackID", other.getManagedPackID()); m_settings->set("ManagedPackName", other.getManagedPackName()); m_settings->set("ManagedPackVersionID", other.getManagedPackVersionID()); m_settings->set("ManagedPackVersionName", other.getManagedPackVersionName()); } int BaseInstance::getConsoleMaxLines() const { auto lineSetting = m_settings->getSetting("ConsoleMaxLines"); bool conversionOk = false; int maxLines = lineSetting->get().toInt(&conversionOk); if (!conversionOk) { maxLines = lineSetting->defValue().toInt(); qWarning() << "ConsoleMaxLines has nonsensical value, defaulting to" << maxLines; } return maxLines; } bool BaseInstance::shouldStopOnConsoleOverflow() const { return m_settings->get("ConsoleOverflowStop").toBool(); } QStringList BaseInstance::getLinkedInstances() const { return m_settings->get("linkedInstances").toStringList(); } void BaseInstance::setLinkedInstances(const QStringList& list) { auto linkedInstances = m_settings->get("linkedInstances").toStringList(); m_settings->set("linkedInstances", list); } void BaseInstance::addLinkedInstanceId(const QString& id) { auto linkedInstances = m_settings->get("linkedInstances").toStringList(); linkedInstances.append(id); setLinkedInstances(linkedInstances); } bool BaseInstance::removeLinkedInstanceId(const QString& id) { auto linkedInstances = m_settings->get("linkedInstances").toStringList(); int numRemoved = linkedInstances.removeAll(id); setLinkedInstances(linkedInstances); return numRemoved > 0; } bool BaseInstance::isLinkedToInstanceId(const QString& id) const { auto linkedInstances = m_settings->get("linkedInstances").toStringList(); return linkedInstances.contains(id); } void BaseInstance::iconUpdated(QString key) { if (iconKey() == key) { emit propertiesChanged(this); } } void BaseInstance::invalidate() { changeStatus(Status::Gone); qDebug() << "Instance" << id() << "has been invalidated."; } void BaseInstance::changeStatus(BaseInstance::Status newStatus) { Status status = currentStatus(); if (status != newStatus) { m_status = newStatus; emit statusChanged(status, newStatus); } } BaseInstance::Status BaseInstance::currentStatus() const { return m_status; } QString BaseInstance::id() const { return QFileInfo(instanceRoot()).fileName(); } bool BaseInstance::isRunning() const { return m_isRunning; } void BaseInstance::setRunning(bool running) { if (running == m_isRunning) return; m_isRunning = running; emit runningStatusChanged(running); } void BaseInstance::setMinecraftRunning(bool running) { if (!settings()->get("RecordGameTime").toBool()) { return; } if (running) { m_timeStarted = QDateTime::currentDateTime(); setLastLaunch(m_timeStarted.toMSecsSinceEpoch()); } else { QDateTime timeEnded = QDateTime::currentDateTime(); qint64 current = settings()->get("totalTimePlayed").toLongLong(); settings()->set("totalTimePlayed", current + m_timeStarted.secsTo(timeEnded)); settings()->set("lastTimePlayed", m_timeStarted.secsTo(timeEnded)); emit propertiesChanged(this); } } int64_t BaseInstance::totalTimePlayed() const { qint64 current = m_settings->get("totalTimePlayed").toLongLong(); if (m_isRunning) { QDateTime timeNow = QDateTime::currentDateTime(); return current + m_timeStarted.secsTo(timeNow); } return current; } int64_t BaseInstance::lastTimePlayed() const { if (m_isRunning) { QDateTime timeNow = QDateTime::currentDateTime(); return m_timeStarted.secsTo(timeNow); } return m_settings->get("lastTimePlayed").toLongLong(); } void BaseInstance::resetTimePlayed() { settings()->reset("totalTimePlayed"); settings()->reset("lastTimePlayed"); } QString BaseInstance::instanceType() const { return m_settings->get("InstanceType").toString(); } QString BaseInstance::instanceRoot() const { return m_rootDir; } SettingsObjectPtr BaseInstance::settings() { loadSpecificSettings(); return m_settings; } bool BaseInstance::canLaunch() const { return (!hasVersionBroken() && !isRunning()); } bool BaseInstance::reloadSettings() { return m_settings->reload(); } qint64 BaseInstance::lastLaunch() const { return m_settings->get("lastLaunchTime").value<qint64>(); } void BaseInstance::setLastLaunch(qint64 val) { // FIXME: if no change, do not set. setting involves saving a file. m_settings->set("lastLaunchTime", val); emit propertiesChanged(this); } void BaseInstance::setNotes(QString val) { // FIXME: if no change, do not set. setting involves saving a file. m_settings->set("notes", val); } QString BaseInstance::notes() const { return m_settings->get("notes").toString(); } void BaseInstance::setIconKey(QString val) { // FIXME: if no change, do not set. setting involves saving a file. m_settings->set("iconKey", val); emit propertiesChanged(this); } QString BaseInstance::iconKey() const { return m_settings->get("iconKey").toString(); } void BaseInstance::setName(QString val) { // FIXME: if no change, do not set. setting involves saving a file. m_settings->set("name", val); emit propertiesChanged(this); } QString BaseInstance::name() const { return m_settings->get("name").toString(); } QString BaseInstance::windowTitle() const { return BuildConfig.LAUNCHER_DISPLAYNAME + ": " + name(); } // FIXME: why is this here? move it to MinecraftInstance!!! QStringList BaseInstance::extraArguments() { return Commandline::splitArgs(settings()->get("JvmArgs").toString()); } shared_qobject_ptr<LaunchTask> BaseInstance::getLaunchTask() { return m_launchProcess; } void BaseInstance::updateRuntimeContext() { // NOOP } bool BaseInstance::isLegacy() { return traits().contains("legacyLaunch") || traits().contains("alphaLaunch"); }
12,540
C++
.cpp
350
32.182857
124
0.732965
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,926
FileIgnoreProxy.cpp
PrismLauncher_PrismLauncher/launcher/FileIgnoreProxy.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * Copyright (C) 2023 TheKodeToad <TheKodeToad@proton.me> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 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 "FileIgnoreProxy.h" #include <QDebug> #include <QFileSystemModel> #include <QSortFilterProxyModel> #include <QStack> #include <algorithm> #include "FileSystem.h" #include "SeparatorPrefixTree.h" #include "StringUtils.h" FileIgnoreProxy::FileIgnoreProxy(QString root, QObject* parent) : QSortFilterProxyModel(parent), root(root) {} // NOTE: Sadly, we have to do sorting ourselves. bool FileIgnoreProxy::lessThan(const QModelIndex& left, const QModelIndex& right) const { QFileSystemModel* fsm = qobject_cast<QFileSystemModel*>(sourceModel()); if (!fsm) { return QSortFilterProxyModel::lessThan(left, right); } bool asc = sortOrder() == Qt::AscendingOrder ? true : false; QFileInfo leftFileInfo = fsm->fileInfo(left); QFileInfo rightFileInfo = fsm->fileInfo(right); if (!leftFileInfo.isDir() && rightFileInfo.isDir()) { return !asc; } if (leftFileInfo.isDir() && !rightFileInfo.isDir()) { return asc; } // sort and proxy model breaks the original model... if (sortColumn() == 0) { return StringUtils::naturalCompare(leftFileInfo.fileName(), rightFileInfo.fileName(), Qt::CaseInsensitive) < 0; } if (sortColumn() == 1) { auto leftSize = leftFileInfo.size(); auto rightSize = rightFileInfo.size(); if ((leftSize == rightSize) || (leftFileInfo.isDir() && rightFileInfo.isDir())) { return StringUtils::naturalCompare(leftFileInfo.fileName(), rightFileInfo.fileName(), Qt::CaseInsensitive) < 0 ? asc : !asc; } return leftSize < rightSize; } return QSortFilterProxyModel::lessThan(left, right); } Qt::ItemFlags FileIgnoreProxy::flags(const QModelIndex& index) const { if (!index.isValid()) return Qt::NoItemFlags; auto sourceIndex = mapToSource(index); Qt::ItemFlags flags = sourceIndex.flags(); if (index.column() == 0) { flags |= Qt::ItemIsUserCheckable; if (sourceIndex.model()->hasChildren(sourceIndex)) { flags |= Qt::ItemIsAutoTristate; } } return flags; } QVariant FileIgnoreProxy::data(const QModelIndex& index, int role) const { QModelIndex sourceIndex = mapToSource(index); if (index.column() == 0 && role == Qt::CheckStateRole) { QFileSystemModel* fsm = qobject_cast<QFileSystemModel*>(sourceModel()); auto blockedPath = relPath(fsm->filePath(sourceIndex)); auto cover = blocked.cover(blockedPath); if (!cover.isNull()) { return QVariant(Qt::Unchecked); } else if (blocked.exists(blockedPath)) { return QVariant(Qt::PartiallyChecked); } else { return QVariant(Qt::Checked); } } return sourceIndex.data(role); } bool FileIgnoreProxy::setData(const QModelIndex& index, const QVariant& value, int role) { if (index.column() == 0 && role == Qt::CheckStateRole) { Qt::CheckState state = static_cast<Qt::CheckState>(value.toInt()); return setFilterState(index, state); } QModelIndex sourceIndex = mapToSource(index); return QSortFilterProxyModel::sourceModel()->setData(sourceIndex, value, role); } QString FileIgnoreProxy::relPath(const QString& path) const { return QDir(root).relativeFilePath(path); } bool FileIgnoreProxy::setFilterState(QModelIndex index, Qt::CheckState state) { QFileSystemModel* fsm = qobject_cast<QFileSystemModel*>(sourceModel()); if (!fsm) { return false; } QModelIndex sourceIndex = mapToSource(index); auto blockedPath = relPath(fsm->filePath(sourceIndex)); bool changed = false; if (state == Qt::Unchecked) { // blocking a path auto& node = blocked.insert(blockedPath); // get rid of all blocked nodes below node.clear(); changed = true; } else if (state == Qt::Checked || state == Qt::PartiallyChecked) { if (!blocked.remove(blockedPath)) { auto cover = blocked.cover(blockedPath); qDebug() << "Blocked by cover" << cover; // uncover blocked.remove(cover); // block all contents, except for any cover QModelIndex rootIndex = fsm->index(FS::PathCombine(root, cover)); QModelIndex doing = rootIndex; int row = 0; QStack<QModelIndex> todo; while (1) { auto node = fsm->index(row, 0, doing); if (!node.isValid()) { if (!todo.size()) { break; } else { doing = todo.pop(); row = 0; continue; } } auto relpath = relPath(fsm->filePath(node)); if (blockedPath.startsWith(relpath)) // cover found? { // continue processing cover later todo.push(node); } else { // or just block this one. blocked.insert(relpath); } row++; } } changed = true; } if (changed) { // update the thing emit dataChanged(index, index, { Qt::CheckStateRole }); // update everything above index QModelIndex up = index.parent(); while (1) { if (!up.isValid()) break; emit dataChanged(up, up, { Qt::CheckStateRole }); up = up.parent(); } // and everything below the index QModelIndex doing = index; int row = 0; QStack<QModelIndex> todo; while (1) { auto node = this->index(row, 0, doing); if (!node.isValid()) { if (!todo.size()) { break; } else { doing = todo.pop(); row = 0; continue; } } emit dataChanged(node, node, { Qt::CheckStateRole }); todo.push(node); row++; } // siblings and unrelated nodes are ignored } return true; } bool FileIgnoreProxy::shouldExpand(QModelIndex index) { QModelIndex sourceIndex = mapToSource(index); QFileSystemModel* fsm = qobject_cast<QFileSystemModel*>(sourceModel()); if (!fsm) { return false; } auto blockedPath = relPath(fsm->filePath(sourceIndex)); auto found = blocked.find(blockedPath); if (found) { return !found->leaf(); } return false; } void FileIgnoreProxy::setBlockedPaths(QStringList paths) { beginResetModel(); blocked.clear(); blocked.insert(paths); endResetModel(); } bool FileIgnoreProxy::filterAcceptsColumn(int source_column, const QModelIndex& source_parent) const { Q_UNUSED(source_parent) // adjust the columns you want to filter out here // return false for those that will be hidden if (source_column == 2 || source_column == 3) return false; return true; } bool FileIgnoreProxy::filterAcceptsRow(int sourceRow, const QModelIndex& sourceParent) const { QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent); QFileSystemModel* fsm = qobject_cast<QFileSystemModel*>(sourceModel()); auto fileInfo = fsm->fileInfo(index); return !ignoreFile(fileInfo); } bool FileIgnoreProxy::ignoreFile(QFileInfo fileInfo) const { return m_ignoreFiles.contains(fileInfo.fileName()) || m_ignoreFilePaths.covers(relPath(fileInfo.absoluteFilePath())); } bool FileIgnoreProxy::filterFile(const QString& fileName) const { return blocked.covers(fileName) || ignoreFile(QFileInfo(QDir(root), fileName)); }
9,302
C++
.cpp
249
30.220884
136
0.634943
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,927
Filter.cpp
PrismLauncher_PrismLauncher/launcher/Filter.cpp
#include "Filter.h" ContainsFilter::ContainsFilter(const QString& pattern) : pattern(pattern) {} bool ContainsFilter::accepts(const QString& value) { return value.contains(pattern); } ExactFilter::ExactFilter(const QString& pattern) : pattern(pattern) {} bool ExactFilter::accepts(const QString& value) { return value == pattern; } ExactIfPresentFilter::ExactIfPresentFilter(const QString& pattern) : pattern(pattern) {} bool ExactIfPresentFilter::accepts(const QString& value) { return value.isEmpty() || value == pattern; } RegexpFilter::RegexpFilter(const QString& regexp, bool invert) : invert(invert) { pattern.setPattern(regexp); pattern.optimize(); } bool RegexpFilter::accepts(const QString& value) { auto match = pattern.match(value); bool matched = match.hasMatch(); return invert ? (!matched) : (matched); } ExactListFilter::ExactListFilter(const QStringList& pattern) : m_pattern(pattern) {} bool ExactListFilter::accepts(const QString& value) { return m_pattern.isEmpty() || m_pattern.contains(value); }
1,057
C++
.cpp
32
30.78125
88
0.761019
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,928
MMCZip.cpp
PrismLauncher_PrismLauncher/launcher/MMCZip.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * Copyright (c) 2023-2024 Trial97 <alexandru.tripon97@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 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 "MMCZip.h" #include <quazip/quazip.h> #include <quazip/quazipdir.h> #include <quazip/quazipfile.h> #include "FileSystem.h" #include <QCoreApplication> #include <QDebug> #include <QFileInfo> #include <QUrl> #if defined(LAUNCHER_APPLICATION) #include <QtConcurrentRun> #endif namespace MMCZip { // ours bool mergeZipFiles(QuaZip* into, QFileInfo from, QSet<QString>& contained, const FilterFunction& filter) { QuaZip modZip(from.filePath()); modZip.open(QuaZip::mdUnzip); QuaZipFile fileInsideMod(&modZip); QuaZipFile zipOutFile(into); for (bool more = modZip.goToFirstFile(); more; more = modZip.goToNextFile()) { QString filename = modZip.getCurrentFileName(); if (filter && !filter(filename)) { qDebug() << "Skipping file " << filename << " from " << from.fileName() << " - filtered"; continue; } if (contained.contains(filename)) { qDebug() << "Skipping already contained file " << filename << " from " << from.fileName(); continue; } contained.insert(filename); if (!fileInsideMod.open(QIODevice::ReadOnly)) { qCritical() << "Failed to open " << filename << " from " << from.fileName(); return false; } QuaZipNewInfo info_out(fileInsideMod.getActualFileName()); if (!zipOutFile.open(QIODevice::WriteOnly, info_out)) { qCritical() << "Failed to open " << filename << " in the jar"; fileInsideMod.close(); return false; } if (!JlCompress::copyData(fileInsideMod, zipOutFile)) { zipOutFile.close(); fileInsideMod.close(); qCritical() << "Failed to copy data of " << filename << " into the jar"; return false; } zipOutFile.close(); fileInsideMod.close(); } return true; } bool compressDirFiles(QuaZip* zip, QString dir, QFileInfoList files, bool followSymlinks) { QDir directory(dir); if (!directory.exists()) return false; for (auto e : files) { auto filePath = directory.relativeFilePath(e.absoluteFilePath()); auto srcPath = e.absoluteFilePath(); if (followSymlinks) { if (e.isSymLink()) { srcPath = e.symLinkTarget(); } else { srcPath = e.canonicalFilePath(); } } if (!JlCompress::compressFile(zip, srcPath, filePath)) return false; } return true; } bool compressDirFiles(QString fileCompressed, QString dir, QFileInfoList files, bool followSymlinks) { QuaZip zip(fileCompressed); zip.setUtf8Enabled(true); QDir().mkpath(QFileInfo(fileCompressed).absolutePath()); if (!zip.open(QuaZip::mdCreate)) { FS::deletePath(fileCompressed); return false; } auto result = compressDirFiles(&zip, dir, files, followSymlinks); zip.close(); if (zip.getZipError() != 0) { FS::deletePath(fileCompressed); return false; } return result; } #if defined(LAUNCHER_APPLICATION) // ours bool createModdedJar(QString sourceJarPath, QString targetJarPath, const QList<Mod*>& mods) { QuaZip zipOut(targetJarPath); zipOut.setUtf8Enabled(true); if (!zipOut.open(QuaZip::mdCreate)) { FS::deletePath(targetJarPath); qCritical() << "Failed to open the minecraft.jar for modding"; return false; } // Files already added to the jar. // These files will be skipped. QSet<QString> addedFiles; // Modify the jar // This needs to be done in reverse-order to ensure we respect the loading order of components for (auto i = mods.crbegin(); i != mods.crend(); i++) { const auto* mod = *i; // do not merge disabled mods. if (!mod->enabled()) continue; if (mod->type() == ResourceType::ZIPFILE) { if (!mergeZipFiles(&zipOut, mod->fileinfo(), addedFiles)) { zipOut.close(); FS::deletePath(targetJarPath); qCritical() << "Failed to add" << mod->fileinfo().fileName() << "to the jar."; return false; } } else if (mod->type() == ResourceType::SINGLEFILE) { // FIXME: buggy - does not work with addedFiles auto filename = mod->fileinfo(); if (!JlCompress::compressFile(&zipOut, filename.absoluteFilePath(), filename.fileName())) { zipOut.close(); FS::deletePath(targetJarPath); qCritical() << "Failed to add" << mod->fileinfo().fileName() << "to the jar."; return false; } addedFiles.insert(filename.fileName()); } else if (mod->type() == ResourceType::FOLDER) { // untested, but seems to be unused / not possible to reach // FIXME: buggy - does not work with addedFiles auto filename = mod->fileinfo(); QString what_to_zip = filename.absoluteFilePath(); QDir dir(what_to_zip); dir.cdUp(); QString parent_dir = dir.absolutePath(); auto files = QFileInfoList(); collectFileListRecursively(what_to_zip, nullptr, &files, nullptr); for (auto e : files) { if (addedFiles.contains(e.filePath())) files.removeAll(e); } if (!compressDirFiles(&zipOut, parent_dir, files)) { zipOut.close(); FS::deletePath(targetJarPath); qCritical() << "Failed to add" << mod->fileinfo().fileName() << "to the jar."; return false; } qDebug() << "Adding folder " << filename.fileName() << " from " << filename.absoluteFilePath(); } else { // Make sure we do not continue launching when something is missing or undefined... zipOut.close(); FS::deletePath(targetJarPath); qCritical() << "Failed to add unknown mod type" << mod->fileinfo().fileName() << "to the jar."; return false; } } if (!mergeZipFiles(&zipOut, QFileInfo(sourceJarPath), addedFiles, [](const QString key) { return !key.contains("META-INF"); })) { zipOut.close(); FS::deletePath(targetJarPath); qCritical() << "Failed to insert minecraft.jar contents."; return false; } // Recompress the jar zipOut.close(); if (zipOut.getZipError() != 0) { FS::deletePath(targetJarPath); qCritical() << "Failed to finalize minecraft.jar!"; return false; } return true; } #endif // ours QString findFolderOfFileInZip(QuaZip* zip, const QString& what, const QStringList& ignore_paths, const QString& root) { QuaZipDir rootDir(zip, root); for (auto&& fileName : rootDir.entryList(QDir::Files)) { if (fileName == what) return root; QCoreApplication::processEvents(); } // Recurse the search to non-ignored subfolders for (auto&& fileName : rootDir.entryList(QDir::Dirs)) { if (ignore_paths.contains(fileName)) continue; QString result = findFolderOfFileInZip(zip, what, ignore_paths, root + fileName); if (!result.isEmpty()) return result; } return {}; } // ours bool findFilesInZip(QuaZip* zip, const QString& what, QStringList& result, const QString& root) { QuaZipDir rootDir(zip, root); for (auto fileName : rootDir.entryList(QDir::Files)) { if (fileName == what) { result.append(root); return true; } } for (auto fileName : rootDir.entryList(QDir::Dirs)) { findFilesInZip(zip, what, result, root + fileName); } return !result.isEmpty(); } // ours std::optional<QStringList> extractSubDir(QuaZip* zip, const QString& subdir, const QString& target) { auto target_top_dir = QUrl::fromLocalFile(target); QStringList extracted; qDebug() << "Extracting subdir" << subdir << "from" << zip->getZipName() << "to" << target; auto numEntries = zip->getEntriesCount(); if (numEntries < 0) { qWarning() << "Failed to enumerate files in archive"; return std::nullopt; } else if (numEntries == 0) { qDebug() << "Extracting empty archives seems odd..."; return extracted; } else if (!zip->goToFirstFile()) { qWarning() << "Failed to seek to first file in zip"; return std::nullopt; } do { QString file_name = zip->getCurrentFileName(); file_name = FS::RemoveInvalidPathChars(file_name); if (!file_name.startsWith(subdir)) continue; auto relative_file_name = QDir::fromNativeSeparators(file_name.mid(subdir.size())); auto original_name = relative_file_name; // Fix subdirs/files ending with a / getting transformed into absolute paths if (relative_file_name.startsWith('/')) relative_file_name = relative_file_name.mid(1); // Fix weird "folders with a single file get squashed" thing QString sub_path; if (relative_file_name.contains('/') && !relative_file_name.endsWith('/')) { sub_path = relative_file_name.section('/', 0, -2) + '/'; FS::ensureFolderPathExists(FS::PathCombine(target, sub_path)); relative_file_name = relative_file_name.split('/').last(); } QString target_file_path; if (relative_file_name.isEmpty()) { target_file_path = target + '/'; } else { target_file_path = FS::PathCombine(target_top_dir.toLocalFile(), sub_path, relative_file_name); if (relative_file_name.endsWith('/') && !target_file_path.endsWith('/')) target_file_path += '/'; } if (!target_top_dir.isParentOf(QUrl::fromLocalFile(target_file_path))) { qWarning() << "Extracting" << relative_file_name << "was cancelled, because it was effectively outside of the target path" << target; return std::nullopt; } if (!JlCompress::extractFile(zip, "", target_file_path)) { qWarning() << "Failed to extract file" << original_name << "to" << target_file_path; JlCompress::removeFile(extracted); return std::nullopt; } extracted.append(target_file_path); auto fileInfo = QFileInfo(target_file_path); if (fileInfo.isFile()) { auto permissions = fileInfo.permissions(); auto maxPermisions = QFileDevice::Permission::ReadUser | QFileDevice::Permission::WriteUser | QFileDevice::Permission::ExeUser | QFileDevice::Permission::ReadGroup | QFileDevice::Permission::ReadOther; auto minPermisions = QFileDevice::Permission::ReadUser | QFileDevice::Permission::WriteUser; auto newPermisions = (permissions & maxPermisions) | minPermisions; if (newPermisions != permissions) { if (!QFile::setPermissions(target_file_path, newPermisions)) { qWarning() << (QObject::tr("Could not fix permissions for %1").arg(target_file_path)); } } } else if (fileInfo.isDir()) { // Ensure the folder has the minimal required permissions QFile::Permissions minimalPermissions = QFile::ReadOwner | QFile::WriteOwner | QFile::ExeOwner | QFile::ReadGroup | QFile::ExeGroup | QFile::ReadOther | QFile::ExeOther; QFile::Permissions currentPermissions = fileInfo.permissions(); if ((currentPermissions & minimalPermissions) != minimalPermissions) { if (!QFile::setPermissions(target_file_path, minimalPermissions)) { qWarning() << (QObject::tr("Could not fix permissions for %1").arg(target_file_path)); } } } qDebug() << "Extracted file" << relative_file_name << "to" << target_file_path; } while (zip->goToNextFile()); return extracted; } // ours bool extractRelFile(QuaZip* zip, const QString& file, const QString& target) { return JlCompress::extractFile(zip, file, target); } // ours std::optional<QStringList> extractDir(QString fileCompressed, QString dir) { QuaZip zip(fileCompressed); if (!zip.open(QuaZip::mdUnzip)) { // check if this is a minimum size empty zip file... QFileInfo fileInfo(fileCompressed); if (fileInfo.size() == 22) { return QStringList(); } qWarning() << "Could not open archive for unpacking:" << fileCompressed << "Error:" << zip.getZipError(); ; return std::nullopt; } return extractSubDir(&zip, "", dir); } // ours std::optional<QStringList> extractDir(QString fileCompressed, QString subdir, QString dir) { QuaZip zip(fileCompressed); if (!zip.open(QuaZip::mdUnzip)) { // check if this is a minimum size empty zip file... QFileInfo fileInfo(fileCompressed); if (fileInfo.size() == 22) { return QStringList(); } qWarning() << "Could not open archive for unpacking:" << fileCompressed << "Error:" << zip.getZipError(); ; return std::nullopt; } return extractSubDir(&zip, subdir, dir); } // ours bool extractFile(QString fileCompressed, QString file, QString target) { QuaZip zip(fileCompressed); if (!zip.open(QuaZip::mdUnzip)) { // check if this is a minimum size empty zip file... QFileInfo fileInfo(fileCompressed); if (fileInfo.size() == 22) { return true; } qWarning() << "Could not open archive for unpacking:" << fileCompressed << "Error:" << zip.getZipError(); return false; } return extractRelFile(&zip, file, target); } bool collectFileListRecursively(const QString& rootDir, const QString& subDir, QFileInfoList* files, FilterFunction excludeFilter) { QDir rootDirectory(rootDir); if (!rootDirectory.exists()) return false; QDir directory; if (subDir == nullptr) directory = rootDirectory; else directory = QDir(subDir); if (!directory.exists()) return false; // shouldn't ever happen // recurse directories QFileInfoList entries = directory.entryInfoList(QDir::AllDirs | QDir::NoDotAndDotDot | QDir::Hidden); for (const auto& e : entries) { if (!collectFileListRecursively(rootDir, e.filePath(), files, excludeFilter)) return false; } // collect files entries = directory.entryInfoList(QDir::Files); for (const auto& e : entries) { QString relativeFilePath = rootDirectory.relativeFilePath(e.absoluteFilePath()); if (excludeFilter && excludeFilter(relativeFilePath)) { qDebug() << "Skipping file " << relativeFilePath; continue; } files->append(e); // we want the original paths for compressDirFiles } return true; } #if defined(LAUNCHER_APPLICATION) void ExportToZipTask::executeTask() { setStatus("Adding files..."); setProgress(0, m_files.length()); m_build_zip_future = QtConcurrent::run(QThreadPool::globalInstance(), [this]() { return exportZip(); }); connect(&m_build_zip_watcher, &QFutureWatcher<ZipResult>::finished, this, &ExportToZipTask::finish); m_build_zip_watcher.setFuture(m_build_zip_future); } auto ExportToZipTask::exportZip() -> ZipResult { if (!m_dir.exists()) { return ZipResult(tr("Folder doesn't exist")); } if (!m_output.isOpen() && !m_output.open(QuaZip::mdCreate)) { return ZipResult(tr("Could not create file")); } for (auto fileName : m_extra_files.keys()) { if (m_build_zip_future.isCanceled()) return ZipResult(); QuaZipFile indexFile(&m_output); if (!indexFile.open(QIODevice::WriteOnly, QuaZipNewInfo(fileName))) { return ZipResult(tr("Could not create:") + fileName); } indexFile.write(m_extra_files[fileName]); } for (const QFileInfo& file : m_files) { if (m_build_zip_future.isCanceled()) return ZipResult(); auto absolute = file.absoluteFilePath(); auto relative = m_dir.relativeFilePath(absolute); setStatus("Compressing: " + relative); setProgress(m_progress + 1, m_progressTotal); if (m_follow_symlinks) { if (file.isSymLink()) absolute = file.symLinkTarget(); else absolute = file.canonicalFilePath(); } if (!m_exclude_files.contains(relative) && !JlCompress::compressFile(&m_output, absolute, m_destination_prefix + relative)) { return ZipResult(tr("Could not read and compress %1").arg(relative)); } } m_output.close(); if (m_output.getZipError() != 0) { return ZipResult(tr("A zip error occurred")); } return ZipResult(); } void ExportToZipTask::finish() { if (m_build_zip_future.isCanceled()) { FS::deletePath(m_output_path); emitAborted(); } else if (auto result = m_build_zip_future.result(); result.has_value()) { FS::deletePath(m_output_path); emitFailed(result.value()); } else { emitSucceeded(); } } bool ExportToZipTask::abort() { if (m_build_zip_future.isRunning()) { m_build_zip_future.cancel(); // NOTE: Here we don't do `emitAborted()` because it will be done when `m_build_zip_future` actually cancels, which may not occur // immediately. return true; } return false; } void ExtractZipTask::executeTask() { if (!m_input->isOpen() && !m_input->open(QuaZip::mdUnzip)) { emitFailed(tr("Unable to open supplied zip file.")); return; } m_zip_future = QtConcurrent::run(QThreadPool::globalInstance(), [this]() { return extractZip(); }); connect(&m_zip_watcher, &QFutureWatcher<ZipResult>::finished, this, &ExtractZipTask::finish); m_zip_watcher.setFuture(m_zip_future); } auto ExtractZipTask::extractZip() -> ZipResult { auto target = m_output_dir.absolutePath(); auto target_top_dir = QUrl::fromLocalFile(target); QStringList extracted; qDebug() << "Extracting subdir" << m_subdirectory << "from" << m_input->getZipName() << "to" << target; auto numEntries = m_input->getEntriesCount(); if (numEntries < 0) { return ZipResult(tr("Failed to enumerate files in archive")); } if (numEntries == 0) { logWarning(tr("Extracting empty archives seems odd...")); return ZipResult(); } if (!m_input->goToFirstFile()) { return ZipResult(tr("Failed to seek to first file in zip")); } setStatus("Extracting files..."); setProgress(0, numEntries); do { if (m_zip_future.isCanceled()) return ZipResult(); setProgress(m_progress + 1, m_progressTotal); QString file_name = m_input->getCurrentFileName(); if (!file_name.startsWith(m_subdirectory)) continue; auto relative_file_name = QDir::fromNativeSeparators(file_name.mid(m_subdirectory.size())); auto original_name = relative_file_name; setStatus("Unpacking: " + relative_file_name); // Fix subdirs/files ending with a / getting transformed into absolute paths if (relative_file_name.startsWith('/')) relative_file_name = relative_file_name.mid(1); // Fix weird "folders with a single file get squashed" thing QString sub_path; if (relative_file_name.contains('/') && !relative_file_name.endsWith('/')) { sub_path = relative_file_name.section('/', 0, -2) + '/'; FS::ensureFolderPathExists(FS::PathCombine(target, sub_path)); relative_file_name = relative_file_name.split('/').last(); } QString target_file_path; if (relative_file_name.isEmpty()) { target_file_path = target + '/'; } else { target_file_path = FS::PathCombine(target_top_dir.toLocalFile(), sub_path, relative_file_name); if (relative_file_name.endsWith('/') && !target_file_path.endsWith('/')) target_file_path += '/'; } if (!target_top_dir.isParentOf(QUrl::fromLocalFile(target_file_path))) { return ZipResult(tr("Extracting %1 was cancelled, because it was effectively outside of the target path %2") .arg(relative_file_name, target)); } if (!JlCompress::extractFile(m_input.get(), "", target_file_path)) { JlCompress::removeFile(extracted); return ZipResult(tr("Failed to extract file %1 to %2").arg(original_name, target_file_path)); } extracted.append(target_file_path); auto fileInfo = QFileInfo(target_file_path); if (fileInfo.isFile()) { auto permissions = fileInfo.permissions(); auto maxPermisions = QFileDevice::Permission::ReadUser | QFileDevice::Permission::WriteUser | QFileDevice::Permission::ExeUser | QFileDevice::Permission::ReadGroup | QFileDevice::Permission::ReadOther; auto minPermisions = QFileDevice::Permission::ReadUser | QFileDevice::Permission::WriteUser; auto newPermisions = (permissions & maxPermisions) | minPermisions; if (newPermisions != permissions) { if (!QFile::setPermissions(target_file_path, newPermisions)) { logWarning(tr("Could not fix permissions for %1").arg(target_file_path)); } } } else if (fileInfo.isDir()) { // Ensure the folder has the minimal required permissions QFile::Permissions minimalPermissions = QFile::ReadOwner | QFile::WriteOwner | QFile::ExeOwner | QFile::ReadGroup | QFile::ExeGroup | QFile::ReadOther | QFile::ExeOther; QFile::Permissions currentPermissions = fileInfo.permissions(); if ((currentPermissions & minimalPermissions) != minimalPermissions) { if (!QFile::setPermissions(target_file_path, minimalPermissions)) { logWarning(tr("Could not fix permissions for %1").arg(target_file_path)); } } } qDebug() << "Extracted file" << relative_file_name << "to" << target_file_path; } while (m_input->goToNextFile()); return ZipResult(); } void ExtractZipTask::finish() { if (m_zip_future.isCanceled()) { emitAborted(); } else if (auto result = m_zip_future.result(); result.has_value()) { emitFailed(result.value()); } else { emitSucceeded(); } } bool ExtractZipTask::abort() { if (m_zip_future.isRunning()) { m_zip_future.cancel(); // NOTE: Here we don't do `emitAborted()` because it will be done when `m_build_zip_future` actually cancels, which may not occur // immediately. return true; } return false; } #endif } // namespace MMCZip
24,805
C++
.cpp
589
34.050934
140
0.622126
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,929
InstanceCreationTask.cpp
PrismLauncher_PrismLauncher/launcher/InstanceCreationTask.cpp
#include "InstanceCreationTask.h" #include <QDebug> #include <QFile> #include "FileSystem.h" void InstanceCreationTask::executeTask() { setAbortable(true); if (updateInstance()) { emitSucceeded(); return; } // When the user aborted in the update stage. if (m_abort) { emitAborted(); return; } if (!createInstance()) { if (m_abort) return; qWarning() << "Instance creation failed!"; if (!m_error_message.isEmpty()) { qWarning() << "Reason: " << m_error_message; emitFailed(tr("Error while creating new instance:\n%1").arg(m_error_message)); } else { emitFailed(tr("Error while creating new instance.")); } return; } // If this is set, it means we're updating an instance. So, we now need to remove the // files scheduled to, and we'd better not let the user abort in the middle of it, since it'd // put the instance in an invalid state. if (shouldOverride()) { bool deleteFailed = false; setAbortable(false); setStatus(tr("Removing old conflicting files...")); qDebug() << "Removing old files"; for (const QString& path : m_files_to_remove) { if (!QFile::exists(path)) continue; qDebug() << "Removing" << path; if (!QFile::remove(path)) { qCritical() << "Could not remove" << path; deleteFailed = true; } } if (deleteFailed) { emitFailed(tr("Failed to remove old conflicting files.")); return; } } if (!m_abort) emitSucceeded(); }
1,719
C++
.cpp
53
24.09434
97
0.563823
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,930
InstanceCopyPrefs.cpp
PrismLauncher_PrismLauncher/launcher/InstanceCopyPrefs.cpp
// // Created by marcelohdez on 10/22/22. // #include "InstanceCopyPrefs.h" bool InstanceCopyPrefs::allTrue() const { return copySaves && keepPlaytime && copyGameOptions && copyResourcePacks && copyShaderPacks && copyServers && copyMods && copyScreenshots; } // Returns a single RegEx string of the selected folders/files to filter out (ex: ".minecraft/saves|.minecraft/server.dat") QString InstanceCopyPrefs::getSelectedFiltersAsRegex() const { return getSelectedFiltersAsRegex({}); } QString InstanceCopyPrefs::getSelectedFiltersAsRegex(const QStringList& additionalFilters) const { QStringList filters; if (!copySaves) filters << "saves"; if (!copyGameOptions) filters << "options.txt"; if (!copyResourcePacks) filters << "resourcepacks" << "texturepacks"; if (!copyShaderPacks) filters << "shaderpacks"; if (!copyServers) filters << "servers.dat" << "servers.dat_old" << "server-resource-packs"; if (!copyMods) filters << "coremods" << "mods" << "config"; if (!copyScreenshots) filters << "screenshots"; for (auto filter : additionalFilters) { filters << filter; } // If we have any filters to add, join them as a single regex string to return: if (!filters.isEmpty()) { const QString MC_ROOT = "[.]?minecraft/"; // Ensure first filter starts with root, then join other filters with OR regex before root (ex: ".minecraft/saves|.minecraft/mods"): return MC_ROOT + filters.join("|" + MC_ROOT); } return {}; } // ======= Getters ======= bool InstanceCopyPrefs::isCopySavesEnabled() const { return copySaves; } bool InstanceCopyPrefs::isKeepPlaytimeEnabled() const { return keepPlaytime; } bool InstanceCopyPrefs::isCopyGameOptionsEnabled() const { return copyGameOptions; } bool InstanceCopyPrefs::isCopyResourcePacksEnabled() const { return copyResourcePacks; } bool InstanceCopyPrefs::isCopyShaderPacksEnabled() const { return copyShaderPacks; } bool InstanceCopyPrefs::isCopyServersEnabled() const { return copyServers; } bool InstanceCopyPrefs::isCopyModsEnabled() const { return copyMods; } bool InstanceCopyPrefs::isCopyScreenshotsEnabled() const { return copyScreenshots; } bool InstanceCopyPrefs::isUseSymLinksEnabled() const { return useSymLinks; } bool InstanceCopyPrefs::isUseHardLinksEnabled() const { return useHardLinks; } bool InstanceCopyPrefs::isLinkRecursivelyEnabled() const { return linkRecursively; } bool InstanceCopyPrefs::isDontLinkSavesEnabled() const { return dontLinkSaves; } bool InstanceCopyPrefs::isUseCloneEnabled() const { return useClone; } // ======= Setters ======= void InstanceCopyPrefs::enableCopySaves(bool b) { copySaves = b; } void InstanceCopyPrefs::enableKeepPlaytime(bool b) { keepPlaytime = b; } void InstanceCopyPrefs::enableCopyGameOptions(bool b) { copyGameOptions = b; } void InstanceCopyPrefs::enableCopyResourcePacks(bool b) { copyResourcePacks = b; } void InstanceCopyPrefs::enableCopyShaderPacks(bool b) { copyShaderPacks = b; } void InstanceCopyPrefs::enableCopyServers(bool b) { copyServers = b; } void InstanceCopyPrefs::enableCopyMods(bool b) { copyMods = b; } void InstanceCopyPrefs::enableCopyScreenshots(bool b) { copyScreenshots = b; } void InstanceCopyPrefs::enableUseSymLinks(bool b) { useSymLinks = b; } void InstanceCopyPrefs::enableLinkRecursively(bool b) { linkRecursively = b; } void InstanceCopyPrefs::enableUseHardLinks(bool b) { useHardLinks = b; } void InstanceCopyPrefs::enableDontLinkSaves(bool b) { dontLinkSaves = b; } void InstanceCopyPrefs::enableUseClone(bool b) { useClone = b; }
3,846
C++
.cpp
153
21.620915
140
0.726402
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,931
MMCIcon.cpp
PrismLauncher_PrismLauncher/launcher/icons/MMCIcon.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * Copyright (c) 2023 Trial97 <alexandru.tripon97@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "MMCIcon.h" #include <QFileInfo> #include <QIcon> IconType operator--(IconType& t, int) { IconType temp = t; switch (t) { case IconType::Builtin: t = IconType::ToBeDeleted; break; case IconType::Transient: t = IconType::Builtin; break; case IconType::FileBased: t = IconType::Transient; break; default: break; } return temp; } IconType MMCIcon::type() const { return m_current_type; } QString MMCIcon::name() const { if (m_name.size()) return m_name; return m_key; } bool MMCIcon::has(IconType _type) const { return m_images[_type].present(); } QIcon MMCIcon::icon() const { if (m_current_type == IconType::ToBeDeleted) return QIcon(); auto& icon = m_images[m_current_type].icon; if (!icon.isNull()) return icon; // FIXME: inject this. return QIcon::fromTheme(m_images[m_current_type].key); } void MMCIcon::remove(IconType rm_type) { m_images[rm_type].filename = QString(); m_images[rm_type].icon = QIcon(); for (auto iter = rm_type; iter != IconType::ToBeDeleted; iter--) { if (m_images[iter].present()) { m_current_type = iter; return; } } m_current_type = IconType::ToBeDeleted; } void MMCIcon::replace(IconType new_type, QIcon icon, QString path) { if (new_type > m_current_type || m_current_type == IconType::ToBeDeleted) { m_current_type = new_type; } m_images[new_type].icon = icon; m_images[new_type].filename = path; m_images[new_type].key = QString(); } void MMCIcon::replace(IconType new_type, const QString& key) { if (new_type > m_current_type || m_current_type == IconType::ToBeDeleted) { m_current_type = new_type; } m_images[new_type].icon = QIcon(); m_images[new_type].filename = QString(); m_images[new_type].key = key; } QString MMCIcon::getFilePath() const { if (m_current_type == IconType::ToBeDeleted) { return QString(); } return m_images[m_current_type].filename; } bool MMCIcon::isBuiltIn() const { return m_current_type == IconType::Builtin; }
3,777
C++
.cpp
121
27.107438
80
0.668587
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
28,932
IconList.cpp
PrismLauncher_PrismLauncher/launcher/icons/IconList.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * Copyright (c) 2023 Trial97 <alexandru.tripon97@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "IconList.h" #include <FileSystem.h> #include <QDebug> #include <QEventLoop> #include <QFileSystemWatcher> #include <QMap> #include <QMimeData> #include <QSet> #include <QUrl> #include "icons/IconUtils.h" #define MAX_SIZE 1024 IconList::IconList(const QStringList& builtinPaths, QString path, QObject* parent) : QAbstractListModel(parent) { QSet<QString> builtinNames; // add builtin icons for (auto& builtinPath : builtinPaths) { QDir instance_icons(builtinPath); auto file_info_list = instance_icons.entryInfoList(QDir::Files, QDir::Name); for (auto file_info : file_info_list) { builtinNames.insert(file_info.completeBaseName()); } } for (auto& builtinName : builtinNames) { addThemeIcon(builtinName); } m_watcher.reset(new QFileSystemWatcher()); is_watching = false; connect(m_watcher.get(), &QFileSystemWatcher::directoryChanged, this, &IconList::directoryChanged); connect(m_watcher.get(), &QFileSystemWatcher::fileChanged, this, &IconList::fileChanged); directoryChanged(path); // Forces the UI to update, so that lengthy icon names are shown properly from the start emit iconUpdated({}); } void IconList::sortIconList() { qDebug() << "Sorting icon list..."; std::sort(icons.begin(), icons.end(), [](const MMCIcon& a, const MMCIcon& b) { return a.m_key.localeAwareCompare(b.m_key) < 0; }); reindex(); } void IconList::directoryChanged(const QString& path) { QDir new_dir(path); if (m_dir.absolutePath() != new_dir.absolutePath()) { m_dir.setPath(path); m_dir.refresh(); if (is_watching) stopWatching(); startWatching(); } if (!m_dir.exists()) if (!FS::ensureFolderPathExists(m_dir.absolutePath())) return; m_dir.refresh(); auto new_list = m_dir.entryList(QDir::Files, QDir::Name); for (auto it = new_list.begin(); it != new_list.end(); it++) { QString& foo = (*it); foo = m_dir.filePath(foo); } #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) QSet<QString> new_set(new_list.begin(), new_list.end()); #else auto new_set = new_list.toSet(); #endif QList<QString> current_list; for (auto& it : icons) { if (!it.has(IconType::FileBased)) continue; current_list.push_back(it.m_images[IconType::FileBased].filename); } #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) QSet<QString> current_set(current_list.begin(), current_list.end()); #else QSet<QString> current_set = current_list.toSet(); #endif QSet<QString> to_remove = current_set; to_remove -= new_set; QSet<QString> to_add = new_set; to_add -= current_set; for (auto remove : to_remove) { qDebug() << "Removing " << remove; QFileInfo rmfile(remove); QString key = rmfile.completeBaseName(); QString suffix = rmfile.suffix(); // The icon doesnt have a suffix, but it can have other .s in the name, so we account for those as well if (!IconUtils::isIconSuffix(suffix)) key = rmfile.fileName(); int idx = getIconIndex(key); if (idx == -1) continue; icons[idx].remove(IconType::FileBased); if (icons[idx].type() == IconType::ToBeDeleted) { beginRemoveRows(QModelIndex(), idx, idx); icons.remove(idx); reindex(); endRemoveRows(); } else { dataChanged(index(idx), index(idx)); } m_watcher->removePath(remove); emit iconUpdated(key); } for (auto add : to_add) { qDebug() << "Adding " << add; QFileInfo addfile(add); QString key = addfile.completeBaseName(); QString suffix = addfile.suffix(); // The icon doesnt have a suffix, but it can have other .s in the name, so we account for those as well if (!IconUtils::isIconSuffix(suffix)) key = addfile.fileName(); if (addIcon(key, QString(), addfile.filePath(), IconType::FileBased)) { m_watcher->addPath(add); emit iconUpdated(key); } } sortIconList(); } void IconList::fileChanged(const QString& path) { qDebug() << "Checking " << path; QFileInfo checkfile(path); if (!checkfile.exists()) return; QString key = checkfile.completeBaseName(); int idx = getIconIndex(key); if (idx == -1) return; QIcon icon(path); if (!icon.availableSizes().size()) return; icons[idx].m_images[IconType::FileBased].icon = icon; dataChanged(index(idx), index(idx)); emit iconUpdated(key); } void IconList::SettingChanged(const Setting& setting, QVariant value) { if (setting.id() != "IconsDir") return; directoryChanged(value.toString()); } void IconList::startWatching() { auto abs_path = m_dir.absolutePath(); FS::ensureFolderPathExists(abs_path); is_watching = m_watcher->addPath(abs_path); if (is_watching) { qDebug() << "Started watching " << abs_path; } else { qDebug() << "Failed to start watching " << abs_path; } } void IconList::stopWatching() { m_watcher->removePaths(m_watcher->files()); m_watcher->removePaths(m_watcher->directories()); is_watching = false; } QStringList IconList::mimeTypes() const { QStringList types; types << "text/uri-list"; return types; } Qt::DropActions IconList::supportedDropActions() const { return Qt::CopyAction; } bool IconList::dropMimeData(const QMimeData* data, Qt::DropAction action, [[maybe_unused]] int row, [[maybe_unused]] int column, [[maybe_unused]] const QModelIndex& parent) { if (action == Qt::IgnoreAction) return true; // check if the action is supported if (!data || !(action & supportedDropActions())) return false; // files dropped from outside? if (data->hasUrls()) { auto urls = data->urls(); QStringList iconFiles; for (auto url : urls) { // only local files may be dropped... if (!url.isLocalFile()) continue; iconFiles += url.toLocalFile(); } installIcons(iconFiles); return true; } return false; } Qt::ItemFlags IconList::flags(const QModelIndex& index) const { Qt::ItemFlags defaultFlags = QAbstractListModel::flags(index); return Qt::ItemIsDropEnabled | defaultFlags; } QVariant IconList::data(const QModelIndex& index, int role) const { if (!index.isValid()) return QVariant(); int row = index.row(); if (row < 0 || row >= icons.size()) return QVariant(); switch (role) { case Qt::DecorationRole: return icons[row].icon(); case Qt::DisplayRole: return icons[row].name(); case Qt::UserRole: return icons[row].m_key; default: return QVariant(); } } int IconList::rowCount(const QModelIndex& parent) const { return parent.isValid() ? 0 : icons.size(); } void IconList::installIcons(const QStringList& iconFiles) { for (QString file : iconFiles) installIcon(file, {}); } void IconList::installIcon(const QString& file, const QString& name) { QFileInfo fileinfo(file); if (!fileinfo.isReadable() || !fileinfo.isFile()) return; if (!IconUtils::isIconSuffix(fileinfo.suffix())) return; QString target = FS::PathCombine(getDirectory(), name.isEmpty() ? fileinfo.fileName() : name); QFile::copy(file, target); } bool IconList::iconFileExists(const QString& key) const { auto iconEntry = icon(key); return iconEntry && iconEntry->has(IconType::FileBased); } const MMCIcon* IconList::icon(const QString& key) const { int iconIdx = getIconIndex(key); if (iconIdx == -1) return nullptr; return &icons[iconIdx]; } bool IconList::deleteIcon(const QString& key) { return iconFileExists(key) && FS::deletePath(icon(key)->getFilePath()); } bool IconList::trashIcon(const QString& key) { return iconFileExists(key) && FS::trash(icon(key)->getFilePath(), nullptr); } bool IconList::addThemeIcon(const QString& key) { auto iter = name_index.find(key); if (iter != name_index.end()) { auto& oldOne = icons[*iter]; oldOne.replace(Builtin, key); dataChanged(index(*iter), index(*iter)); return true; } // add a new icon beginInsertRows(QModelIndex(), icons.size(), icons.size()); { MMCIcon mmc_icon; mmc_icon.m_name = key; mmc_icon.m_key = key; mmc_icon.replace(Builtin, key); icons.push_back(mmc_icon); name_index[key] = icons.size() - 1; } endInsertRows(); return true; } bool IconList::addIcon(const QString& key, const QString& name, const QString& path, const IconType type) { // replace the icon even? is the input valid? QIcon icon(path); if (icon.isNull()) return false; auto iter = name_index.find(key); if (iter != name_index.end()) { auto& oldOne = icons[*iter]; oldOne.replace(type, icon, path); dataChanged(index(*iter), index(*iter)); return true; } // add a new icon beginInsertRows(QModelIndex(), icons.size(), icons.size()); { MMCIcon mmc_icon; mmc_icon.m_name = name; mmc_icon.m_key = key; mmc_icon.replace(type, icon, path); icons.push_back(mmc_icon); name_index[key] = icons.size() - 1; } endInsertRows(); return true; } void IconList::saveIcon(const QString& key, const QString& path, const char* format) const { auto icon = getIcon(key); auto pixmap = icon.pixmap(128, 128); pixmap.save(path, format); } void IconList::reindex() { name_index.clear(); int i = 0; for (auto& iter : icons) { name_index[iter.m_key] = i; i++; } } QIcon IconList::getIcon(const QString& key) const { int icon_index = getIconIndex(key); if (icon_index != -1) return icons[icon_index].icon(); // Fallback for icons that don't exist. icon_index = getIconIndex("grass"); if (icon_index != -1) return icons[icon_index].icon(); return QIcon(); } int IconList::getIconIndex(const QString& key) const { auto iter = name_index.find(key == "default" ? "grass" : key); if (iter != name_index.end()) return *iter; return -1; } QString IconList::getDirectory() const { return m_dir.absolutePath(); }
12,221
C++
.cpp
374
27.179144
134
0.641682
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
28,933
IconUtils.cpp
PrismLauncher_PrismLauncher/launcher/icons/IconUtils.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2023 Trial97 <alexandru.tripon97@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 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 "IconUtils.h" #include <QDirIterator> #include "FileSystem.h" namespace { static const QStringList validIconExtensions = { { "svg", "png", "ico", "gif", "jpg", "jpeg", "webp" } }; } namespace IconUtils { QString findBestIconIn(const QString& folder, const QString& iconKey) { QString best_filename; QDirIterator it(folder, QDir::NoDotAndDotDot | QDir::Files, QDirIterator::NoIteratorFlags); while (it.hasNext()) { it.next(); auto fileInfo = it.fileInfo(); if ((fileInfo.completeBaseName() == iconKey || fileInfo.fileName() == iconKey) && isIconSuffix(fileInfo.suffix())) return fileInfo.absoluteFilePath(); } return {}; } QString getIconFilter() { return "(*." + validIconExtensions.join(" *.") + ")"; } bool isIconSuffix(QString suffix) { return validIconExtensions.contains(suffix); } } // namespace IconUtils
2,390
C++
.cpp
62
35.854839
122
0.716688
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,934
ConcurrentTask.cpp
PrismLauncher_PrismLauncher/launcher/tasks/ConcurrentTask.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 flowln <flowlnlnln@gmail.com> * Copyright (c) 2023 Rachel Powers <508861+Ryex@users.noreply.github.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 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 "ConcurrentTask.h" #include <QDebug> #include "tasks/Task.h" ConcurrentTask::ConcurrentTask(QString task_name, int max_concurrent) : Task(), m_total_max_size(max_concurrent) { setObjectName(task_name); } ConcurrentTask::~ConcurrentTask() { for (auto task : m_doing) { if (task) task->disconnect(this); } } auto ConcurrentTask::getStepProgress() const -> TaskStepProgressList { return m_task_progress.values(); } void ConcurrentTask::addTask(Task::Ptr task) { m_queue.append(task); } void ConcurrentTask::executeTask() { for (auto i = 0; i < m_total_max_size; i++) QMetaObject::invokeMethod(this, &ConcurrentTask::executeNextSubTask, Qt::QueuedConnection); } bool ConcurrentTask::abort() { m_queue.clear(); if (m_doing.isEmpty()) { // Don't call emitAborted() here, we want to bypass the 'is the task running' check emit aborted(); emit finished(); return true; } bool suceedeed = true; QMutableHashIterator<Task*, Task::Ptr> doing_iter(m_doing); while (doing_iter.hasNext()) { auto task = doing_iter.next(); disconnect(task->get(), &Task::aborted, this, 0); suceedeed &= (task.value())->abort(); } if (suceedeed) emitAborted(); else emitFailed(tr("Failed to abort all running tasks.")); return suceedeed; } void ConcurrentTask::clear() { Q_ASSERT(!isRunning()); m_done.clear(); m_failed.clear(); m_queue.clear(); m_task_progress.clear(); m_progress = 0; } void ConcurrentTask::executeNextSubTask() { if (!isRunning()) { return; } if (m_doing.count() >= m_total_max_size) { return; } if (m_queue.isEmpty()) { if (m_doing.isEmpty()) { if (m_failed.isEmpty()) emitSucceeded(); else emitFailed(tr("One or more subtasks failed")); } return; } startSubTask(m_queue.dequeue()); } void ConcurrentTask::startSubTask(Task::Ptr next) { connect(next.get(), &Task::succeeded, this, [this, next]() { subTaskSucceeded(next); }); connect(next.get(), &Task::failed, this, [this, next](QString msg) { subTaskFailed(next, msg); }); // this should never happen but if it does, it's better to fail the task than get stuck connect(next.get(), &Task::aborted, this, [this, next] { subTaskFailed(next, "Aborted"); }); connect(next.get(), &Task::status, this, [this, next](QString msg) { subTaskStatus(next, msg); }); connect(next.get(), &Task::details, this, [this, next](QString msg) { subTaskDetails(next, msg); }); connect(next.get(), &Task::stepProgress, this, &ConcurrentTask::stepProgress); connect(next.get(), &Task::progress, this, [this, next](qint64 current, qint64 total) { subTaskProgress(next, current, total); }); m_doing.insert(next.get(), next); auto task_progress = std::make_shared<TaskStepProgress>(next->getUid()); m_task_progress.insert(next->getUid(), task_progress); updateState(); QMetaObject::invokeMethod(next.get(), &Task::start, Qt::QueuedConnection); } void ConcurrentTask::subTaskFinished(Task::Ptr task, TaskStepState state) { m_done.insert(task.get(), task); (state == TaskStepState::Succeeded ? m_succeeded : m_failed).insert(task.get(), task); m_doing.remove(task.get()); auto task_progress = *m_task_progress.value(task->getUid()); task_progress.state = state; m_task_progress.remove(task->getUid()); disconnect(task.get(), 0, this, 0); emit stepProgress(task_progress); updateState(); QMetaObject::invokeMethod(this, &ConcurrentTask::executeNextSubTask, Qt::QueuedConnection); } void ConcurrentTask::subTaskSucceeded(Task::Ptr task) { subTaskFinished(task, TaskStepState::Succeeded); } void ConcurrentTask::subTaskFailed(Task::Ptr task, [[maybe_unused]] const QString& msg) { subTaskFinished(task, TaskStepState::Failed); } void ConcurrentTask::subTaskStatus(Task::Ptr task, const QString& msg) { auto task_progress = m_task_progress.value(task->getUid()); task_progress->status = msg; task_progress->state = TaskStepState::Running; emit stepProgress(*task_progress); if (totalSize() == 1) { setStatus(msg); } } void ConcurrentTask::subTaskDetails(Task::Ptr task, const QString& msg) { auto task_progress = m_task_progress.value(task->getUid()); task_progress->details = msg; task_progress->state = TaskStepState::Running; emit stepProgress(*task_progress); if (totalSize() == 1) { setDetails(msg); } } void ConcurrentTask::subTaskProgress(Task::Ptr task, qint64 current, qint64 total) { auto task_progress = m_task_progress.value(task->getUid()); task_progress->update(current, total); emit stepProgress(*task_progress); updateState(); if (totalSize() == 1) { setProgress(task_progress->current, task_progress->total); } } void ConcurrentTask::updateState() { if (totalSize() > 1) { setProgress(m_done.count(), totalSize()); setStatus(tr("Executing %1 task(s) (%2 out of %3 are done)") .arg(QString::number(m_doing.count()), QString::number(m_done.count()), QString::number(totalSize()))); } else { QString status = tr("Please wait..."); if (m_queue.size() > 0) { status = tr("Waiting for a task to start..."); } else if (m_doing.size() > 0) { status = tr("Executing 1 task:"); } else if (m_done.size() > 0) { status = tr("Task finished."); } setStatus(status); } }
7,235
C++
.cpp
197
32.081218
134
0.669335
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,935
SequentialTask.cpp
PrismLauncher_PrismLauncher/launcher/tasks/SequentialTask.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 flowln <flowlnlnln@gmail.com> * Copyright (c) 2023 Rachel Powers <508861+Ryex@users.noreply.github.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 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 "SequentialTask.h" #include <QDebug> #include "tasks/ConcurrentTask.h" SequentialTask::SequentialTask(QString task_name) : ConcurrentTask(task_name, 1) {} void SequentialTask::subTaskFailed(Task::Ptr task, const QString& msg) { emitFailed(msg); qWarning() << msg; ConcurrentTask::subTaskFailed(task, msg); } void SequentialTask::updateState() { setProgress(m_done.count(), totalSize()); setStatus(tr("Executing task %1 out of %2").arg(QString::number(m_doing.count() + m_done.count()), QString::number(totalSize()))); }
2,115
C++
.cpp
50
40.16
134
0.733624
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,936
MultipleOptionsTask.cpp
PrismLauncher_PrismLauncher/launcher/tasks/MultipleOptionsTask.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 flowln <flowlnlnln@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 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 "MultipleOptionsTask.h" #include <QDebug> MultipleOptionsTask::MultipleOptionsTask(const QString& task_name) : ConcurrentTask(task_name, 1) {} void MultipleOptionsTask::executeNextSubTask() { if (m_done.size() != m_failed.size()) { emitSucceeded(); return; } if (m_queue.isEmpty()) { emitFailed(tr("All attempts have failed!")); qWarning() << "All attempts have failed!"; return; } ConcurrentTask::executeNextSubTask(); } void MultipleOptionsTask::updateState() { setProgress(m_done.count(), totalSize()); setStatus(tr("Attempting task %1 out of %2").arg(QString::number(m_doing.count() + m_done.count()), QString::number(totalSize()))); }
2,209
C++
.cpp
55
37.236364
135
0.715084
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,937
Task.cpp
PrismLauncher_PrismLauncher/launcher/tasks/Task.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 flowln <flowlnlnln@gmail.com> * Copyright (c) 2023 Rachel Powers <508861+Ryex@users.noreply.github.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 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 "Task.h" #include <QDebug> Q_LOGGING_CATEGORY(taskLogC, "launcher.task") Task::Task(bool show_debug) : m_show_debug(show_debug) { m_uid = QUuid::createUuid(); setAutoDelete(false); } void Task::setStatus(const QString& new_status) { if (m_status != new_status) { m_status = new_status; emit status(m_status); } } void Task::setDetails(const QString& new_details) { if (m_details != new_details) { m_details = new_details; emit details(m_details); } } void Task::setProgress(qint64 current, qint64 total) { if ((m_progress != current) || (m_progressTotal != total)) { m_progress = current; m_progressTotal = total; emit progress(m_progress, m_progressTotal); } } void Task::start() { switch (m_state) { case State::Inactive: { if (m_show_debug) qCDebug(taskLogC) << "Task" << describe() << "starting for the first time"; break; } case State::AbortedByUser: { if (m_show_debug) qCDebug(taskLogC) << "Task" << describe() << "restarting for after being aborted by user"; break; } case State::Failed: { if (m_show_debug) qCDebug(taskLogC) << "Task" << describe() << "restarting for after failing at first"; break; } case State::Succeeded: { if (m_show_debug) qCDebug(taskLogC) << "Task" << describe() << "restarting for after succeeding at first"; break; } case State::Running: { if (m_show_debug) qCWarning(taskLogC) << "The launcher tried to start task" << describe() << "while it was already running!"; return; } } // NOTE: only fall through to here in end states m_state = State::Running; emit started(); executeTask(); } void Task::emitFailed(QString reason) { // Don't fail twice. if (!isRunning()) { qCCritical(taskLogC) << "Task" << describe() << "failed while not running!!!!: " << reason; return; } m_state = State::Failed; m_failReason = reason; qCCritical(taskLogC) << "Task" << describe() << "failed: " << reason; emit failed(reason); emit finished(); } void Task::emitAborted() { // Don't abort twice. if (!isRunning()) { qCCritical(taskLogC) << "Task" << describe() << "aborted while not running!!!!"; return; } m_state = State::AbortedByUser; m_failReason = "Aborted."; if (m_show_debug) qCDebug(taskLogC) << "Task" << describe() << "aborted."; emit aborted(); emit finished(); } void Task::emitSucceeded() { // Don't succeed twice. if (!isRunning()) { qCCritical(taskLogC) << "Task" << describe() << "succeeded while not running!!!!"; return; } m_state = State::Succeeded; if (m_show_debug) qCDebug(taskLogC) << "Task" << describe() << "succeeded"; emit succeeded(); emit finished(); } void Task::propagateStepProgress(TaskStepProgress const& task_progress) { emit stepProgress(task_progress); } QString Task::describe() { QString outStr; QTextStream out(&outStr); out << metaObject()->className() << QChar('('); auto name = objectName(); if (name.isEmpty()) { out << QString("0x%1").arg(reinterpret_cast<quintptr>(this), 0, 16); } else { out << name; } out << " ID: " << m_uid.toString(QUuid::WithoutBraces); out << QChar(')'); out.flush(); return outStr; } bool Task::isRunning() const { return m_state == State::Running; } bool Task::isFinished() const { return m_state != State::Running && m_state != State::Inactive; } bool Task::wasSuccessful() const { return m_state == State::Succeeded; } QString Task::failReason() const { return m_failReason; } void Task::logWarning(const QString& line) { qWarning() << line; m_Warnings.append(line); } QStringList Task::warnings() const { return m_Warnings; }
5,648
C++
.cpp
184
25.929348
123
0.633725
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,938
ImgurAlbumCreation.cpp
PrismLauncher_PrismLauncher/launcher/screenshots/ImgurAlbumCreation.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 flowln <flowlnlnln@gmail.com> * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 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 "ImgurAlbumCreation.h" #include <QDebug> #include <QJsonDocument> #include <QJsonObject> #include <QList> #include <QNetworkRequest> #include <QStringList> #include <QUrl> #include <memory> #include "BuildConfig.h" #include "net/RawHeaderProxy.h" Net::NetRequest::Ptr ImgurAlbumCreation::make(std::shared_ptr<ImgurAlbumCreation::Result> output, QList<ScreenShot::Ptr> screenshots) { auto up = makeShared<ImgurAlbumCreation>(); up->m_url = BuildConfig.IMGUR_BASE_URL + "album"; up->m_sink.reset(new Sink(output)); up->m_screenshots = screenshots; up->addHeaderProxy(new Net::RawHeaderProxy( QList<Net::HeaderPair>{ { "Content-Type", "application/x-www-form-urlencoded" }, { "Authorization", QString("Client-ID %1").arg(BuildConfig.IMGUR_CLIENT_ID).toUtf8() }, { "Accept", "application/json" } })); return up; } QNetworkReply* ImgurAlbumCreation::getReply(QNetworkRequest& request) { QStringList hashes; for (auto shot : m_screenshots) { hashes.append(shot->m_imgurDeleteHash); } const QByteArray data = "deletehashes=" + hashes.join(',').toUtf8() + "&title=Minecraft%20Screenshots&privacy=hidden"; return m_network->post(request, data); } auto ImgurAlbumCreation::Sink::init(QNetworkRequest& request) -> Task::State { m_output.clear(); return Task::State::Running; } auto ImgurAlbumCreation::Sink::write(QByteArray& data) -> Task::State { m_output.append(data); return Task::State::Running; } auto ImgurAlbumCreation::Sink::abort() -> Task::State { m_output.clear(); return Task::State::Failed; } auto ImgurAlbumCreation::Sink::finalize(QNetworkReply&) -> Task::State { QJsonParseError jsonError; QJsonDocument doc = QJsonDocument::fromJson(m_output, &jsonError); if (jsonError.error != QJsonParseError::NoError) { qDebug() << jsonError.errorString(); return Task::State::Failed; } auto object = doc.object(); if (!object.value("success").toBool()) { qDebug() << doc.toJson(); return Task::State::Failed; } m_result->deleteHash = object.value("data").toObject().value("deletehash").toString(); m_result->id = object.value("data").toObject().value("id").toString(); return Task::State::Succeeded; }
3,880
C++
.cpp
99
35.555556
133
0.704744
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,939
ImgurUpload.cpp
PrismLauncher_PrismLauncher/launcher/screenshots/ImgurUpload.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 flowln <flowlnlnln@gmail.com> * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 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 "ImgurUpload.h" #include "BuildConfig.h" #include "net/RawHeaderProxy.h" #include <QDebug> #include <QFile> #include <QHttpMultiPart> #include <QHttpPart> #include <QJsonDocument> #include <QJsonObject> #include <QNetworkRequest> #include <QUrl> QNetworkReply* ImgurUpload::getReply(QNetworkRequest& request) { auto file = new QFile(m_fileInfo.absoluteFilePath(), this); if (!file->open(QFile::ReadOnly)) { emitFailed(); return nullptr; } QHttpMultiPart* multipart = new QHttpMultiPart(QHttpMultiPart::FormDataType, this); file->setParent(multipart); QHttpPart filePart; filePart.setBodyDevice(file); filePart.setHeader(QNetworkRequest::ContentTypeHeader, "image/png"); filePart.setHeader(QNetworkRequest::ContentDispositionHeader, "form-data; name=\"image\"; filename=\"" + file->fileName() + "\""); multipart->append(filePart); QHttpPart typePart; typePart.setHeader(QNetworkRequest::ContentDispositionHeader, "form-data; name=\"type\""); typePart.setBody("file"); multipart->append(typePart); QHttpPart namePart; namePart.setHeader(QNetworkRequest::ContentDispositionHeader, "form-data; name=\"title\""); namePart.setBody(m_fileInfo.baseName().toUtf8()); multipart->append(namePart); return m_network->post(request, multipart); } auto ImgurUpload::Sink::init(QNetworkRequest& request) -> Task::State { m_output.clear(); return Task::State::Running; } auto ImgurUpload::Sink::write(QByteArray& data) -> Task::State { m_output.append(data); return Task::State::Running; } auto ImgurUpload::Sink::abort() -> Task::State { m_output.clear(); return Task::State::Failed; } auto ImgurUpload::Sink::finalize(QNetworkReply&) -> Task::State { QJsonParseError jsonError; QJsonDocument doc = QJsonDocument::fromJson(m_output, &jsonError); if (jsonError.error != QJsonParseError::NoError) { qDebug() << "imgur server did not reply with JSON" << jsonError.errorString(); return Task::State::Failed; } auto object = doc.object(); if (!object.value("success").toBool()) { qDebug() << "Screenshot upload not successful:" << doc.toJson(); return Task::State::Failed; } m_shot->m_imgurId = object.value("data").toObject().value("id").toString(); m_shot->m_url = object.value("data").toObject().value("link").toString(); m_shot->m_imgurDeleteHash = object.value("data").toObject().value("deletehash").toString(); return Task::State::Succeeded; } Net::NetRequest::Ptr ImgurUpload::make(ScreenShot::Ptr m_shot) { auto up = makeShared<ImgurUpload>(m_shot->m_file); up->m_url = std::move(BuildConfig.IMGUR_BASE_URL + "image"); up->m_sink.reset(new Sink(m_shot)); up->addHeaderProxy(new Net::RawHeaderProxy(QList<Net::HeaderPair>{ { "Authorization", QString("Client-ID %1").arg(BuildConfig.IMGUR_CLIENT_ID).toUtf8() }, { "Accept", "application/json" } })); return up; }
4,534
C++
.cpp
112
37.125
134
0.713897
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,941
NewsEntry.cpp
PrismLauncher_PrismLauncher/launcher/news/NewsEntry.cpp
/* Copyright 2013-2021 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 "NewsEntry.h" #include <QDomNodeList> #include <QVariant> NewsEntry::NewsEntry(QObject* parent) : QObject(parent) { this->title = tr("Untitled"); this->content = tr("No content."); this->link = ""; } NewsEntry::NewsEntry(const QString& title, const QString& content, const QString& link, QObject* parent) : QObject(parent) { this->title = title; this->content = content; this->link = link; } /*! * Gets the text content of the given child element as a QVariant. */ inline QString childValue(const QDomElement& element, const QString& childName, QString defaultVal = "") { QDomNodeList nodes = element.elementsByTagName(childName); if (nodes.count() > 0) { QDomElement elem = nodes.at(0).toElement(); return elem.text(); } else { return defaultVal; } } bool NewsEntry::fromXmlElement(const QDomElement& element, NewsEntry* entry, [[maybe_unused]] QString* errorMsg) { QString title = childValue(element, "title", tr("Untitled")); QString content = childValue(element, "content", tr("No content.")); QString link = childValue(element, "id"); entry->title = title; entry->content = content; entry->link = link; return true; }
1,839
C++
.cpp
52
32.173077
122
0.713483
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,943
MCEditTool.cpp
PrismLauncher_PrismLauncher/launcher/tools/MCEditTool.cpp
#include "MCEditTool.h" #include <QDir> #include <QProcess> #include <QUrl> #include "BaseInstance.h" #include "minecraft/MinecraftInstance.h" #include "settings/SettingsObject.h" MCEditTool::MCEditTool(SettingsObjectPtr settings) { settings->registerSetting("MCEditPath"); m_settings = settings; } void MCEditTool::setPath(QString& path) { m_settings->set("MCEditPath", path); } QString MCEditTool::path() const { return m_settings->get("MCEditPath").toString(); } bool MCEditTool::check(const QString& toolPath, QString& error) { if (toolPath.isEmpty()) { error = QObject::tr("Path is empty"); return false; } const QDir dir(toolPath); if (!dir.exists()) { error = QObject::tr("Path does not exist"); return false; } if (!dir.exists("mcedit.sh") && !dir.exists("mcedit.py") && !dir.exists("mcedit.exe") && !dir.exists("Contents") && !dir.exists("mcedit2.exe")) { error = QObject::tr("Path does not seem to be a MCEdit path"); return false; } return true; } QString MCEditTool::getProgramPath() { #ifdef Q_OS_OSX return path(); #else const QString mceditPath = path(); QDir mceditDir(mceditPath); #if defined(Q_OS_LINUX) || defined(Q_OS_FREEBSD) || defined(Q_OS_OPENBSD) if (mceditDir.exists("mcedit.sh")) { return mceditDir.absoluteFilePath("mcedit.sh"); } else if (mceditDir.exists("mcedit.py")) { return mceditDir.absoluteFilePath("mcedit.py"); } return QString(); #elif defined(Q_OS_WIN32) if (mceditDir.exists("mcedit.exe")) { return mceditDir.absoluteFilePath("mcedit.exe"); } else if (mceditDir.exists("mcedit2.exe")) { return mceditDir.absoluteFilePath("mcedit2.exe"); } return QString(); #endif #endif }
1,801
C++
.cpp
62
25.032258
119
0.67321
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
28,944
GenericProfiler.cpp
PrismLauncher_PrismLauncher/launcher/tools/GenericProfiler.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2023 Trial97 <alexandru.tripon97@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "GenericProfiler.h" #include "BaseInstance.h" #include "launch/LaunchTask.h" #include "settings/SettingsObject.h" class GenericProfiler : public BaseProfiler { Q_OBJECT public: GenericProfiler(SettingsObjectPtr settings, InstancePtr instance, QObject* parent = 0); protected: void beginProfilingImpl(shared_qobject_ptr<LaunchTask> process); }; GenericProfiler::GenericProfiler(SettingsObjectPtr settings, InstancePtr instance, QObject* parent) : BaseProfiler(settings, instance, parent) {} void GenericProfiler::beginProfilingImpl(shared_qobject_ptr<LaunchTask> process) { emit readyToLaunch(tr("Started process: %1").arg(process->pid())); } BaseExternalTool* GenericProfilerFactory::createTool(InstancePtr instance, QObject* parent) { return new GenericProfiler(globalSettings, instance, parent); } #include "GenericProfiler.moc"
1,620
C++
.cpp
40
38.25
99
0.778413
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,946
JVisualVM.cpp
PrismLauncher_PrismLauncher/launcher/tools/JVisualVM.cpp
#include "JVisualVM.h" #include <QDir> #include <QStandardPaths> #include "BaseInstance.h" #include "launch/LaunchTask.h" #include "settings/SettingsObject.h" class JVisualVM : public BaseProfiler { Q_OBJECT public: JVisualVM(SettingsObjectPtr settings, InstancePtr instance, QObject* parent = 0); private slots: void profilerStarted(); void profilerFinished(int exit, QProcess::ExitStatus status); protected: void beginProfilingImpl(shared_qobject_ptr<LaunchTask> process); }; JVisualVM::JVisualVM(SettingsObjectPtr settings, InstancePtr instance, QObject* parent) : BaseProfiler(settings, instance, parent) {} void JVisualVM::profilerStarted() { emit readyToLaunch(tr("JVisualVM started")); } void JVisualVM::profilerFinished([[maybe_unused]] int exit, QProcess::ExitStatus status) { if (status == QProcess::CrashExit) { emit abortLaunch(tr("Profiler aborted")); } if (m_profilerProcess) { m_profilerProcess->deleteLater(); m_profilerProcess = 0; } } void JVisualVM::beginProfilingImpl(shared_qobject_ptr<LaunchTask> process) { QProcess* profiler = new QProcess(this); QStringList profilerArgs = { "--openpid", QString::number(process->pid()) }; auto programPath = globalSettings->get("JVisualVMPath").toString(); profiler->setArguments(profilerArgs); profiler->setProgram(programPath); connect(profiler, &QProcess::started, this, &JVisualVM::profilerStarted); connect(profiler, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), this, &JVisualVM::profilerFinished); profiler->start(); m_profilerProcess = profiler; } void JVisualVMFactory::registerSettings(SettingsObjectPtr settings) { QString defaultValue = QStandardPaths::findExecutable("jvisualvm"); if (defaultValue.isNull()) { defaultValue = QStandardPaths::findExecutable("visualvm"); } settings->registerSetting("JVisualVMPath", defaultValue); globalSettings = settings; } BaseExternalTool* JVisualVMFactory::createTool(InstancePtr instance, QObject* parent) { return new JVisualVM(globalSettings, instance, parent); } bool JVisualVMFactory::check(QString* error) { return check(globalSettings->get("JVisualVMPath").toString(), error); } bool JVisualVMFactory::check(const QString& path, QString* error) { if (path.isEmpty()) { *error = QObject::tr("Empty path"); return false; } QFileInfo finfo(path); if (!finfo.isExecutable() || !finfo.fileName().contains("visualvm")) { *error = QObject::tr("Invalid path to JVisualVM"); return false; } return true; } #include "JVisualVM.moc"
2,673
C++
.cpp
74
32.175676
133
0.735864
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
28,948
PrismExternalUpdater.cpp
PrismLauncher_PrismLauncher/launcher/updater/PrismExternalUpdater.cpp
// SPDX-FileCopyrightText: 2023 Rachel Powers <508861+Ryex@users.noreply.github.com> // // SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2023 Rachel Powers <508861+Ryex@users.noreply.github.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #include "PrismExternalUpdater.h" #include <QCoreApplication> #include <QDateTime> #include <QDebug> #include <QDir> #include <QMessageBox> #include <QProcess> #include <QProgressDialog> #include <QSettings> #include <QTimer> #include <memory> #include "StringUtils.h" #include "BuildConfig.h" #include "ui/dialogs/UpdateAvailableDialog.h" class PrismExternalUpdater::Private { public: QDir appDir; QDir dataDir; QTimer updateTimer; bool allowBeta; bool autoCheck; double updateInterval; QDateTime lastCheck; std::unique_ptr<QSettings> settings; QWidget* parent; }; PrismExternalUpdater::PrismExternalUpdater(QWidget* parent, const QString& appDir, const QString& dataDir) { priv = new PrismExternalUpdater::Private(); priv->appDir = QDir(appDir); priv->dataDir = QDir(dataDir); auto settings_file = priv->dataDir.absoluteFilePath("prismlauncher_update.cfg"); priv->settings = std::make_unique<QSettings>(settings_file, QSettings::Format::IniFormat); priv->allowBeta = priv->settings->value("allow_beta", false).toBool(); priv->autoCheck = priv->settings->value("auto_check", false).toBool(); bool interval_ok; // default once per day priv->updateInterval = priv->settings->value("update_interval", 86400).toInt(&interval_ok); if (!interval_ok) priv->updateInterval = 86400; auto last_check = priv->settings->value("last_check"); if (!last_check.isNull() && last_check.isValid()) { priv->lastCheck = QDateTime::fromString(last_check.toString(), Qt::ISODate); } priv->parent = parent; connectTimer(); resetAutoCheckTimer(); } PrismExternalUpdater::~PrismExternalUpdater() { if (priv->updateTimer.isActive()) priv->updateTimer.stop(); disconnectTimer(); priv->settings->sync(); delete priv; } void PrismExternalUpdater::checkForUpdates() { checkForUpdates(true); } void PrismExternalUpdater::checkForUpdates(bool triggeredByUser) { QProgressDialog progress(tr("Checking for updates..."), "", 0, 0, priv->parent); progress.setCancelButton(nullptr); progress.adjustSize(); progress.show(); QCoreApplication::processEvents(); QProcess proc; auto exe_name = QStringLiteral("%1_updater").arg(BuildConfig.LAUNCHER_APP_BINARY_NAME); #if defined Q_OS_WIN32 exe_name.append(".exe"); auto env = QProcessEnvironment::systemEnvironment(); env.insert("__COMPAT_LAYER", "RUNASINVOKER"); proc.setProcessEnvironment(env); #else exe_name = QString("bin/%1").arg(exe_name); #endif QStringList args = { "--check-only", "--dir", priv->dataDir.absolutePath(), "--debug" }; if (priv->allowBeta) args.append("--pre-release"); proc.start(priv->appDir.absoluteFilePath(exe_name), args); auto result_start = proc.waitForStarted(5000); if (!result_start) { auto err = proc.error(); qDebug() << "Failed to start updater after 5 seconds." << "reason:" << err << proc.errorString(); auto msgBox = QMessageBox(QMessageBox::Information, tr("Update Check Failed"), tr("Failed to start after 5 seconds\nReason: %1.").arg(proc.errorString()), QMessageBox::Ok, priv->parent); msgBox.setMinimumWidth(460); msgBox.adjustSize(); msgBox.exec(); priv->lastCheck = QDateTime::currentDateTime(); priv->settings->setValue("last_check", priv->lastCheck.toString(Qt::ISODate)); priv->settings->sync(); resetAutoCheckTimer(); return; } QCoreApplication::processEvents(); auto result_finished = proc.waitForFinished(60000); if (!result_finished) { proc.kill(); auto err = proc.error(); auto output = proc.readAll(); qDebug() << "Updater failed to close after 60 seconds." << "reason:" << err << proc.errorString(); auto msgBox = QMessageBox(QMessageBox::Information, tr("Update Check Failed"), tr("Updater failed to close 60 seconds\nReason: %1.").arg(proc.errorString()), QMessageBox::Ok, priv->parent); msgBox.setDetailedText(output); msgBox.setMinimumWidth(460); msgBox.adjustSize(); msgBox.exec(); priv->lastCheck = QDateTime::currentDateTime(); priv->settings->setValue("last_check", priv->lastCheck.toString(Qt::ISODate)); priv->settings->sync(); resetAutoCheckTimer(); return; } auto exit_code = proc.exitCode(); auto std_output = proc.readAllStandardOutput(); auto std_error = proc.readAllStandardError(); progress.hide(); QCoreApplication::processEvents(); switch (exit_code) { case 0: // no update available if (triggeredByUser) { qDebug() << "No update available"; auto msgBox = QMessageBox(QMessageBox::Information, tr("No Update Available"), tr("You are running the latest version."), QMessageBox::Ok, priv->parent); msgBox.setMinimumWidth(460); msgBox.adjustSize(); msgBox.exec(); } break; case 1: // there was an error { qDebug() << "Updater subprocess error" << qPrintable(std_error); auto msgBox = QMessageBox(QMessageBox::Warning, tr("Update Check Error"), tr("There was an error running the update check."), QMessageBox::Ok, priv->parent); msgBox.setDetailedText(QString(std_error)); msgBox.setMinimumWidth(460); msgBox.adjustSize(); msgBox.exec(); } break; case 100: // update available { auto [first_line, remainder1] = StringUtils::splitFirst(std_output, '\n'); auto [second_line, remainder2] = StringUtils::splitFirst(remainder1, '\n'); auto [third_line, release_notes] = StringUtils::splitFirst(remainder2, '\n'); auto version_name = StringUtils::splitFirst(first_line, ": ").second.trimmed(); auto version_tag = StringUtils::splitFirst(second_line, ": ").second.trimmed(); auto release_timestamp = QDateTime::fromString(StringUtils::splitFirst(third_line, ": ").second.trimmed(), Qt::ISODate); qDebug() << "Update available:" << version_name << version_tag << release_timestamp; qDebug() << "Update release notes:" << release_notes; offerUpdate(version_name, version_tag, release_notes); } break; default: // unknown error code { qDebug() << "Updater exited with unknown code" << exit_code; auto msgBox = QMessageBox(QMessageBox::Information, tr("Unknown Update Error"), tr("The updater exited with an unknown condition.\nExit Code: %1").arg(QString::number(exit_code)), QMessageBox::Ok, priv->parent); auto detail_txt = tr("StdOut: %1\nStdErr: %2").arg(QString(std_output)).arg(QString(std_error)); msgBox.setDetailedText(detail_txt); msgBox.setMinimumWidth(460); msgBox.adjustSize(); msgBox.exec(); } } priv->lastCheck = QDateTime::currentDateTime(); priv->settings->setValue("last_check", priv->lastCheck.toString(Qt::ISODate)); priv->settings->sync(); resetAutoCheckTimer(); } bool PrismExternalUpdater::getAutomaticallyChecksForUpdates() { return priv->autoCheck; } double PrismExternalUpdater::getUpdateCheckInterval() { return priv->updateInterval; } bool PrismExternalUpdater::getBetaAllowed() { return priv->allowBeta; } void PrismExternalUpdater::setAutomaticallyChecksForUpdates(bool check) { priv->autoCheck = check; priv->settings->setValue("auto_check", check); priv->settings->sync(); resetAutoCheckTimer(); } void PrismExternalUpdater::setUpdateCheckInterval(double seconds) { priv->updateInterval = seconds; priv->settings->setValue("update_interval", seconds); priv->settings->sync(); resetAutoCheckTimer(); } void PrismExternalUpdater::setBetaAllowed(bool allowed) { priv->allowBeta = allowed; priv->settings->setValue("auto_beta", allowed); priv->settings->sync(); } void PrismExternalUpdater::resetAutoCheckTimer() { if (priv->autoCheck && priv->updateInterval > 0) { int timeoutDuration = 0; auto now = QDateTime::currentDateTime(); if (priv->lastCheck.isValid()) { auto diff = priv->lastCheck.secsTo(now); auto secs_left = priv->updateInterval - diff; if (secs_left < 0) secs_left = 0; timeoutDuration = secs_left * 1000; // to msec } qDebug() << "Auto update timer starting," << timeoutDuration / 1000 << "seconds left"; priv->updateTimer.start(timeoutDuration); } else { if (priv->updateTimer.isActive()) priv->updateTimer.stop(); } } void PrismExternalUpdater::connectTimer() { connect(&priv->updateTimer, &QTimer::timeout, this, &PrismExternalUpdater::autoCheckTimerFired); } void PrismExternalUpdater::disconnectTimer() { disconnect(&priv->updateTimer, &QTimer::timeout, this, &PrismExternalUpdater::autoCheckTimerFired); } void PrismExternalUpdater::autoCheckTimerFired() { qDebug() << "Auto update Timer fired"; checkForUpdates(false); } void PrismExternalUpdater::offerUpdate(const QString& version_name, const QString& version_tag, const QString& release_notes) { priv->settings->beginGroup("skip"); auto should_skip = priv->settings->value(version_tag, false).toBool(); priv->settings->endGroup(); if (should_skip) { auto msgBox = QMessageBox(QMessageBox::Information, tr("No Update Available"), tr("There are no new updates available."), QMessageBox::Ok, priv->parent); msgBox.setMinimumWidth(460); msgBox.adjustSize(); msgBox.exec(); return; } UpdateAvailableDialog dlg(BuildConfig.printableVersionString(), version_name, release_notes); auto result = dlg.exec(); qDebug() << "offer dlg result" << result; switch (result) { case UpdateAvailableDialog::Install: { performUpdate(version_tag); return; } case UpdateAvailableDialog::Skip: { priv->settings->beginGroup("skip"); priv->settings->setValue(version_tag, true); priv->settings->endGroup(); priv->settings->sync(); return; } case UpdateAvailableDialog::DontInstall: { return; } } } void PrismExternalUpdater::performUpdate(const QString& version_tag) { QProcess proc; auto exe_name = QStringLiteral("%1_updater").arg(BuildConfig.LAUNCHER_APP_BINARY_NAME); #if defined Q_OS_WIN32 exe_name.append(".exe"); auto env = QProcessEnvironment::systemEnvironment(); env.insert("__COMPAT_LAYER", "RUNASINVOKER"); proc.setProcessEnvironment(env); #else exe_name = QString("bin/%1").arg(exe_name); #endif QStringList args = { "--dir", priv->dataDir.absolutePath(), "--install-version", version_tag }; if (priv->allowBeta) args.append("--pre-release"); auto result = proc.startDetached(priv->appDir.absoluteFilePath(exe_name), args); if (!result) { qDebug() << "Failed to start updater:" << proc.error() << proc.errorString(); } QCoreApplication::exit(); }
12,650
C++
.cpp
320
32.2625
137
0.646327
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,949
PrismUpdater.cpp
PrismLauncher_PrismLauncher/launcher/updater/prismupdater/PrismUpdater.cpp
// SPDX-FileCopyrightText: 2022 Rachel Powers <508861+Ryex@users.noreply.github.com> // // SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Rachel Powers <508861+Ryex@users.noreply.github.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #include "PrismUpdater.h" #include "BuildConfig.h" #include "ui/dialogs/ProgressDialog.h" #include <cstdlib> #include <iostream> #include <QDebug> #include <QAccessible> #include <QCommandLineParser> #include <QFileInfo> #include <QMessageBox> #include <QNetworkProxy> #include <QNetworkReply> #include <QNetworkRequest> #include <QProcess> #include <QProgressDialog> #include <memory> #include <sys.h> #if defined Q_OS_WIN32 #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #include <fcntl.h> #include <io.h> #include <stdio.h> #include <windows.h> #include <iostream> #endif // Snippet from https://github.com/gulrak/filesystem#using-it-as-single-file-header #ifdef __APPLE__ #include <Availability.h> // for deployment target to support pre-catalina targets without std::fs #endif // __APPLE__ #if ((defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) || (defined(__cplusplus) && __cplusplus >= 201703L)) && defined(__has_include) #if __has_include(<filesystem>) && (!defined(__MAC_OS_X_VERSION_MIN_REQUIRED) || __MAC_OS_X_VERSION_MIN_REQUIRED >= 101500) #define GHC_USE_STD_FS #include <filesystem> namespace fs = std::filesystem; #endif // MacOS min version check #endif // Other OSes version check #ifndef GHC_USE_STD_FS #include <ghc/filesystem.hpp> namespace fs = ghc::filesystem; #endif #include "DesktopServices.h" #include "updater/prismupdater/UpdaterDialogs.h" #include "FileSystem.h" #include "Json.h" #include "StringUtils.h" #include "net/Download.h" #include "net/RawHeaderProxy.h" #include "MMCZip.h" /** output to the log file */ void appDebugOutput(QtMsgType type, const QMessageLogContext& context, const QString& msg) { static std::mutex loggerMutex; const std::lock_guard<std::mutex> lock(loggerMutex); // synchronized, QFile logFile is not thread-safe QString out = qFormatLogMessage(type, context, msg); out += QChar::LineFeed; PrismUpdaterApp* app = static_cast<PrismUpdaterApp*>(QCoreApplication::instance()); app->logFile->write(out.toUtf8()); app->logFile->flush(); if (app->logToConsole) { QTextStream(stderr) << out.toLocal8Bit(); fflush(stderr); } } #if defined Q_OS_WIN32 // taken from https://stackoverflow.com/a/25927081 // getting a proper output to console with redirection support on windows is apparently hell void BindCrtHandlesToStdHandles(bool bindStdIn, bool bindStdOut, bool bindStdErr) { // Re-initialize the C runtime "FILE" handles with clean handles bound to "nul". We do this because it has been // observed that the file number of our standard handle file objects can be assigned internally to a value of -2 // when not bound to a valid target, which represents some kind of unknown internal invalid state. In this state our // call to "_dup2" fails, as it specifically tests to ensure that the target file number isn't equal to this value // before allowing the operation to continue. We can resolve this issue by first "re-opening" the target files to // use the "nul" device, which will place them into a valid state, after which we can redirect them to our target // using the "_dup2" function. if (bindStdIn) { FILE* dummyFile; freopen_s(&dummyFile, "nul", "r", stdin); } if (bindStdOut) { FILE* dummyFile; freopen_s(&dummyFile, "nul", "w", stdout); } if (bindStdErr) { FILE* dummyFile; freopen_s(&dummyFile, "nul", "w", stderr); } // Redirect unbuffered stdin from the current standard input handle if (bindStdIn) { HANDLE stdHandle = GetStdHandle(STD_INPUT_HANDLE); if (stdHandle != INVALID_HANDLE_VALUE) { int fileDescriptor = _open_osfhandle((intptr_t)stdHandle, _O_TEXT); if (fileDescriptor != -1) { FILE* file = _fdopen(fileDescriptor, "r"); if (file != NULL) { int dup2Result = _dup2(_fileno(file), _fileno(stdin)); if (dup2Result == 0) { setvbuf(stdin, NULL, _IONBF, 0); } } } } } // Redirect unbuffered stdout to the current standard output handle if (bindStdOut) { HANDLE stdHandle = GetStdHandle(STD_OUTPUT_HANDLE); if (stdHandle != INVALID_HANDLE_VALUE) { int fileDescriptor = _open_osfhandle((intptr_t)stdHandle, _O_TEXT); if (fileDescriptor != -1) { FILE* file = _fdopen(fileDescriptor, "w"); if (file != NULL) { int dup2Result = _dup2(_fileno(file), _fileno(stdout)); if (dup2Result == 0) { setvbuf(stdout, NULL, _IONBF, 0); } } } } } // Redirect unbuffered stderr to the current standard error handle if (bindStdErr) { HANDLE stdHandle = GetStdHandle(STD_ERROR_HANDLE); if (stdHandle != INVALID_HANDLE_VALUE) { int fileDescriptor = _open_osfhandle((intptr_t)stdHandle, _O_TEXT); if (fileDescriptor != -1) { FILE* file = _fdopen(fileDescriptor, "w"); if (file != NULL) { int dup2Result = _dup2(_fileno(file), _fileno(stderr)); if (dup2Result == 0) { setvbuf(stderr, NULL, _IONBF, 0); } } } } } // Clear the error state for each of the C++ standard stream objects. We need to do this, as attempts to access the // standard streams before they refer to a valid target will cause the iostream objects to enter an error state. In // versions of Visual Studio after 2005, this seems to always occur during startup regardless of whether anything // has been read from or written to the targets or not. if (bindStdIn) { std::wcin.clear(); std::cin.clear(); } if (bindStdOut) { std::wcout.clear(); std::cout.clear(); } if (bindStdErr) { std::wcerr.clear(); std::cerr.clear(); } } #endif PrismUpdaterApp::PrismUpdaterApp(int& argc, char** argv) : QApplication(argc, argv) { #if defined Q_OS_WIN32 // attach the parent console if stdout not already captured auto stdout_type = GetFileType(GetStdHandle(STD_OUTPUT_HANDLE)); if (stdout_type == FILE_TYPE_CHAR || stdout_type == FILE_TYPE_UNKNOWN) { if (AttachConsole(ATTACH_PARENT_PROCESS)) { BindCrtHandlesToStdHandles(true, true, true); consoleAttached = true; } } #endif setOrganizationName(BuildConfig.LAUNCHER_NAME); setOrganizationDomain(BuildConfig.LAUNCHER_DOMAIN); setApplicationName(BuildConfig.LAUNCHER_NAME + "Updater"); setApplicationVersion(BuildConfig.printableVersionString() + "\n" + BuildConfig.GIT_COMMIT); // Command line parsing QCommandLineParser parser; parser.setApplicationDescription(QObject::tr("An auto-updater for Prism Launcher")); parser.addOptions( { { { "d", "dir" }, tr("Use a custom path as application root (use '.' for current directory)."), tr("directory") }, { { "V", "prism-version" }, tr("Use this version as the installed launcher version. (provided because stdout can not be reliably captured on windows)"), tr("installed launcher version") }, { { "I", "install-version" }, "Install a specific version.", tr("version name") }, { { "U", "update-url" }, tr("Update from the specified repo."), tr("github repo url") }, { { "c", "check-only" }, tr("Only check if an update is needed. Exit status 100 if true, 0 if false (or non 0 if there was an error).") }, { { "p", "pre-release" }, tr("Allow updating to pre-release releases") }, { { "F", "force" }, tr("Force an update, even if one is not needed.") }, { { "l", "list" }, tr("List available releases.") }, { "debug", tr("Log debug to console.") }, { { "S", "select-ui" }, tr("Select the version to install with a GUI.") }, { { "D", "allow-downgrade" }, tr("Allow the updater to downgrade to previous versions.") } }); parser.addHelpOption(); parser.addVersionOption(); parser.process(arguments()); logToConsole = parser.isSet("debug"); auto updater_executable = QCoreApplication::applicationFilePath(); #ifdef Q_OS_MACOS showFatalErrorMessage(tr("MacOS Not Supported"), tr("The updater does not support installations on MacOS")); #endif if (updater_executable.startsWith("/tmp/.mount_")) { m_isAppimage = true; m_appimagePath = QProcessEnvironment::systemEnvironment().value(QStringLiteral("APPIMAGE")); if (m_appimagePath.isEmpty()) { showFatalErrorMessage(tr("Unsupported Installation"), tr("Updater is running as misconfigured AppImage? ($APPIMAGE environment variable is missing)")); } } m_isFlatpak = DesktopServices::isFlatpak(); QString prism_executable = FS::PathCombine(applicationDirPath(), BuildConfig.LAUNCHER_APP_BINARY_NAME); #if defined Q_OS_WIN32 prism_executable.append(".exe"); #endif if (!QFileInfo(prism_executable).isFile()) { showFatalErrorMessage(tr("Unsupported Installation"), tr("The updater can not find the main executable.")); } m_prismExecutable = prism_executable; auto prism_update_url = parser.value("update-url"); if (prism_update_url.isEmpty()) prism_update_url = BuildConfig.UPDATER_GITHUB_REPO; m_prismRepoUrl = QUrl::fromUserInput(prism_update_url); m_checkOnly = parser.isSet("check-only"); m_forceUpdate = parser.isSet("force"); m_printOnly = parser.isSet("list"); auto user_version = parser.value("install-version"); if (!user_version.isEmpty()) { m_userSelectedVersion = Version(user_version); } m_selectUI = parser.isSet("select-ui"); m_allowDowngrade = parser.isSet("allow-downgrade"); auto version = parser.value("prism-version"); if (!version.isEmpty()) { if (version.contains('-')) { auto index = version.indexOf('-'); m_prsimVersionChannel = version.mid(index + 1); version = version.left(index); } else { m_prsimVersionChannel = "stable"; } auto version_parts = version.split('.'); m_prismVersionMajor = version_parts.takeFirst().toInt(); m_prismVersionMinor = version_parts.takeFirst().toInt(); } m_allowPreRelease = parser.isSet("pre-release"); QString origCwdPath = QDir::currentPath(); QString binPath = applicationDirPath(); { // find data director // Root path is used for updates and portable data #if defined(Q_OS_LINUX) || defined(Q_OS_FREEBSD) || defined(Q_OS_OPENBSD) QDir foo(FS::PathCombine(binPath, "..")); // typically portable-root or /usr m_rootPath = foo.absolutePath(); #elif defined(Q_OS_WIN32) m_rootPath = binPath; #elif defined(Q_OS_MAC) QDir foo(FS::PathCombine(binPath, "../..")); m_rootPath = foo.absolutePath(); // on macOS, touch the root to force Finder to reload the .app metadata (and fix any icon change issues) FS::updateTimestamp(m_rootPath); #endif } QString adjustedBy; // change folder QString dirParam = parser.value("dir"); if (!dirParam.isEmpty()) { // the dir param. it makes prism launcher data path point to whatever the user specified // on command line adjustedBy = "Command line"; m_dataPath = dirParam; #ifndef Q_OS_MACOS if (QDir(FS::PathCombine(m_rootPath, "UserData")).exists()) { m_isPortable = true; } if (QFile::exists(FS::PathCombine(m_rootPath, "portable.txt"))) { m_isPortable = true; } #endif } else if (auto dataDirEnv = QProcessEnvironment::systemEnvironment().value(QString("%1_DATA_DIR").arg(BuildConfig.LAUNCHER_NAME.toUpper())); !dataDirEnv.isEmpty()) { adjustedBy = "System environment"; m_dataPath = dataDirEnv; #ifndef Q_OS_MACOS if (QFile::exists(FS::PathCombine(m_rootPath, "portable.txt"))) { m_isPortable = true; } #endif } else { QDir foo(FS::PathCombine(QStandardPaths::writableLocation(QStandardPaths::AppDataLocation), "..")); m_dataPath = foo.absolutePath(); adjustedBy = "Persistent data path"; #ifndef Q_OS_MACOS if (auto portableUserData = FS::PathCombine(m_rootPath, "UserData"); QDir(portableUserData).exists()) { m_dataPath = portableUserData; adjustedBy = "Portable user data path"; m_isPortable = true; } else if (QFile::exists(FS::PathCombine(m_rootPath, "portable.txt"))) { m_dataPath = m_rootPath; adjustedBy = "Portable data path"; m_isPortable = true; } #endif } m_updateLogPath = FS::PathCombine(m_dataPath, "logs", "prism_launcher_update.log"); { // setup logging FS::ensureFolderPathExists(FS::PathCombine(m_dataPath, "logs")); static const QString baseLogFile = BuildConfig.LAUNCHER_NAME + "Updater" + (m_checkOnly ? "-CheckOnly" : "") + "-%0.log"; static const QString logBase = FS::PathCombine(m_dataPath, "logs", baseLogFile); if (FS::ensureFolderPathExists("logs")) { // enough history to track both launches of the updater during a portable install FS::move(logBase.arg(1), logBase.arg(2)); FS::move(logBase.arg(0), logBase.arg(1)); } logFile = std::unique_ptr<QFile>(new QFile(logBase.arg(0))); if (!logFile->open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate)) { showFatalErrorMessage(tr("The launcher data folder is not writable!"), tr("The updater couldn't create a log file - the data folder is not writable.\n" "\n" "Make sure you have write permissions to the data folder.\n" "(%1)\n" "\n" "The updater cannot continue until you fix this problem.") .arg(m_dataPath)); return; } qInstallMessageHandler(appDebugOutput); qSetMessagePattern( "%{time process}" " " "%{if-debug}D%{endif}" "%{if-info}I%{endif}" "%{if-warning}W%{endif}" "%{if-critical}C%{endif}" "%{if-fatal}F%{endif}" " " "|" " " "%{if-category}[%{category}]: %{endif}" "%{message}"); bool foundLoggingRules = false; auto logRulesFile = QStringLiteral("qtlogging.ini"); auto logRulesPath = FS::PathCombine(m_dataPath, logRulesFile); qDebug() << "Testing" << logRulesPath << "..."; foundLoggingRules = QFile::exists(logRulesPath); // search the dataPath() // seach app data standard path if (!foundLoggingRules && !isPortable() && dirParam.isEmpty()) { logRulesPath = QStandardPaths::locate(QStandardPaths::AppDataLocation, FS::PathCombine("..", logRulesFile)); if (!logRulesPath.isEmpty()) { qDebug() << "Found" << logRulesPath << "..."; foundLoggingRules = true; } } // seach root path if (!foundLoggingRules) { logRulesPath = FS::PathCombine(m_rootPath, logRulesFile); qDebug() << "Testing" << logRulesPath << "..."; foundLoggingRules = QFile::exists(logRulesPath); } if (foundLoggingRules) { // load and set logging rules qDebug() << "Loading logging rules from:" << logRulesPath; QSettings loggingRules(logRulesPath, QSettings::IniFormat); loggingRules.beginGroup("Rules"); QStringList rule_names = loggingRules.childKeys(); QStringList rules; qDebug() << "Setting log rules:"; for (auto rule_name : rule_names) { auto rule = QString("%1=%2").arg(rule_name).arg(loggingRules.value(rule_name).toString()); rules.append(rule); qDebug() << " " << rule; } auto rules_str = rules.join("\n"); QLoggingCategory::setFilterRules(rules_str); } qDebug() << "<> Log initialized."; } { // log debug program info qDebug() << qPrintable(BuildConfig.LAUNCHER_DISPLAYNAME + " Updater, " + QString(BuildConfig.LAUNCHER_COPYRIGHT).replace("\n", ", ")); qDebug() << "Version : " << BuildConfig.printableVersionString(); qDebug() << "Git commit : " << BuildConfig.GIT_COMMIT; qDebug() << "Git refspec : " << BuildConfig.GIT_REFSPEC; qDebug() << "Compiled for : " << BuildConfig.systemID(); qDebug() << "Compiled by : " << BuildConfig.compilerID(); qDebug() << "Build Artifact : " << BuildConfig.BUILD_ARTIFACT; if (adjustedBy.size()) { qDebug() << "Data dir before adjustment : " << origCwdPath; qDebug() << "Data dir after adjustment : " << m_dataPath; qDebug() << "Adjusted by : " << adjustedBy; } else { qDebug() << "Data dir : " << QDir::currentPath(); } qDebug() << "Work dir : " << QDir::currentPath(); qDebug() << "Binary path : " << binPath; qDebug() << "Application root path : " << m_rootPath; qDebug() << "Portable install : " << m_isPortable; qDebug() << "<> Paths set."; } { // network m_network = makeShared<QNetworkAccessManager>(new QNetworkAccessManager()); qDebug() << "Detecting proxy settings..."; QNetworkProxy proxy = QNetworkProxy::applicationProxy(); m_network->setProxy(proxy); } auto marker_file_path = QDir(m_rootPath).absoluteFilePath(".prism_launcher_updater_unpack.marker"); auto marker_file = QFileInfo(marker_file_path); if (marker_file.exists()) { auto target_dir = QString(FS::read(marker_file_path)).trimmed(); if (target_dir.isEmpty()) { qWarning() << "Empty updater marker file contains no install target. making best guess of parent dir"; target_dir = QDir(m_rootPath).absoluteFilePath(".."); } QMetaObject::invokeMethod(this, [this, target_dir]() { moveAndFinishUpdate(target_dir); }, Qt::QueuedConnection); } else { QMetaObject::invokeMethod(this, &PrismUpdaterApp::loadReleaseList, Qt::QueuedConnection); } } PrismUpdaterApp::~PrismUpdaterApp() { qDebug() << "updater shutting down"; // Shut down logger by setting the logger function to nothing qInstallMessageHandler(nullptr); #if defined Q_OS_WIN32 // Detach from Windows console if (consoleAttached) { fclose(stdout); fclose(stdin); fclose(stderr); FreeConsole(); } #endif } void PrismUpdaterApp::fail(const QString& reason) { qCritical() << qPrintable(reason); m_status = Failed; exit(1); } void PrismUpdaterApp::abort(const QString& reason) { qCritical() << qPrintable(reason); m_status = Aborted; exit(2); } void PrismUpdaterApp::showFatalErrorMessage(const QString& title, const QString& content) { m_status = Failed; auto msgBox = new QMessageBox(); msgBox->setWindowTitle(title); msgBox->setText(content); msgBox->setStandardButtons(QMessageBox::Ok); msgBox->setDefaultButton(QMessageBox::Ok); msgBox->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextBrowserInteraction); msgBox->setIcon(QMessageBox::Critical); msgBox->setMinimumWidth(460); msgBox->adjustSize(); msgBox->exec(); exit(1); } void PrismUpdaterApp::run() { qDebug() << "found" << m_releases.length() << "releases on github"; qDebug() << "loading exe at " << m_prismExecutable; if (m_printOnly) { printReleases(); m_status = Succeeded; return exit(0); } if (!loadPrismVersionFromExe(m_prismExecutable)) { m_prismVersion = BuildConfig.printableVersionString(); m_prismVersionMajor = BuildConfig.VERSION_MAJOR; m_prismVersionMinor = BuildConfig.VERSION_MINOR; m_prsimVersionChannel = BuildConfig.VERSION_CHANNEL; m_prismGitCommit = BuildConfig.GIT_COMMIT; } m_status = Succeeded; qDebug() << "Executable reports as:" << m_prismBinaryName << "version:" << m_prismVersion; qDebug() << "Version major:" << m_prismVersionMajor; qDebug() << "Version minor:" << m_prismVersionMinor; qDebug() << "Version channel:" << m_prsimVersionChannel; qDebug() << "Git Commit:" << m_prismGitCommit; auto latest = getLatestRelease(); qDebug() << "Latest release" << latest.version; auto need_update = needUpdate(latest); if (m_checkOnly) { if (need_update) { QTextStream stdOutStream(stdout); stdOutStream << "Name: " << latest.name << "\n"; stdOutStream << "Version: " << latest.tag_name << "\n"; stdOutStream << "TimeStamp: " << latest.created_at.toString(Qt::ISODate) << "\n"; stdOutStream << latest.body << "\n"; stdOutStream.flush(); return exit(100); } else { return exit(0); } } if (m_isFlatpak) { showFatalErrorMessage(tr("Updating flatpack not supported"), tr("Actions outside of checking if an update is available are not " "supported when running the flatpak version of Prism Launcher.")); return; } if (m_isAppimage) { bool result = true; if (need_update) result = callAppImageUpdate(); return exit(result ? 0 : 1); } if (need_update || m_forceUpdate || !m_userSelectedVersion.isEmpty()) { GitHubRelease update_release = latest; if (!m_userSelectedVersion.isEmpty()) { bool found = false; for (auto rls : m_releases) { if (rls.version == m_userSelectedVersion) { found = true; update_release = rls; break; } } if (!found) { showFatalErrorMessage( "No release for version!", QString("Can not find a github release for specified version %1").arg(m_userSelectedVersion.toString())); return; } } else if (m_selectUI) { update_release = selectRelease(); if (!update_release.isValid()) { showFatalErrorMessage("No version selected.", "No version was selected."); return; } } performUpdate(update_release); } exit(0); } void PrismUpdaterApp::moveAndFinishUpdate(QDir target) { logUpdate("Finishing update process"); logUpdate("Waiting 2 seconds for resources to free"); this->thread()->sleep(2); auto manifest_path = FS::PathCombine(m_rootPath, "manifest.txt"); QFileInfo manifest(manifest_path); auto app_dir = QDir(m_rootPath); QStringList file_list; if (manifest.isFile()) { // load manifest from file logUpdate(tr("Reading manifest from %1").arg(manifest.absoluteFilePath())); try { auto contents = QString::fromUtf8(FS::read(manifest.absoluteFilePath())); auto files = contents.split('\n'); for (auto file : files) { file_list.append(file.trimmed()); } } catch (FS::FileSystemException&) { } } if (file_list.isEmpty()) { logUpdate(tr("Manifest empty, making best guess of the directory contents of %1").arg(m_rootPath)); auto entries = target.entryInfoList(QDir::NoDotAndDotDot | QDir::Files | QDir::Dirs); for (auto entry : entries) { file_list.append(entry.fileName()); } } logUpdate(tr("Installing the following to %1 :\n %2").arg(target.absolutePath()).arg(file_list.join(",\n "))); bool error = false; QProgressDialog progress(tr("Installing from %1").arg(m_rootPath), "", 0, file_list.length()); progress.setCancelButton(nullptr); progress.setMinimumWidth(400); progress.adjustSize(); progress.show(); QCoreApplication::processEvents(); logUpdate(tr("Installing from %1").arg(m_rootPath)); auto copy = [this, app_dir, target](QString to_install_file) { auto rel_path = app_dir.relativeFilePath(to_install_file); auto install_path = FS::PathCombine(target.absolutePath(), rel_path); logUpdate(tr("Installing %1 from %2").arg(install_path).arg(to_install_file)); FS::ensureFilePathExists(install_path); auto result = FS::copy(to_install_file, install_path).overwrite(true)(); if (!result) { logUpdate(tr("Failed copy %1 to %2").arg(to_install_file).arg(install_path)); return true; } return false; }; int i = 0; for (auto glob : file_list) { QDirIterator iter(m_rootPath, QStringList({ glob }), QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot); progress.setValue(i); QCoreApplication::processEvents(); if (!iter.hasNext() && !glob.isEmpty()) { if (auto file_info = QFileInfo(FS::PathCombine(m_rootPath, glob)); file_info.exists()) { error |= copy(file_info.absoluteFilePath()); } else { logUpdate(tr("File doesn't exist, ignoring: %1").arg(FS::PathCombine(m_rootPath, glob))); } } else { while (iter.hasNext()) { error |= copy(iter.next()); } } i++; } progress.setValue(i); QCoreApplication::processEvents(); if (error) { logUpdate(tr("There were errors installing the update.")); auto fail_marker = FS::PathCombine(m_dataPath, ".prism_launcher_update.fail"); FS::copy(m_updateLogPath, fail_marker).overwrite(true)(); } else { logUpdate(tr("Update succeed.")); auto success_marker = FS::PathCombine(m_dataPath, ".prism_launcher_update.success"); FS::copy(m_updateLogPath, success_marker).overwrite(true)(); } auto update_lock_path = FS::PathCombine(m_dataPath, ".prism_launcher_update.lock"); FS::deletePath(update_lock_path); QProcess proc; auto app_exe_name = BuildConfig.LAUNCHER_APP_BINARY_NAME; #if defined Q_OS_WIN32 app_exe_name.append(".exe"); auto env = QProcessEnvironment::systemEnvironment(); env.insert("__COMPAT_LAYER", "RUNASINVOKER"); proc.setProcessEnvironment(env); #else app_exe_name.prepend("bin/"); #endif auto app_exe_path = target.absoluteFilePath(app_exe_name); proc.startDetached(app_exe_path); exit(error ? 1 : 0); } void PrismUpdaterApp::printReleases() { for (auto release : m_releases) { std::cout << release.name.toStdString() << " Version: " << release.tag_name.toStdString() << std::endl; } } QList<GitHubRelease> PrismUpdaterApp::nonDraftReleases() { QList<GitHubRelease> nonDraft; for (auto rls : m_releases) { if (rls.isValid() && !rls.draft) nonDraft.append(rls); } return nonDraft; } QList<GitHubRelease> PrismUpdaterApp::newerReleases() { QList<GitHubRelease> newer; for (auto rls : nonDraftReleases()) { if (rls.version > m_prismVersion) newer.append(rls); } return newer; } GitHubRelease PrismUpdaterApp::selectRelease() { QList<GitHubRelease> releases; if (m_allowDowngrade) { releases = nonDraftReleases(); } else { releases = newerReleases(); } if (releases.isEmpty()) return {}; SelectReleaseDialog dlg(Version(m_prismVersion), releases); auto result = dlg.exec(); if (result == QDialog::Rejected) { return {}; } GitHubRelease release = dlg.selectedRelease(); return release; } QList<GitHubReleaseAsset> PrismUpdaterApp::validReleaseArtifacts(const GitHubRelease& release) { QList<GitHubReleaseAsset> valid; qDebug() << "Selecting best asset from" << release.tag_name << "for platform" << BuildConfig.BUILD_ARTIFACT << "portable:" << m_isPortable; if (BuildConfig.BUILD_ARTIFACT.isEmpty()) qWarning() << "Build platform is not set!"; for (auto asset : release.assets) { if (asset.name.endsWith(".zsync")) { qDebug() << "Rejecting zsync file" << asset.name; continue; } if (!m_isAppimage && asset.name.toLower().endsWith("appimage")) { qDebug() << "Rejecting" << asset.name << "because it is an AppImage"; continue; } else if (m_isAppimage && !asset.name.toLower().endsWith("appimage")) { qDebug() << "Rejecting" << asset.name << "because it is not an AppImage"; continue; } auto asset_name = asset.name.toLower(); auto [platform, platform_qt_ver] = StringUtils::splitFirst(BuildConfig.BUILD_ARTIFACT.toLower(), "-qt"); auto system_is_arm = QSysInfo::buildCpuArchitecture().contains("arm64"); auto asset_is_arm = asset_name.contains("arm64"); auto asset_is_archive = asset_name.endsWith(".zip") || asset_name.endsWith(".tar.gz"); bool for_platform = !platform.isEmpty() && asset_name.contains(platform); if (!for_platform) { qDebug() << "Rejecting" << asset.name << "because platforms do not match"; } bool for_portable = asset_name.contains("portable"); if (for_platform && asset_name.contains("legacy") && !platform.contains("legacy")) { qDebug() << "Rejecting" << asset.name << "because platforms do not match"; for_platform = false; } if (for_platform && ((asset_is_arm && !system_is_arm) || (!asset_is_arm && system_is_arm))) { qDebug() << "Rejecting" << asset.name << "because architecture does not match"; for_platform = false; } if (for_platform && platform.contains("windows") && !m_isPortable && asset_is_archive) { qDebug() << "Rejecting" << asset.name << "because it is not an installer"; for_platform = false; } auto qt_pattern = QRegularExpression("-qt(\\d+)"); auto qt_match = qt_pattern.match(asset_name); if (for_platform && qt_match.hasMatch()) { if (platform_qt_ver.isEmpty() || platform_qt_ver.toInt() != qt_match.captured(1).toInt()) { qDebug() << "Rejecting" << asset.name << "because it is not for the correct qt version" << platform_qt_ver.toInt() << "vs" << qt_match.captured(1).toInt(); for_platform = false; } } if (((m_isPortable && for_portable) || (!m_isPortable && !for_portable)) && for_platform) { qDebug() << "Accepting" << asset.name; valid.append(asset); } } return valid; } GitHubReleaseAsset PrismUpdaterApp::selectAsset(const QList<GitHubReleaseAsset>& assets) { SelectReleaseAssetDialog dlg(assets); auto result = dlg.exec(); if (result == QDialog::Rejected) { return {}; } GitHubReleaseAsset asset = dlg.selectedAsset(); return asset; } void PrismUpdaterApp::performUpdate(const GitHubRelease& release) { m_install_release = release; qDebug() << "Updating to" << release.tag_name; auto valid_assets = validReleaseArtifacts(release); qDebug() << "valid release assets:" << valid_assets; GitHubReleaseAsset selected_asset; if (valid_assets.isEmpty()) { return showFatalErrorMessage( tr("No Valid Release Assets"), tr("Github release %1 has no valid assets for this platform: %2") .arg(release.tag_name) .arg(tr("%1 portable: %2").arg(BuildConfig.BUILD_ARTIFACT).arg(m_isPortable ? tr("yes") : tr("no")))); } else if (valid_assets.length() > 1) { selected_asset = selectAsset(valid_assets); } else { selected_asset = valid_assets.takeFirst(); } if (!selected_asset.isValid()) { return showFatalErrorMessage(tr("No version selected."), tr("No version was selected.")); } qDebug() << "will install" << selected_asset; auto file = downloadAsset(selected_asset); if (!file.exists()) { return showFatalErrorMessage(tr("Failed to Download"), tr("Failed to download the selected asset.")); } performInstall(file); } QFileInfo PrismUpdaterApp::downloadAsset(const GitHubReleaseAsset& asset) { auto temp_dir = QDir::tempPath(); auto file_url = QUrl(asset.browser_download_url); auto out_file_path = FS::PathCombine(temp_dir, file_url.fileName()); qDebug() << "downloading" << file_url << "to" << out_file_path; auto download = Net::Download::makeFile(file_url, out_file_path); download->setNetwork(m_network); auto progress_dialog = ProgressDialog(); progress_dialog.adjustSize(); progress_dialog.execWithTask(download.get()); qDebug() << "download complete"; QFileInfo out_file(out_file_path); return out_file; } bool PrismUpdaterApp::callAppImageUpdate() { auto appimage_path = QProcessEnvironment::systemEnvironment().value(QStringLiteral("APPIMAGE")); QProcess proc = QProcess(); qDebug() << "Calling: AppImageUpdate" << appimage_path; proc.setProgram(FS::PathCombine(m_rootPath, "bin", "AppImageUpdate-x86_64.AppImage")); proc.setArguments({ appimage_path }); auto result = proc.startDetached(); if (!result) qDebug() << "Failed to start AppImageUpdate reason:" << proc.errorString(); return result; } void PrismUpdaterApp::clearUpdateLog() { FS::deletePath(m_updateLogPath); } void PrismUpdaterApp::logUpdate(const QString& msg) { qDebug() << qUtf8Printable(msg); FS::append(m_updateLogPath, QStringLiteral("%1\n").arg(msg).toUtf8()); } std::tuple<QDateTime, QString, QString, QString, QString> read_lock_File(const QString& path) { auto contents = QString(FS::read(path)); auto lines = contents.split('\n'); QDateTime timestamp; QString from, to, target, data_path; for (auto line : lines) { auto index = line.indexOf("="); if (index < 0) continue; auto left = line.left(index); auto right = line.mid(index + 1); if (left.toLower() == "timestamp") { timestamp = QDateTime::fromString(right, Qt::ISODate); } else if (left.toLower() == "from") { from = right; } else if (left.toLower() == "to") { to = right; } else if (left.toLower() == "target") { target = right; } else if (left.toLower() == "data_path") { data_path = right; } } return std::make_tuple(timestamp, from, to, target, data_path); } bool write_lock_file(const QString& path, QDateTime timestamp, QString from, QString to, QString target, QString data_path) { try { FS::write(path, QStringLiteral("TIMESTAMP=%1\nFROM=%2\nTO=%3\nTARGET=%4\nDATA_PATH=%5\n") .arg(timestamp.toString(Qt::ISODate)) .arg(from) .arg(to) .arg(target) .arg(data_path) .toUtf8()); } catch (FS::FileSystemException& err) { qWarning() << "Error writing lockfile:" << err.what() << "\n" << err.cause(); return false; } return true; } void PrismUpdaterApp::performInstall(QFileInfo file) { qDebug() << "starting install"; auto update_lock_path = FS::PathCombine(m_dataPath, ".prism_launcher_update.lock"); QFileInfo update_lock(update_lock_path); if (update_lock.exists()) { auto [timestamp, from, to, target, data_path] = read_lock_File(update_lock_path); auto msg = tr("Update already in progress\n"); auto infoMsg = tr("This installation has a update lock file present at: %1\n" "\n" "Timestamp: %2\n" "Updating from version %3 to %4\n" "Target install path: %5\n" "Data Path: %6" "\n" "This likely means that a previous update attempt failed. Please ensure your installation is in working order before " "proceeding.\n" "Check the Prism Launcher updater log at: \n" "%7\n" "for details on the last update attempt.\n" "\n" "To overwrite this lock and proceed with this update anyway, select \"Ignore\" below.") .arg(update_lock_path) .arg(timestamp.toString(Qt::ISODate), from, to, target, data_path) .arg(m_updateLogPath); QMessageBox msgBox; msgBox.setText(msg); msgBox.setInformativeText(infoMsg); msgBox.setStandardButtons(QMessageBox::Ignore | QMessageBox::Cancel); msgBox.setDefaultButton(QMessageBox::Cancel); msgBox.setMinimumWidth(460); msgBox.adjustSize(); switch (msgBox.exec()) { case QMessageBox::AcceptRole: break; case QMessageBox::RejectRole: [[fallthrough]]; default: return showFatalErrorMessage(tr("Update Aborted"), tr("The update attempt was aborted")); } } clearUpdateLog(); auto changelog_path = FS::PathCombine(m_dataPath, ".prism_launcher_update.changelog"); FS::write(changelog_path, m_install_release.body.toUtf8()); logUpdate(tr("Updating from %1 to %2").arg(m_prismVersion).arg(m_install_release.tag_name)); if (m_isPortable || file.fileName().endsWith(".zip") || file.fileName().endsWith(".tar.gz")) { write_lock_file(update_lock_path, QDateTime::currentDateTime(), m_prismVersion, m_install_release.tag_name, m_rootPath, m_dataPath); logUpdate(tr("Updating portable install at %1").arg(m_rootPath)); unpackAndInstall(file); } else { logUpdate(tr("Running installer file at %1").arg(file.absoluteFilePath())); QProcess proc = QProcess(); #if defined Q_OS_WIN auto env = QProcessEnvironment::systemEnvironment(); env.insert("__COMPAT_LAYER", "RUNASINVOKER"); proc.setProcessEnvironment(env); #endif proc.setProgram(file.absoluteFilePath()); bool result = proc.startDetached(); logUpdate(tr("Process start result: %1").arg(result ? tr("yes") : tr("no"))); exit(result ? 0 : 1); } } void PrismUpdaterApp::unpackAndInstall(QFileInfo archive) { logUpdate(tr("Backing up install")); backupAppDir(); if (auto loc = unpackArchive(archive)) { auto marker_file_path = loc.value().absoluteFilePath(".prism_launcher_updater_unpack.marker"); FS::write(marker_file_path, m_rootPath.toUtf8()); QProcess proc = QProcess(); auto exe_name = QStringLiteral("%1_updater").arg(BuildConfig.LAUNCHER_APP_BINARY_NAME); #if defined Q_OS_WIN32 exe_name.append(".exe"); auto env = QProcessEnvironment::systemEnvironment(); env.insert("__COMPAT_LAYER", "RUNASINVOKER"); proc.setProcessEnvironment(env); #else exe_name.prepend("bin/"); #endif auto new_updater_path = loc.value().absoluteFilePath(exe_name); logUpdate(tr("Starting new updater at '%1'").arg(new_updater_path)); if (!proc.startDetached(new_updater_path, { "-d", m_dataPath }, loc.value().absolutePath())) { logUpdate(tr("Failed to launch '%1' %2").arg(new_updater_path).arg(proc.errorString())); return exit(10); } return exit(); // up to the new updater now } return exit(1); // unpack failure } void PrismUpdaterApp::backupAppDir() { auto manifest_path = FS::PathCombine(m_rootPath, "manifest.txt"); QFileInfo manifest(manifest_path); QStringList file_list; if (manifest.isFile()) { // load manifest from file logUpdate(tr("Reading manifest from %1").arg(manifest.absoluteFilePath())); try { auto contents = QString::fromUtf8(FS::read(manifest.absoluteFilePath())); auto files = contents.split('\n'); for (auto file : files) { file_list.append(file.trimmed()); } } catch (FS::FileSystemException&) { } } if (file_list.isEmpty()) { // best guess if (BuildConfig.BUILD_ARTIFACT.toLower().contains("linux")) { file_list.append({ "PrismLauncher", "bin", "share", "lib" }); } else { // windows by process of elimination file_list.append({ "jars", "prismlauncher.exe", "prismlauncher_filelink.exe", "prismlauncher_updater.exe", "qtlogging.ini", "imageformats", "iconengines", "platforms", "styles", "tls", "qt.conf", "Qt*.dll", }); } logUpdate("manifest.txt empty or missing. making best guess at files to back up."); } logUpdate(tr("Backing up:\n %1").arg(file_list.join(",\n "))); auto app_dir = QDir(m_rootPath); auto backup_dir = FS::PathCombine( app_dir.absolutePath(), QStringLiteral("backup_") + QString(m_prismVersion).replace(QRegularExpression("[" + QRegularExpression::escape("\\/:*?\"<>|") + "]"), QString("_")) + "-" + m_prismGitCommit); FS::ensureFolderPathExists(backup_dir); auto backup_marker_path = FS::PathCombine(m_dataPath, ".prism_launcher_update_backup_path.txt"); FS::write(backup_marker_path, backup_dir.toUtf8()); QProgressDialog progress(tr("Backing up install at %1").arg(m_rootPath), "", 0, file_list.length()); progress.setCancelButton(nullptr); progress.setMinimumWidth(400); progress.adjustSize(); progress.show(); QCoreApplication::processEvents(); logUpdate(tr("Backing up install at %1").arg(m_rootPath)); auto copy = [this, app_dir, backup_dir](QString to_bak_file) { auto rel_path = app_dir.relativeFilePath(to_bak_file); auto bak_path = FS::PathCombine(backup_dir, rel_path); logUpdate(tr("Backing up and then removing %1").arg(to_bak_file)); FS::ensureFilePathExists(bak_path); auto result = FS::copy(to_bak_file, bak_path).overwrite(true)(); if (!result) { logUpdate(tr("Failed to backup %1 to %2").arg(to_bak_file).arg(bak_path)); } else { if (!FS::deletePath(to_bak_file)) logUpdate(tr("Failed to remove %1").arg(to_bak_file)); } }; int i = 0; for (auto glob : file_list) { QDirIterator iter(app_dir.absolutePath(), QStringList({ glob }), QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot); progress.setValue(i); QCoreApplication::processEvents(); if (!iter.hasNext() && !glob.isEmpty()) { if (auto file_info = QFileInfo(FS::PathCombine(app_dir.absolutePath(), glob)); file_info.exists()) { copy(file_info.absoluteFilePath()); } else { logUpdate(tr("File doesn't exist, ignoring: %1").arg(FS::PathCombine(app_dir.absolutePath(), glob))); } } else { while (iter.hasNext()) { copy(iter.next()); } } i++; } progress.setValue(i); QCoreApplication::processEvents(); } std::optional<QDir> PrismUpdaterApp::unpackArchive(QFileInfo archive) { auto temp_extract_path = FS::PathCombine(m_dataPath, "prism_launcher_update_release"); FS::ensureFolderPathExists(temp_extract_path); auto tmp_extract_dir = QDir(temp_extract_path); if (archive.fileName().endsWith(".zip")) { auto result = MMCZip::extractDir(archive.absoluteFilePath(), tmp_extract_dir.absolutePath()); if (result) { logUpdate(tr("Extracted the following to \"%1\":\n %2").arg(tmp_extract_dir.absolutePath()).arg(result->join("\n "))); } else { logUpdate(tr("Failed to extract %1 to %2").arg(archive.absoluteFilePath()).arg(tmp_extract_dir.absolutePath())); showFatalErrorMessage("Failed to extract archive", tr("Failed to extract %1 to %2").arg(archive.absoluteFilePath()).arg(tmp_extract_dir.absolutePath())); return std::nullopt; } } else if (archive.fileName().endsWith(".tar.gz")) { QString cmd = "tar"; QStringList args = { "-xvf", archive.absoluteFilePath(), "-C", tmp_extract_dir.absolutePath() }; logUpdate(tr("Running: `%1 %2`").arg(cmd).arg(args.join(" "))); QProcess proc = QProcess(); proc.start(cmd, args); if (!proc.waitForStarted(5000)) { // wait 5 seconds to start auto msg = tr("Failed to launch child process \"%1 %2\".").arg(cmd).arg(args.join(" ")); logUpdate(msg); showFatalErrorMessage(tr("Failed extract archive"), msg); return std::nullopt; } auto result = proc.waitForFinished(5000); auto out = proc.readAll(); logUpdate(out); if (!result) { auto msg = tr("Child process \"%1 %2\" failed.").arg(cmd).arg(args.join(" ")); logUpdate(msg); showFatalErrorMessage(tr("Failed to extract archive"), msg); return std::nullopt; } } else { logUpdate(tr("Unknown archive format for %1").arg(archive.absoluteFilePath())); showFatalErrorMessage("Can not extract", QStringLiteral("Unknown archive format %1").arg(archive.absoluteFilePath())); return std::nullopt; } return tmp_extract_dir; } bool PrismUpdaterApp::loadPrismVersionFromExe(const QString& exe_path) { QProcess proc = QProcess(); proc.setProcessChannelMode(QProcess::MergedChannels); proc.setReadChannel(QProcess::StandardOutput); proc.start(exe_path, { "--version" }); if (!proc.waitForStarted(5000)) { showFatalErrorMessage(tr("Failed to Check Version"), tr("Failed to launch child process to read version.")); return false; } // wait 5 seconds to start if (!proc.waitForFinished(5000)) { showFatalErrorMessage(tr("Failed to Check Version"), tr("Child launcher process failed.")); return false; } auto out = proc.readAllStandardOutput(); auto lines = out.split('\n'); lines.removeAll(""); if (lines.length() < 2) return false; else if (lines.length() > 2) { auto line1 = lines.takeLast(); auto line2 = lines.takeLast(); lines = { line2, line1 }; } auto first = lines.takeFirst(); auto first_parts = first.split(' '); if (first_parts.length() < 2) return false; m_prismBinaryName = first_parts.takeFirst(); auto version = first_parts.takeFirst().trimmed(); m_prismVersion = version; if (version.contains('-')) { auto index = version.indexOf('-'); m_prsimVersionChannel = version.mid(index + 1); version = version.left(index); } else { m_prsimVersionChannel = "stable"; } auto version_parts = version.split('.'); if (version_parts.length() < 2) return false; m_prismVersionMajor = version_parts.takeFirst().toInt(); m_prismVersionMinor = version_parts.takeFirst().toInt(); m_prismGitCommit = lines.takeFirst().simplified(); return true; } void PrismUpdaterApp::loadReleaseList() { auto github_repo = m_prismRepoUrl; if (github_repo.host() != "github.com") return fail("updating from a non github url is not supported"); auto path_parts = github_repo.path().split('/'); path_parts.removeFirst(); // empty segment from leading / auto repo_owner = path_parts.takeFirst(); auto repo_name = path_parts.takeFirst(); auto api_url = QString("https://api.github.com/repos/%1/%2/releases").arg(repo_owner, repo_name); qDebug() << "Fetching release list from" << api_url; downloadReleasePage(api_url, 1); } void PrismUpdaterApp::downloadReleasePage(const QString& api_url, int page) { int per_page = 30; auto page_url = QString("%1?per_page=%2&page=%3").arg(api_url).arg(QString::number(per_page)).arg(QString::number(page)); auto response = std::make_shared<QByteArray>(); auto download = Net::Download::makeByteArray(page_url, response); download->setNetwork(m_network); m_current_url = page_url; auto github_api_headers = new Net::RawHeaderProxy(); github_api_headers->addHeaders({ { "Accept", "application/vnd.github+json" }, { "X-GitHub-Api-Version", "2022-11-28" }, }); download->addHeaderProxy(github_api_headers); connect(download.get(), &Net::Download::succeeded, this, [this, response, per_page, api_url, page]() { int num_found = parseReleasePage(response.get()); if (!(num_found < per_page)) { // there may be more, fetch next page downloadReleasePage(api_url, page + 1); } else { run(); } }); connect(download.get(), &Net::Download::failed, this, &PrismUpdaterApp::downloadError); m_current_task.reset(download); connect(download.get(), &Net::Download::finished, this, [this]() { qDebug() << "Download" << m_current_task->getUid().toString() << "finished"; m_current_task.reset(); m_current_url = ""; }); QCoreApplication::processEvents(); QMetaObject::invokeMethod(download.get(), &Task::start, Qt::QueuedConnection); } int PrismUpdaterApp::parseReleasePage(const QByteArray* response) { if (response->isEmpty()) // empty page return 0; int num_releases = 0; try { auto doc = Json::requireDocument(*response); auto release_list = Json::requireArray(doc); for (auto release_json : release_list) { auto release_obj = Json::requireObject(release_json); GitHubRelease release = {}; release.id = Json::requireInteger(release_obj, "id"); release.name = Json::ensureString(release_obj, "name"); release.tag_name = Json::requireString(release_obj, "tag_name"); release.created_at = QDateTime::fromString(Json::requireString(release_obj, "created_at"), Qt::ISODate); release.published_at = QDateTime::fromString(Json::ensureString(release_obj, "published_at"), Qt::ISODate); release.draft = Json::requireBoolean(release_obj, "draft"); release.prerelease = Json::requireBoolean(release_obj, "prerelease"); release.body = Json::ensureString(release_obj, "body"); release.version = Version(release.tag_name); auto release_assets_obj = Json::requireArray(release_obj, "assets"); for (auto asset_json : release_assets_obj) { auto asset_obj = Json::requireObject(asset_json); GitHubReleaseAsset asset = {}; asset.id = Json::requireInteger(asset_obj, "id"); asset.name = Json::requireString(asset_obj, "name"); asset.label = Json::ensureString(asset_obj, "label"); asset.content_type = Json::requireString(asset_obj, "content_type"); asset.size = Json::requireInteger(asset_obj, "size"); asset.created_at = QDateTime::fromString(Json::requireString(asset_obj, "created_at"), Qt::ISODate); asset.updated_at = QDateTime::fromString(Json::requireString(asset_obj, "updated_at"), Qt::ISODate); asset.browser_download_url = Json::requireString(asset_obj, "browser_download_url"); release.assets.append(asset); } m_releases.append(release); num_releases++; } } catch (Json::JsonException& e) { auto err_msg = QString("Failed to parse releases from github: %1\n%2").arg(e.what()).arg(QString::fromStdString(response->toStdString())); fail(err_msg); } return num_releases; } GitHubRelease PrismUpdaterApp::getLatestRelease() { GitHubRelease latest; for (auto release : m_releases) { if (release.draft) continue; if (release.prerelease && !m_allowPreRelease) continue; if (!latest.isValid() || (release.version > latest.version)) { latest = release; } } return latest; } bool PrismUpdaterApp::needUpdate(const GitHubRelease& release) { auto current_ver = Version(QString("%1.%2").arg(QString::number(m_prismVersionMajor)).arg(QString::number(m_prismVersionMinor))); return current_ver < release.version; } void PrismUpdaterApp::downloadError(QString reason) { fail(QString("Network request Failed: %1 with reason %2").arg(m_current_url).arg(reason)); }
54,582
C++
.cpp
1,243
35.695897
140
0.616321
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,950
updater_main.cpp
PrismLauncher_PrismLauncher/launcher/updater/prismupdater/updater_main.cpp
// SPDX-FileCopyrightText: 2022 Rachel Powers <508861+Ryex@users.noreply.github.com> // // SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Rachel Powers <508861+Ryex@users.noreply.github.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #include "PrismUpdater.h" int main(int argc, char* argv[]) { PrismUpdaterApp wUpApp(argc, argv); switch (wUpApp.status()) { case PrismUpdaterApp::Starting: case PrismUpdaterApp::Initialized: { return wUpApp.exec(); } case PrismUpdaterApp::Failed: return 1; case PrismUpdaterApp::Succeeded: return 0; default: return -1; } }
1,285
C++
.cpp
37
30.297297
84
0.697189
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,951
GitHubRelease.cpp
PrismLauncher_PrismLauncher/launcher/updater/prismupdater/GitHubRelease.cpp
// SPDX-FileCopyrightText: 2023 Rachel Powers <508861+Ryex@users.noreply.github.com> // // SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2023 Rachel Powers <508861+Ryex@users.noreply.github.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #include "GitHubRelease.h" QDebug operator<<(QDebug debug, const GitHubReleaseAsset& asset) { QDebugStateSaver saver(debug); debug.nospace() << "GitHubReleaseAsset( " "id: " << asset.id << ", " "name " << asset.name << ", " "label: " << asset.label << ", " "content_type: " << asset.content_type << ", " "size: " << asset.size << ", " "created_at: " << asset.created_at << ", " "updated_at: " << asset.updated_at << ", " "browser_download_url: " << asset.browser_download_url << " " ")"; return debug; } QDebug operator<<(QDebug debug, const GitHubRelease& rls) { QDebugStateSaver saver(debug); debug.nospace() << "GitHubRelease( " "id: " << rls.id << ", " "name " << rls.name << ", " "tag_name: " << rls.tag_name << ", " "created_at: " << rls.created_at << ", " "published_at: " << rls.published_at << ", " "prerelease: " << rls.prerelease << ", " "draft: " << rls.draft << ", " "version" << rls.version << ", " "body: " << rls.body << ", " "assets: " << rls.assets << " " ")"; return debug; }
3,053
C++
.cpp
89
19.550562
84
0.40473
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,952
UpdaterDialogs.cpp
PrismLauncher_PrismLauncher/launcher/updater/prismupdater/UpdaterDialogs.cpp
// SPDX-FileCopyrightText: 2023 Rachel Powers <508861+Ryex@users.noreply.github.com> // // SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2023 Rachel Powers <508861+Ryex@users.noreply.github.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #include "UpdaterDialogs.h" #include "ui_SelectReleaseDialog.h" #include <QPushButton> #include <QTextBrowser> #include "Markdown.h" #include "StringUtils.h" SelectReleaseDialog::SelectReleaseDialog(const Version& current_version, const QList<GitHubRelease>& releases, QWidget* parent) : QDialog(parent), m_releases(releases), m_currentVersion(current_version), ui(new Ui::SelectReleaseDialog) { ui->setupUi(this); ui->changelogTextBrowser->setOpenExternalLinks(true); ui->changelogTextBrowser->setLineWrapMode(QTextBrowser::LineWrapMode::WidgetWidth); ui->changelogTextBrowser->setVerticalScrollBarPolicy(Qt::ScrollBarPolicy::ScrollBarAsNeeded); ui->versionsTree->setColumnCount(2); ui->versionsTree->header()->setSectionResizeMode(0, QHeaderView::Stretch); ui->versionsTree->header()->setSectionResizeMode(1, QHeaderView::ResizeToContents); ui->versionsTree->setHeaderLabels({ tr("Version"), tr("Published Date") }); ui->versionsTree->header()->setStretchLastSection(false); ui->eplainLabel->setText(tr("Select a version to install.\n" "\n" "Currently installed version: %1") .arg(m_currentVersion.toString())); loadReleases(); connect(ui->versionsTree, &QTreeWidget::currentItemChanged, this, &SelectReleaseDialog::selectionChanged); connect(ui->buttonBox, &QDialogButtonBox::accepted, this, &SelectReleaseDialog::accept); connect(ui->buttonBox, &QDialogButtonBox::rejected, this, &SelectReleaseDialog::reject); ui->buttonBox->button(QDialogButtonBox::Cancel)->setText(tr("Cancel")); ui->buttonBox->button(QDialogButtonBox::Ok)->setText(tr("OK")); } SelectReleaseDialog::~SelectReleaseDialog() { delete ui; } void SelectReleaseDialog::loadReleases() { for (auto rls : m_releases) { appendRelease(rls); } } void SelectReleaseDialog::appendRelease(GitHubRelease const& release) { auto rls_item = new QTreeWidgetItem(ui->versionsTree); rls_item->setText(0, release.tag_name); rls_item->setExpanded(true); rls_item->setText(1, release.published_at.toString()); rls_item->setData(0, Qt::UserRole, QVariant(release.id)); ui->versionsTree->addTopLevelItem(rls_item); } GitHubRelease SelectReleaseDialog::getRelease(QTreeWidgetItem* item) { int id = item->data(0, Qt::UserRole).toInt(); GitHubRelease release; for (auto rls : m_releases) { if (rls.id == id) release = rls; } return release; } void SelectReleaseDialog::selectionChanged(QTreeWidgetItem* current, QTreeWidgetItem* previous) { GitHubRelease release = getRelease(current); QString body = markdownToHTML(release.body.toUtf8()); m_selectedRelease = release; ui->changelogTextBrowser->setHtml(StringUtils::htmlListPatch(body)); } SelectReleaseAssetDialog::SelectReleaseAssetDialog(const QList<GitHubReleaseAsset>& assets, QWidget* parent) : QDialog(parent), m_assets(assets), ui(new Ui::SelectReleaseDialog) { ui->setupUi(this); ui->changelogTextBrowser->setOpenExternalLinks(true); ui->changelogTextBrowser->setLineWrapMode(QTextBrowser::LineWrapMode::WidgetWidth); ui->changelogTextBrowser->setVerticalScrollBarPolicy(Qt::ScrollBarPolicy::ScrollBarAsNeeded); ui->versionsTree->setColumnCount(2); ui->versionsTree->header()->setSectionResizeMode(0, QHeaderView::Stretch); ui->versionsTree->header()->setSectionResizeMode(1, QHeaderView::ResizeToContents); ui->versionsTree->setHeaderLabels({ tr("Version"), tr("Published Date") }); ui->versionsTree->header()->setStretchLastSection(false); ui->eplainLabel->setText(tr("Select a version to install.")); ui->changelogTextBrowser->setHidden(true); loadAssets(); connect(ui->versionsTree, &QTreeWidget::currentItemChanged, this, &SelectReleaseAssetDialog::selectionChanged); connect(ui->buttonBox, &QDialogButtonBox::accepted, this, &SelectReleaseAssetDialog::accept); connect(ui->buttonBox, &QDialogButtonBox::rejected, this, &SelectReleaseAssetDialog::reject); } SelectReleaseAssetDialog::~SelectReleaseAssetDialog() { delete ui; } void SelectReleaseAssetDialog::loadAssets() { for (auto rls : m_assets) { appendAsset(rls); } } void SelectReleaseAssetDialog::appendAsset(GitHubReleaseAsset const& asset) { auto rls_item = new QTreeWidgetItem(ui->versionsTree); rls_item->setText(0, asset.name); rls_item->setExpanded(true); rls_item->setText(1, asset.updated_at.toString()); rls_item->setData(0, Qt::UserRole, QVariant(asset.id)); ui->versionsTree->addTopLevelItem(rls_item); } GitHubReleaseAsset SelectReleaseAssetDialog::getAsset(QTreeWidgetItem* item) { int id = item->data(0, Qt::UserRole).toInt(); GitHubReleaseAsset selected_asset; for (auto asset : m_assets) { if (asset.id == id) selected_asset = asset; } return selected_asset; } void SelectReleaseAssetDialog::selectionChanged(QTreeWidgetItem* current, QTreeWidgetItem* previous) { GitHubReleaseAsset asset = getAsset(current); m_selectedAsset = asset; }
6,025
C++
.cpp
138
39.23913
127
0.74026
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,953
MainWindow.cpp
PrismLauncher_PrismLauncher/launcher/ui/MainWindow.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * Copyright (C) 2023 TheKodeToad <TheKodeToad@proton.me> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Authors: Andrew Okin * Peterix * Orochimarufan <orochimarufan.x3@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "Application.h" #include "BuildConfig.h" #include "FileSystem.h" #include "MainWindow.h" #include "ui_MainWindow.h" #include <QDir> #include <QFileInfo> #include <QUrl> #include <QVariant> #include <QAction> #include <QActionGroup> #include <QApplication> #include <QButtonGroup> #include <QFileDialog> #include <QHBoxLayout> #include <QHeaderView> #include <QInputDialog> #include <QKeyEvent> #include <QLabel> #include <QMainWindow> #include <QMenu> #include <QMenuBar> #include <QMessageBox> #include <QProgressDialog> #include <QShortcut> #include <QStatusBar> #include <QToolBar> #include <QToolButton> #include <QWidget> #include <QWidgetAction> #include <BaseInstance.h> #include <BuildConfig.h> #include <DesktopServices.h> #include <InstanceList.h> #include <MMCZip.h> #include <icons/IconList.h> #include <java/JavaInstallList.h> #include <java/JavaUtils.h> #include <launch/LaunchTask.h> #include <minecraft/MinecraftInstance.h> #include <minecraft/auth/AccountList.h> #include <net/ApiDownload.h> #include <net/NetJob.h> #include <news/NewsChecker.h> #include <tools/BaseProfiler.h> #include <updater/ExternalUpdater.h> #include "InstanceWindow.h" #include "ui/dialogs/AboutDialog.h" #include "ui/dialogs/CopyInstanceDialog.h" #include "ui/dialogs/CustomMessageBox.h" #include "ui/dialogs/ExportInstanceDialog.h" #include "ui/dialogs/ExportPackDialog.h" #include "ui/dialogs/IconPickerDialog.h" #include "ui/dialogs/ImportResourceDialog.h" #include "ui/dialogs/NewInstanceDialog.h" #include "ui/dialogs/NewsDialog.h" #include "ui/dialogs/ProgressDialog.h" #include "ui/instanceview/InstanceDelegate.h" #include "ui/instanceview/InstanceProxyModel.h" #include "ui/instanceview/InstanceView.h" #include "ui/themes/ITheme.h" #include "ui/themes/ThemeManager.h" #include "ui/widgets/LabeledToolButton.h" #include "minecraft/PackProfile.h" #include "minecraft/VersionFile.h" #include "minecraft/WorldList.h" #include "minecraft/mod/ModFolderModel.h" #include "minecraft/mod/ResourcePackFolderModel.h" #include "minecraft/mod/ShaderPackFolderModel.h" #include "minecraft/mod/TexturePackFolderModel.h" #include "minecraft/mod/tasks/LocalResourceParse.h" #include "modplatform/ModIndex.h" #include "modplatform/flame/FlameAPI.h" #include "modplatform/flame/FlameModIndex.h" #include "KonamiCode.h" #include "InstanceCopyTask.h" #include "Json.h" #include "MMCTime.h" namespace { QString profileInUseFilter(const QString& profile, bool used) { if (used) { return QObject::tr("%1 (in use)").arg(profile); } else { return profile; } } } // namespace MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); setWindowIcon(APPLICATION->getThemedIcon("logo")); setWindowTitle(APPLICATION->applicationDisplayName()); #ifndef QT_NO_ACCESSIBILITY setAccessibleName(BuildConfig.LAUNCHER_DISPLAYNAME); #endif // instance toolbar stuff { // Qt doesn't like vertical moving toolbars, so we have to force them... // See https://github.com/PolyMC/PolyMC/issues/493 connect(ui->instanceToolBar, &QToolBar::orientationChanged, [this](Qt::Orientation) { ui->instanceToolBar->setOrientation(Qt::Vertical); }); // if you try to add a widget to a toolbar in a .ui file // qt designer will delete it when you save the file >:( changeIconButton = new LabeledToolButton(this); changeIconButton->setObjectName(QStringLiteral("changeIconButton")); changeIconButton->setIcon(APPLICATION->getThemedIcon("news")); changeIconButton->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); connect(changeIconButton, &QToolButton::clicked, this, &MainWindow::on_actionChangeInstIcon_triggered); ui->instanceToolBar->insertWidgetBefore(ui->actionLaunchInstance, changeIconButton); renameButton = new LabeledToolButton(this); renameButton->setObjectName(QStringLiteral("renameButton")); renameButton->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); connect(renameButton, &QToolButton::clicked, this, &MainWindow::on_actionRenameInstance_triggered); ui->instanceToolBar->insertWidgetBefore(ui->actionLaunchInstance, renameButton); ui->instanceToolBar->insertSeparator(ui->actionLaunchInstance); // restore the instance toolbar settings auto const setting_name = QString("WideBarVisibility_%1").arg(ui->instanceToolBar->objectName()); if (!APPLICATION->settings()->contains(setting_name)) instanceToolbarSetting = APPLICATION->settings()->registerSetting(setting_name); else instanceToolbarSetting = APPLICATION->settings()->getSetting(setting_name); ui->instanceToolBar->setVisibilityState(instanceToolbarSetting->get().toByteArray()); ui->instanceToolBar->addContextMenuAction(ui->newsToolBar->toggleViewAction()); ui->instanceToolBar->addContextMenuAction(ui->instanceToolBar->toggleViewAction()); ui->instanceToolBar->addContextMenuAction(ui->actionToggleStatusBar); ui->instanceToolBar->addContextMenuAction(ui->actionLockToolbars); } // set the menu for the folders help, accounts, and export tool buttons { auto foldersMenuButton = dynamic_cast<QToolButton*>(ui->mainToolBar->widgetForAction(ui->actionFoldersButton)); ui->actionFoldersButton->setMenu(ui->foldersMenu); foldersMenuButton->setPopupMode(QToolButton::InstantPopup); helpMenuButton = dynamic_cast<QToolButton*>(ui->mainToolBar->widgetForAction(ui->actionHelpButton)); ui->actionHelpButton->setMenu(new QMenu(this)); ui->actionHelpButton->menu()->addActions(ui->helpMenu->actions()); ui->actionHelpButton->menu()->removeAction(ui->actionCheckUpdate); helpMenuButton->setPopupMode(QToolButton::InstantPopup); auto accountMenuButton = dynamic_cast<QToolButton*>(ui->mainToolBar->widgetForAction(ui->actionAccountsButton)); accountMenuButton->setPopupMode(QToolButton::InstantPopup); auto exportInstanceMenu = new QMenu(this); exportInstanceMenu->addAction(ui->actionExportInstanceZip); exportInstanceMenu->addAction(ui->actionExportInstanceMrPack); exportInstanceMenu->addAction(ui->actionExportInstanceFlamePack); ui->actionExportInstance->setMenu(exportInstanceMenu); } // hide, disable and show stuff { ui->actionReportBug->setVisible(!BuildConfig.BUG_TRACKER_URL.isEmpty()); ui->actionMATRIX->setVisible(!BuildConfig.MATRIX_URL.isEmpty()); ui->actionDISCORD->setVisible(!BuildConfig.DISCORD_URL.isEmpty()); ui->actionREDDIT->setVisible(!BuildConfig.SUBREDDIT_URL.isEmpty()); ui->actionCheckUpdate->setVisible(APPLICATION->updaterEnabled()); #ifndef Q_OS_MAC ui->actionAddToPATH->setVisible(false); #endif // disabled until we have an instance selected ui->instanceToolBar->setEnabled(false); setInstanceActionsEnabled(false); // add a close button at the end of the main toolbar when running on gamescope / steam deck // this is only needed on gamescope because it defaults to an X11/XWayland session and // does not implement decorations if (qgetenv("XDG_CURRENT_DESKTOP") == "gamescope") { ui->mainToolBar->addAction(ui->actionCloseWindow); } ui->actionViewJavaFolder->setEnabled(BuildConfig.JAVA_DOWNLOADER_ENABLED); } // add the toolbar toggles to the view menu ui->viewMenu->addAction(ui->instanceToolBar->toggleViewAction()); ui->viewMenu->addAction(ui->newsToolBar->toggleViewAction()); updateThemeMenu(); updateMainToolBar(); // OSX magic. setUnifiedTitleAndToolBarOnMac(true); // Global shortcuts { // you can't set QKeySequence::StandardKey shortcuts in qt designer >:( ui->actionAddInstance->setShortcut(QKeySequence::New); ui->actionSettings->setShortcut(QKeySequence::Preferences); ui->actionUndoTrashInstance->setShortcut(QKeySequence::Undo); ui->actionDeleteInstance->setShortcuts({ QKeySequence(tr("Backspace")), QKeySequence::Delete }); ui->actionCloseWindow->setShortcut(QKeySequence::Close); connect(ui->actionCloseWindow, &QAction::triggered, APPLICATION, &Application::closeCurrentWindow); // FIXME: This is kinda weird. and bad. We need some kind of managed shutdown. auto q = new QShortcut(QKeySequence::Quit, this); connect(q, &QShortcut::activated, APPLICATION, &Application::quit); } // Konami Code { secretEventFilter = new KonamiCode(this); connect(secretEventFilter, &KonamiCode::triggered, this, &MainWindow::konamiTriggered); } // Add the news label to the news toolbar. { m_newsChecker.reset(new NewsChecker(APPLICATION->network(), BuildConfig.NEWS_RSS_URL)); newsLabel = new QToolButton(); newsLabel->setIcon(APPLICATION->getThemedIcon("news")); newsLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); newsLabel->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); newsLabel->setFocusPolicy(Qt::NoFocus); ui->newsToolBar->insertWidget(ui->actionMoreNews, newsLabel); QObject::connect(newsLabel, &QAbstractButton::clicked, this, &MainWindow::newsButtonClicked); QObject::connect(m_newsChecker.get(), &NewsChecker::newsLoaded, this, &MainWindow::updateNewsLabel); updateNewsLabel(); } // Create the instance list widget { view = new InstanceView(ui->centralWidget); view->setSelectionMode(QAbstractItemView::SingleSelection); // FIXME: leaks ListViewDelegate view->setItemDelegate(new ListViewDelegate(this)); view->setFrameShape(QFrame::NoFrame); // do not show ugly blue border on the mac view->setAttribute(Qt::WA_MacShowFocusRect, false); view->installEventFilter(this); view->setContextMenuPolicy(Qt::CustomContextMenu); connect(view, &QWidget::customContextMenuRequested, this, &MainWindow::showInstanceContextMenu); connect(view, &InstanceView::droppedURLs, this, &MainWindow::processURLs, Qt::QueuedConnection); proxymodel = new InstanceProxyModel(this); proxymodel->setSourceModel(APPLICATION->instances().get()); proxymodel->sort(0); connect(proxymodel, &InstanceProxyModel::dataChanged, this, &MainWindow::instanceDataChanged); view->setModel(proxymodel); view->setSourceOfGroupCollapseStatus( [](const QString& groupName) -> bool { return APPLICATION->instances()->isGroupCollapsed(groupName); }); connect(view, &InstanceView::groupStateChanged, APPLICATION->instances().get(), &InstanceList::on_GroupStateChanged); ui->horizontalLayout->addWidget(view); } // The cat background { // set the cat action priority here so you can still see the action in qt designer ui->actionCAT->setPriority(QAction::LowPriority); bool cat_enable = APPLICATION->settings()->get("TheCat").toBool(); ui->actionCAT->setChecked(cat_enable); connect(ui->actionCAT, &QAction::toggled, this, &MainWindow::onCatToggled); connect(APPLICATION, &Application::currentCatChanged, this, &MainWindow::onCatChanged); setCatBackground(cat_enable); } // Togglable status bar { bool statusBarVisible = APPLICATION->settings()->get("StatusBarVisible").toBool(); ui->actionToggleStatusBar->setChecked(statusBarVisible); connect(ui->actionToggleStatusBar, &QAction::toggled, this, &MainWindow::setStatusBarVisibility); setStatusBarVisibility(statusBarVisible); } // Lock toolbars { bool toolbarsLocked = APPLICATION->settings()->get("ToolbarsLocked").toBool(); ui->actionLockToolbars->setChecked(toolbarsLocked); connect(ui->actionLockToolbars, &QAction::toggled, this, &MainWindow::lockToolbars); lockToolbars(toolbarsLocked); } // start instance when double-clicked connect(view, &InstanceView::activated, this, &MainWindow::instanceActivated); // track the selection -- update the instance toolbar connect(view->selectionModel(), &QItemSelectionModel::currentChanged, this, &MainWindow::instanceChanged); // track icon changes and update the toolbar! connect(APPLICATION->icons().get(), &IconList::iconUpdated, this, &MainWindow::iconUpdated); // model reset -> selection is invalid. All the instance pointers are wrong. connect(APPLICATION->instances().get(), &InstanceList::dataIsInvalid, this, &MainWindow::selectionBad); // handle newly added instances connect(APPLICATION->instances().get(), &InstanceList::instanceSelectRequest, this, &MainWindow::instanceSelectRequest); // When the global settings page closes, we want to know about it and update our state connect(APPLICATION, &Application::globalSettingsClosed, this, &MainWindow::globalSettingsClosed); m_statusLeft = new QLabel(tr("No instance selected"), this); m_statusCenter = new QLabel(tr("Total playtime: 0s"), this); statusBar()->addPermanentWidget(m_statusLeft, 1); statusBar()->addPermanentWidget(m_statusCenter, 0); // Add "manage accounts" button, right align QWidget* spacer = new QWidget(); spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); ui->mainToolBar->insertWidget(ui->actionAccountsButton, spacer); // Use undocumented property... https://stackoverflow.com/questions/7121718/create-a-scrollbar-in-a-submenu-qt ui->accountsMenu->setStyleSheet("QMenu { menu-scrollable: 1; }"); repopulateAccountsMenu(); // Update the menu when the active account changes. // Shouldn't have to use lambdas here like this, but if I don't, the compiler throws a fit. // Template hell sucks... connect(APPLICATION->accounts().get(), &AccountList::defaultAccountChanged, [this] { defaultAccountChanged(); }); connect(APPLICATION->accounts().get(), &AccountList::listChanged, [this] { defaultAccountChanged(); }); // Show initial account defaultAccountChanged(); // TODO: refresh accounts here? // auto accounts = APPLICATION->accounts(); // load the news { m_newsChecker->reloadNews(); updateNewsLabel(); } if (APPLICATION->updaterEnabled()) { bool updatesAllowed = APPLICATION->updatesAreAllowed(); updatesAllowedChanged(updatesAllowed); connect(ui->actionCheckUpdate, &QAction::triggered, this, &MainWindow::checkForUpdates); // set up the updater object. auto updater = APPLICATION->updater(); if (updater) { connect(updater.get(), &ExternalUpdater::canCheckForUpdatesChanged, this, &MainWindow::updatesAllowedChanged); } } connect(ui->actionUndoTrashInstance, &QAction::triggered, this, &MainWindow::undoTrashInstance); setSelectedInstanceById(APPLICATION->settings()->get("SelectedInstance").toString()); // removing this looks stupid view->setFocus(); retranslateUi(); } // macOS always has a native menu bar, so these fixes are not applicable // Other systems may or may not have a native menu bar (most do not - it seems like only Ubuntu Unity does) #ifndef Q_OS_MAC void MainWindow::keyReleaseEvent(QKeyEvent* event) { if (event->key() == Qt::Key_Alt && !APPLICATION->settings()->get("MenuBarInsteadOfToolBar").toBool()) ui->menuBar->setVisible(!ui->menuBar->isVisible()); else QMainWindow::keyReleaseEvent(event); } #endif void MainWindow::retranslateUi() { if (m_selectedInstance) { m_statusLeft->setText(m_selectedInstance->getStatusbarDescription()); } else { m_statusLeft->setText(tr("No instance selected")); } ui->retranslateUi(this); MinecraftAccountPtr defaultAccount = APPLICATION->accounts()->defaultAccount(); if (defaultAccount) { auto profileLabel = profileInUseFilter(defaultAccount->profileName(), defaultAccount->isInUse()); ui->actionAccountsButton->setText(profileLabel); } changeIconButton->setToolTip(ui->actionChangeInstIcon->toolTip()); renameButton->setToolTip(ui->actionRenameInstance->toolTip()); // replace the %1 with the launcher display name in some actions if (helpMenuButton->toolTip().contains("%1")) helpMenuButton->setToolTip(helpMenuButton->toolTip().arg(BuildConfig.LAUNCHER_DISPLAYNAME)); for (auto action : ui->helpMenu->actions()) { if (action->text().contains("%1")) action->setText(action->text().arg(BuildConfig.LAUNCHER_DISPLAYNAME)); if (action->toolTip().contains("%1")) action->setToolTip(action->toolTip().arg(BuildConfig.LAUNCHER_DISPLAYNAME)); } } MainWindow::~MainWindow() {} QMenu* MainWindow::createPopupMenu() { QMenu* filteredMenu = QMainWindow::createPopupMenu(); filteredMenu->removeAction(ui->mainToolBar->toggleViewAction()); filteredMenu->addAction(ui->actionToggleStatusBar); filteredMenu->addAction(ui->actionLockToolbars); return filteredMenu; } void MainWindow::setStatusBarVisibility(bool state) { statusBar()->setVisible(state); APPLICATION->settings()->set("StatusBarVisible", state); } void MainWindow::lockToolbars(bool state) { ui->mainToolBar->setMovable(!state); ui->instanceToolBar->setMovable(!state); ui->newsToolBar->setMovable(!state); APPLICATION->settings()->set("ToolbarsLocked", state); } void MainWindow::konamiTriggered() { QString gradient = " stop:0 rgba(125, 0, 0, 255), stop:0.166 rgba(125, 125, 0, 255), stop:0.333 rgba(0, 125, 0, 255), stop:0.5 rgba(0, 125, 125, " "255), stop:0.666 rgba(0, 0, 125, 255), stop:0.833 rgba(125, 0, 125, 255), stop:1 rgba(125, 0, 0, 255));"; QString stylesheet = "background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0," + gradient; if (ui->mainToolBar->styleSheet() == stylesheet) { ui->mainToolBar->setStyleSheet(""); ui->instanceToolBar->setStyleSheet(""); ui->centralWidget->setStyleSheet(""); ui->newsToolBar->setStyleSheet(""); ui->statusBar->setStyleSheet(""); qDebug() << "Super Secret Mode DEACTIVATED!"; } else { ui->mainToolBar->setStyleSheet(stylesheet); ui->instanceToolBar->setStyleSheet("background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1," + gradient); ui->centralWidget->setStyleSheet("background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:1," + gradient); ui->newsToolBar->setStyleSheet(stylesheet); ui->statusBar->setStyleSheet(stylesheet); qDebug() << "Super Secret Mode ACTIVATED!"; } } void MainWindow::showInstanceContextMenu(const QPoint& pos) { QList<QAction*> actions; QAction* actionSep = new QAction("", this); actionSep->setSeparator(true); bool onInstance = view->indexAt(pos).isValid(); if (onInstance) { // reuse the file menu actions actions = ui->fileMenu->actions(); // remove the add instance action, launcher settings action and close action actions.removeFirst(); actions.removeLast(); actions.removeLast(); actions.prepend(ui->actionChangeInstIcon); actions.prepend(ui->actionRenameInstance); // add header actions.prepend(actionSep); QAction* actionVoid = new QAction(m_selectedInstance->name(), this); actionVoid->setEnabled(false); actions.prepend(actionVoid); } else { auto group = view->groupNameAt(pos); QAction* actionVoid = new QAction(group.isNull() ? BuildConfig.LAUNCHER_DISPLAYNAME : group, this); actionVoid->setEnabled(false); QAction* actionCreateInstance = new QAction(tr("&Create instance"), this); actionCreateInstance->setToolTip(ui->actionAddInstance->toolTip()); if (!group.isNull()) { QVariantMap instance_action_data; instance_action_data["group"] = group; actionCreateInstance->setData(instance_action_data); } connect(actionCreateInstance, SIGNAL(triggered(bool)), SLOT(on_actionAddInstance_triggered())); actions.prepend(actionSep); actions.prepend(actionVoid); actions.append(actionCreateInstance); if (!group.isNull()) { QAction* actionDeleteGroup = new QAction(tr("&Delete group"), this); connect(actionDeleteGroup, &QAction::triggered, this, [this, group] { deleteGroup(group); }); actions.append(actionDeleteGroup); QAction* actionRenameGroup = new QAction(tr("&Rename group"), this); connect(actionRenameGroup, &QAction::triggered, this, [this, group] { renameGroup(group); }); actions.append(actionRenameGroup); } } QMenu myMenu; myMenu.addActions(actions); /* if (onInstance) myMenu.setEnabled(m_selectedInstance->canLaunch()); */ myMenu.exec(view->mapToGlobal(pos)); } void MainWindow::updateMainToolBar() { ui->menuBar->setVisible(APPLICATION->settings()->get("MenuBarInsteadOfToolBar").toBool()); ui->mainToolBar->setVisible(ui->menuBar->isNativeMenuBar() || !APPLICATION->settings()->get("MenuBarInsteadOfToolBar").toBool()); } void MainWindow::updateLaunchButton() { QMenu* launchMenu = ui->actionLaunchInstance->menu(); if (launchMenu) launchMenu->clear(); else launchMenu = new QMenu(this); if (m_selectedInstance) m_selectedInstance->populateLaunchMenu(launchMenu); ui->actionLaunchInstance->setMenu(launchMenu); } void MainWindow::updateThemeMenu() { QMenu* themeMenu = ui->actionChangeTheme->menu(); if (themeMenu) { themeMenu->clear(); } else { themeMenu = new QMenu(this); } auto themes = APPLICATION->themeManager()->getValidApplicationThemes(); QActionGroup* themesGroup = new QActionGroup(this); for (auto* theme : themes) { QAction* themeAction = themeMenu->addAction(theme->name()); themeAction->setCheckable(true); if (APPLICATION->settings()->get("ApplicationTheme").toString() == theme->id()) { themeAction->setChecked(true); } themeAction->setActionGroup(themesGroup); connect(themeAction, &QAction::triggered, [theme]() { APPLICATION->themeManager()->setApplicationTheme(theme->id()); APPLICATION->settings()->set("ApplicationTheme", theme->id()); }); } ui->actionChangeTheme->setMenu(themeMenu); } void MainWindow::repopulateAccountsMenu() { ui->accountsMenu->clear(); // NOTE: this is done so the accounts button text is not set to the accounts menu title QMenu* accountsButtonMenu = ui->actionAccountsButton->menu(); if (accountsButtonMenu) { accountsButtonMenu->clear(); } else { accountsButtonMenu = new QMenu(this); ui->actionAccountsButton->setMenu(accountsButtonMenu); } auto accounts = APPLICATION->accounts(); MinecraftAccountPtr defaultAccount = accounts->defaultAccount(); QString active_profileId = ""; if (defaultAccount) { // this can be called before accountMenuButton exists if (ui->actionAccountsButton) { auto profileLabel = profileInUseFilter(defaultAccount->profileName(), defaultAccount->isInUse()); ui->actionAccountsButton->setText(profileLabel); } } QActionGroup* accountsGroup = new QActionGroup(this); if (accounts->count() <= 0) { ui->actionNoAccountsAdded->setEnabled(false); ui->accountsMenu->addAction(ui->actionNoAccountsAdded); } else { // TODO: Nicer way to iterate? for (int i = 0; i < accounts->count(); i++) { MinecraftAccountPtr account = accounts->at(i); auto profileLabel = profileInUseFilter(account->profileName(), account->isInUse()); QAction* action = new QAction(profileLabel, this); action->setData(i); action->setCheckable(true); action->setActionGroup(accountsGroup); if (defaultAccount == account) { action->setChecked(true); } auto face = account->getFace(); if (!face.isNull()) { action->setIcon(face); } else { action->setIcon(APPLICATION->getThemedIcon("noaccount")); } const int highestNumberKey = 9; if (i < highestNumberKey) { action->setShortcut(QKeySequence(tr("Ctrl+%1").arg(i + 1))); } ui->accountsMenu->addAction(action); connect(action, SIGNAL(triggered(bool)), SLOT(changeActiveAccount())); } } ui->accountsMenu->addSeparator(); ui->actionNoDefaultAccount->setData(-1); ui->actionNoDefaultAccount->setChecked(!defaultAccount); ui->actionNoDefaultAccount->setActionGroup(accountsGroup); ui->accountsMenu->addAction(ui->actionNoDefaultAccount); connect(ui->actionNoDefaultAccount, SIGNAL(triggered(bool)), SLOT(changeActiveAccount())); ui->accountsMenu->addSeparator(); ui->accountsMenu->addAction(ui->actionManageAccounts); accountsButtonMenu->addActions(ui->accountsMenu->actions()); } void MainWindow::updatesAllowedChanged(bool allowed) { if (!APPLICATION->updaterEnabled()) { return; } ui->actionCheckUpdate->setEnabled(allowed); } /* * Assumes the sender is a QAction */ void MainWindow::changeActiveAccount() { QAction* sAction = (QAction*)sender(); // Profile's associated Mojang username if (sAction->data().type() != QVariant::Type::Int) return; QVariant action_data = sAction->data(); bool valid = false; int index = action_data.toInt(&valid); if (!valid) { index = -1; } auto accounts = APPLICATION->accounts(); accounts->setDefaultAccount(index == -1 ? nullptr : accounts->at(index)); defaultAccountChanged(); } void MainWindow::defaultAccountChanged() { repopulateAccountsMenu(); MinecraftAccountPtr account = APPLICATION->accounts()->defaultAccount(); // FIXME: this needs adjustment for MSA if (account && account->profileName() != "") { auto profileLabel = profileInUseFilter(account->profileName(), account->isInUse()); ui->actionAccountsButton->setText(profileLabel); auto face = account->getFace(); if (face.isNull()) { ui->actionAccountsButton->setIcon(APPLICATION->getThemedIcon("noaccount")); } else { ui->actionAccountsButton->setIcon(face); } return; } // Set the icon to the "no account" icon. ui->actionAccountsButton->setIcon(APPLICATION->getThemedIcon("noaccount")); ui->actionAccountsButton->setText(tr("Accounts")); } bool MainWindow::eventFilter(QObject* obj, QEvent* ev) { if (obj == view) { if (ev->type() == QEvent::KeyPress) { secretEventFilter->input(ev); QKeyEvent* keyEvent = static_cast<QKeyEvent*>(ev); switch (keyEvent->key()) { /* case Qt::Key_Enter: case Qt::Key_Return: activateInstance(m_selectedInstance); return true; */ case Qt::Key_Delete: on_actionDeleteInstance_triggered(); return true; case Qt::Key_F5: refreshInstances(); return true; case Qt::Key_F2: on_actionRenameInstance_triggered(); return true; default: break; } } } return QMainWindow::eventFilter(obj, ev); } void MainWindow::updateNewsLabel() { if (m_newsChecker->isLoadingNews()) { newsLabel->setText(tr("Loading news...")); newsLabel->setEnabled(false); ui->actionMoreNews->setVisible(false); } else { QList<NewsEntryPtr> entries = m_newsChecker->getNewsEntries(); if (entries.length() > 0) { newsLabel->setText(entries[0]->title); newsLabel->setEnabled(true); ui->actionMoreNews->setVisible(true); } else { newsLabel->setText(tr("No news available.")); newsLabel->setEnabled(false); ui->actionMoreNews->setVisible(false); } } } QList<int> stringToIntList(const QString& string) { #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) QStringList split = string.split(',', Qt::SkipEmptyParts); #else QStringList split = string.split(',', QString::SkipEmptyParts); #endif QList<int> out; for (int i = 0; i < split.size(); ++i) { out.append(split.at(i).toInt()); } return out; } QString intListToString(const QList<int>& list) { QStringList slist; for (int i = 0; i < list.size(); ++i) { slist.append(QString::number(list.at(i))); } return slist.join(','); } void MainWindow::onCatToggled(bool state) { setCatBackground(state); APPLICATION->settings()->set("TheCat", state); } void MainWindow::setCatBackground(bool enabled) { view->setPaintCat(enabled); view->viewport()->repaint(); } void MainWindow::runModalTask(Task* task) { connect(task, &Task::failed, [this](QString reason) { CustomMessageBox::selectable(this, tr("Error"), reason, QMessageBox::Critical)->show(); }); connect(task, &Task::succeeded, [this, task]() { QStringList warnings = task->warnings(); if (warnings.count()) { CustomMessageBox::selectable(this, tr("Warnings"), warnings.join('\n'), QMessageBox::Warning)->show(); } }); connect(task, &Task::aborted, [this] { CustomMessageBox::selectable(this, tr("Task aborted"), tr("The task has been aborted by the user."), QMessageBox::Information) ->show(); }); ProgressDialog loadDialog(this); loadDialog.setSkipButton(true, tr("Abort")); loadDialog.execWithTask(task); } void MainWindow::instanceFromInstanceTask(InstanceTask* rawTask) { unique_qobject_ptr<Task> task(APPLICATION->instances()->wrapInstanceTask(rawTask)); runModalTask(task.get()); } void MainWindow::on_actionCopyInstance_triggered() { if (!m_selectedInstance) return; CopyInstanceDialog copyInstDlg(m_selectedInstance, this); if (!copyInstDlg.exec()) return; auto copyTask = new InstanceCopyTask(m_selectedInstance, copyInstDlg.getChosenOptions()); copyTask->setName(copyInstDlg.instName()); copyTask->setGroup(copyInstDlg.instGroup()); copyTask->setIcon(copyInstDlg.iconKey()); unique_qobject_ptr<Task> task(APPLICATION->instances()->wrapInstanceTask(copyTask)); runModalTask(task.get()); } void MainWindow::addInstance(const QString& url, const QMap<QString, QString>& extra_info) { QString groupName; do { QObject* obj = sender(); if (!obj) break; QAction* action = qobject_cast<QAction*>(obj); if (!action) break; auto map = action->data().toMap(); if (!map.contains("group")) break; groupName = map["group"].toString(); } while (0); if (groupName.isEmpty()) { groupName = APPLICATION->settings()->get("LastUsedGroupForNewInstance").toString(); } NewInstanceDialog newInstDlg(groupName, url, extra_info, this); if (!newInstDlg.exec()) return; APPLICATION->settings()->set("LastUsedGroupForNewInstance", newInstDlg.instGroup()); InstanceTask* creationTask = newInstDlg.extractTask(); if (creationTask) { instanceFromInstanceTask(creationTask); } } void MainWindow::on_actionAddInstance_triggered() { addInstance(); } void MainWindow::processURLs(QList<QUrl> urls) { // NOTE: This loop only processes one dropped file! for (auto& url : urls) { qDebug() << "Processing" << url; // The isLocalFile() check below doesn't work as intended without an explicit scheme. if (url.scheme().isEmpty()) url.setScheme("file"); ModPlatform::IndexedVersion version; QMap<QString, QString> extra_info; QUrl local_url; if (!url.isLocalFile()) { // download the remote resource and identify QUrl dl_url; if (url.scheme() == "curseforge") { // need to find the download link for the modpack / resource // format of url curseforge://install?addonId=IDHERE&fileId=IDHERE QUrlQuery query(url); if (query.allQueryItemValues("addonId").isEmpty() || query.allQueryItemValues("fileId").isEmpty()) { qDebug() << "Invalid curseforge link:" << url; continue; } auto addonId = query.allQueryItemValues("addonId")[0]; auto fileId = query.allQueryItemValues("fileId")[0]; extra_info.insert("pack_id", addonId); extra_info.insert("pack_version_id", fileId); auto array = std::make_shared<QByteArray>(); auto api = FlameAPI(); auto job = api.getFile(addonId, fileId, array); connect(job.get(), &Task::failed, this, [this](QString reason) { CustomMessageBox::selectable(this, tr("Error"), reason, QMessageBox::Critical)->show(); }); connect(job.get(), &Task::succeeded, this, [this, array, addonId, fileId, &dl_url, &version] { qDebug() << "Returned CFURL Json:\n" << array->toStdString().c_str(); auto doc = Json::requireDocument(*array); auto data = Json::ensureObject(Json::ensureObject(doc.object()), "data"); // No way to find out if it's a mod or a modpack before here // And also we need to check if it ends with .zip, instead of any better way version = FlameMod::loadIndexedPackVersion(data); auto fileName = version.fileName; // Have to use ensureString then use QUrl to get proper url encoding dl_url = QUrl(version.downloadUrl); if (!dl_url.isValid()) { CustomMessageBox::selectable( this, tr("Error"), tr("The modpack, mod, or resource %1 is blocked for third-parties! Please download it manually.").arg(fileName), QMessageBox::Critical) ->show(); return; } QFileInfo dl_file(dl_url.fileName()); }); { // drop stack ProgressDialog dlUrlDialod(this); dlUrlDialod.setSkipButton(true, tr("Abort")); dlUrlDialod.execWithTask(job.get()); } } else if (url.scheme() == BuildConfig.LAUNCHER_APP_BINARY_NAME) { QVariantMap receivedData; const QUrlQuery query(url.query()); const auto items = query.queryItems(); for (auto it = items.begin(), end = items.end(); it != end; ++it) receivedData.insert(it->first, it->second); emit APPLICATION->oauthReplyRecieved(receivedData); continue; } else { dl_url = url; } if (!dl_url.isValid()) { continue; // no valid url to download this resource } const QString path = dl_url.host() + '/' + dl_url.path(); auto entry = APPLICATION->metacache()->resolveEntry("general", path); entry->setStale(true); auto dl_job = unique_qobject_ptr<NetJob>(new NetJob(tr("Modpack download"), APPLICATION->network())); dl_job->addNetAction(Net::ApiDownload::makeCached(dl_url, entry)); auto archivePath = entry->getFullPath(); bool dl_success = false; connect(dl_job.get(), &Task::failed, this, [this](QString reason) { CustomMessageBox::selectable(this, tr("Error"), reason, QMessageBox::Critical)->show(); }); connect(dl_job.get(), &Task::succeeded, this, [&dl_success] { dl_success = true; }); { // drop stack ProgressDialog dlUrlDialod(this); dlUrlDialod.setSkipButton(true, tr("Abort")); dlUrlDialod.execWithTask(dl_job.get()); } if (!dl_success) { continue; // no local file to identify } local_url = QUrl::fromLocalFile(archivePath); } else { local_url = url; } auto localFileName = QDir::toNativeSeparators(local_url.toLocalFile()); QFileInfo localFileInfo(localFileName); auto type = ResourceUtils::identify(localFileInfo); if (ResourceUtils::ValidResourceTypes.count(type) == 0) { // probably instance/modpack addInstance(localFileName, extra_info); continue; } ImportResourceDialog dlg(localFileName, type, this); if (dlg.exec() != QDialog::Accepted) continue; qDebug() << "Adding resource" << localFileName << "to" << dlg.selectedInstanceKey; auto inst = APPLICATION->instances()->getInstanceById(dlg.selectedInstanceKey); auto minecraftInst = std::dynamic_pointer_cast<MinecraftInstance>(inst); switch (type) { case PackedResourceType::ResourcePack: minecraftInst->resourcePackList()->installResource(localFileName); break; case PackedResourceType::TexturePack: minecraftInst->texturePackList()->installResource(localFileName); break; case PackedResourceType::DataPack: qWarning() << "Importing of Data Packs not supported at this time. Ignoring" << localFileName; break; case PackedResourceType::Mod: minecraftInst->loaderModList()->installResourceWithFlameMetadata(localFileName, version); break; case PackedResourceType::ShaderPack: minecraftInst->shaderPackList()->installResource(localFileName); break; case PackedResourceType::WorldSave: minecraftInst->worldList()->installWorld(localFileInfo); break; case PackedResourceType::UNKNOWN: default: qDebug() << "Can't Identify" << localFileName << "Ignoring it."; break; } } } void MainWindow::on_actionREDDIT_triggered() { DesktopServices::openUrl(QUrl(BuildConfig.SUBREDDIT_URL)); } void MainWindow::on_actionDISCORD_triggered() { DesktopServices::openUrl(QUrl(BuildConfig.DISCORD_URL)); } void MainWindow::on_actionMATRIX_triggered() { DesktopServices::openUrl(QUrl(BuildConfig.MATRIX_URL)); } void MainWindow::on_actionChangeInstIcon_triggered() { if (!m_selectedInstance) return; IconPickerDialog dlg(this); dlg.execWithSelection(m_selectedInstance->iconKey()); if (dlg.result() == QDialog::Accepted) { m_selectedInstance->setIconKey(dlg.selectedIconKey); auto icon = APPLICATION->icons()->getIcon(dlg.selectedIconKey); ui->actionChangeInstIcon->setIcon(icon); changeIconButton->setIcon(icon); } } void MainWindow::iconUpdated(QString icon) { if (icon == m_currentInstIcon) { auto new_icon = APPLICATION->icons()->getIcon(m_currentInstIcon); ui->actionChangeInstIcon->setIcon(new_icon); changeIconButton->setIcon(new_icon); } } void MainWindow::updateInstanceToolIcon(QString new_icon) { m_currentInstIcon = new_icon; auto icon = APPLICATION->icons()->getIcon(m_currentInstIcon); ui->actionChangeInstIcon->setIcon(icon); changeIconButton->setIcon(icon); } void MainWindow::setSelectedInstanceById(const QString& id) { if (id.isNull()) return; const QModelIndex index = APPLICATION->instances()->getInstanceIndexById(id); if (index.isValid()) { QModelIndex selectionIndex = proxymodel->mapFromSource(index); view->selectionModel()->setCurrentIndex(selectionIndex, QItemSelectionModel::ClearAndSelect); updateStatusCenter(); } } void MainWindow::on_actionChangeInstGroup_triggered() { if (!m_selectedInstance) return; InstanceId instId = m_selectedInstance->id(); QString src(APPLICATION->instances()->getInstanceGroup(instId)); QStringList groups = APPLICATION->instances()->getGroups(); groups.prepend(""); int index = groups.indexOf(src); bool ok = false; QString dst = QInputDialog::getItem(this, tr("Group name"), tr("Enter a new group name."), groups, index, true, &ok); dst = dst.simplified(); if (ok) { APPLICATION->instances()->setInstanceGroup(instId, dst); } } void MainWindow::deleteGroup(QString group) { Q_ASSERT(!group.isEmpty()); const int reply = QMessageBox::question(this, tr("Delete group"), tr("Are you sure you want to delete the group '%1'?").arg(group), QMessageBox::Yes | QMessageBox::No); if (reply == QMessageBox::Yes) APPLICATION->instances()->deleteGroup(group); } void MainWindow::renameGroup(QString group) { Q_ASSERT(!group.isEmpty()); QString name = QInputDialog::getText(this, tr("Rename group"), tr("Enter a new group name."), QLineEdit::Normal, group); name = name.simplified(); if (name.isNull() || name == group) return; const bool empty = name.isEmpty(); const bool duplicate = APPLICATION->instances()->getGroups().contains(name, Qt::CaseInsensitive) && group.toLower() != name.toLower(); if (empty || duplicate) { QMessageBox::warning(this, tr("Cannot rename group"), empty ? tr("Cannot set empty name.") : tr("Group already exists. :/")); return; } APPLICATION->instances()->renameGroup(group, name); } void MainWindow::undoTrashInstance() { APPLICATION->instances()->undoTrashInstance(); ui->actionUndoTrashInstance->setEnabled(APPLICATION->instances()->trashedSomething()); } void MainWindow::on_actionViewLauncherRootFolder_triggered() { DesktopServices::openPath("."); } void MainWindow::on_actionViewInstanceFolder_triggered() { QString str = APPLICATION->settings()->get("InstanceDir").toString(); DesktopServices::openPath(str); } void MainWindow::on_actionViewCentralModsFolder_triggered() { DesktopServices::openPath(APPLICATION->settings()->get("CentralModsDir").toString(), true); } void MainWindow::on_actionViewSkinsFolder_triggered() { DesktopServices::openPath(APPLICATION->settings()->get("SkinsDir").toString(), true); } void MainWindow::on_actionViewIconThemeFolder_triggered() { DesktopServices::openPath(APPLICATION->themeManager()->getIconThemesFolder().path(), true); } void MainWindow::on_actionViewWidgetThemeFolder_triggered() { DesktopServices::openPath(APPLICATION->themeManager()->getApplicationThemesFolder().path(), true); } void MainWindow::on_actionViewCatPackFolder_triggered() { DesktopServices::openPath(APPLICATION->themeManager()->getCatPacksFolder().path(), true); } void MainWindow::on_actionViewIconsFolder_triggered() { DesktopServices::openPath(APPLICATION->icons()->getDirectory(), true); } void MainWindow::on_actionViewLogsFolder_triggered() { DesktopServices::openPath("logs", true); } void MainWindow::on_actionViewJavaFolder_triggered() { DesktopServices::openPath(APPLICATION->javaPath(), true); } void MainWindow::refreshInstances() { APPLICATION->instances()->loadList(); } void MainWindow::checkForUpdates() { if (APPLICATION->updaterEnabled()) { APPLICATION->triggerUpdateCheck(); } else { qWarning() << "Updater not set up. Cannot check for updates."; } } void MainWindow::on_actionSettings_triggered() { APPLICATION->ShowGlobalSettings(this, "global-settings"); } void MainWindow::globalSettingsClosed() { // FIXME: quick HACK to make this work. improve, optimize. APPLICATION->instances()->loadList(); proxymodel->invalidate(); proxymodel->sort(0); updateMainToolBar(); updateLaunchButton(); updateThemeMenu(); updateStatusCenter(); // This needs to be done to prevent UI elements disappearing in the event the config is changed // but Prism Launcher exits abnormally, causing the window state to never be saved: APPLICATION->settings()->set("MainWindowState", saveState().toBase64()); update(); } void MainWindow::on_actionEditInstance_triggered() { if (!m_selectedInstance) return; if (m_selectedInstance->canEdit()) { APPLICATION->showInstanceWindow(m_selectedInstance); } else { CustomMessageBox::selectable(this, tr("Instance not editable"), tr("This instance is not editable. It may be broken, invalid, or too old. Check logs for details."), QMessageBox::Critical) ->show(); } } void MainWindow::on_actionManageAccounts_triggered() { APPLICATION->ShowGlobalSettings(this, "accounts"); } void MainWindow::on_actionReportBug_triggered() { DesktopServices::openUrl(QUrl(BuildConfig.BUG_TRACKER_URL)); } void MainWindow::on_actionClearMetadata_triggered() { APPLICATION->metacache()->evictAll(); APPLICATION->metacache()->SaveNow(); } #ifdef Q_OS_MAC void MainWindow::on_actionAddToPATH_triggered() { auto binaryPath = APPLICATION->applicationFilePath(); auto targetPath = QString("/usr/local/bin/%1").arg(BuildConfig.LAUNCHER_APP_BINARY_NAME); qDebug() << "Symlinking" << binaryPath << "to" << targetPath; QStringList args; args << "-e"; args << QString("do shell script \"mkdir -p /usr/local/bin && ln -sf '%1' '%2'\" with administrator privileges") .arg(binaryPath, targetPath); auto outcome = QProcess::execute("/usr/bin/osascript", args); if (!outcome) { QMessageBox::information(this, tr("Successfully added %1 to PATH").arg(BuildConfig.LAUNCHER_DISPLAYNAME), tr("%1 was successfully added to your PATH. You can now start it by running `%2`.") .arg(BuildConfig.LAUNCHER_DISPLAYNAME, BuildConfig.LAUNCHER_APP_BINARY_NAME)); } else { QMessageBox::critical(this, tr("Failed to add %1 to PATH").arg(BuildConfig.LAUNCHER_DISPLAYNAME), tr("An error occurred while trying to add %1 to PATH").arg(BuildConfig.LAUNCHER_DISPLAYNAME)); } } #endif void MainWindow::on_actionOpenWiki_triggered() { DesktopServices::openUrl(QUrl(BuildConfig.HELP_URL.arg(""))); } void MainWindow::on_actionMoreNews_triggered() { auto entries = m_newsChecker->getNewsEntries(); NewsDialog news_dialog(entries, this); news_dialog.exec(); } void MainWindow::newsButtonClicked() { auto entries = m_newsChecker->getNewsEntries(); NewsDialog news_dialog(entries, this); news_dialog.toggleArticleList(); news_dialog.exec(); } void MainWindow::onCatChanged(int) { setCatBackground(APPLICATION->settings()->get("TheCat").toBool()); } void MainWindow::on_actionAbout_triggered() { AboutDialog dialog(this); dialog.exec(); } void MainWindow::on_actionDeleteInstance_triggered() { if (!m_selectedInstance) { return; } auto id = m_selectedInstance->id(); auto response = CustomMessageBox::selectable(this, tr("Confirm Deletion"), tr("You are about to delete \"%1\".\n" "This may be permanent and will completely delete the instance.\n\n" "Are you sure?") .arg(m_selectedInstance->name()), QMessageBox::Warning, QMessageBox::Yes | QMessageBox::No, QMessageBox::No) ->exec(); if (response != QMessageBox::Yes) return; auto linkedInstances = APPLICATION->instances()->getLinkedInstancesById(id); if (!linkedInstances.empty()) { response = CustomMessageBox::selectable(this, tr("There are linked instances"), tr("The following instance(s) might reference files in this instance:\n\n" "%1\n\n" "Deleting it could break the other instance(s), \n\n" "Do you wish to proceed?", nullptr, linkedInstances.count()) .arg(linkedInstances.join("\n")), QMessageBox::Warning, QMessageBox::Yes | QMessageBox::No, QMessageBox::No) ->exec(); if (response != QMessageBox::Yes) return; } if (APPLICATION->instances()->trashInstance(id)) { ui->actionUndoTrashInstance->setEnabled(APPLICATION->instances()->trashedSomething()); } else { APPLICATION->instances()->deleteInstance(id); } APPLICATION->settings()->set("SelectedInstance", QString()); selectionBad(); } void MainWindow::on_actionExportInstanceZip_triggered() { if (m_selectedInstance) { ExportInstanceDialog dlg(m_selectedInstance, this); dlg.exec(); } } void MainWindow::on_actionExportInstanceMrPack_triggered() { if (m_selectedInstance) { ExportPackDialog dlg(m_selectedInstance, this); dlg.exec(); } } void MainWindow::on_actionExportInstanceFlamePack_triggered() { if (m_selectedInstance) { auto instance = dynamic_cast<MinecraftInstance*>(m_selectedInstance.get()); if (instance) { if (auto cmp = instance->getPackProfile()->getComponent("net.minecraft"); cmp && cmp->getVersionFile() && cmp->getVersionFile()->type == "snapshot") { QMessageBox msgBox(this); msgBox.setText("Snapshots are currently not supported by CurseForge modpacks."); msgBox.exec(); return; } ExportPackDialog dlg(m_selectedInstance, this, ModPlatform::ResourceProvider::FLAME); dlg.exec(); } } } void MainWindow::on_actionRenameInstance_triggered() { if (m_selectedInstance) { view->edit(view->currentIndex()); } } void MainWindow::on_actionViewSelectedInstFolder_triggered() { if (m_selectedInstance) { QString str = m_selectedInstance->instanceRoot(); DesktopServices::openPath(QFileInfo(str)); } } void MainWindow::closeEvent(QCloseEvent* event) { // Save the window state and geometry. APPLICATION->settings()->set("MainWindowState", saveState().toBase64()); APPLICATION->settings()->set("MainWindowGeometry", saveGeometry().toBase64()); instanceToolbarSetting->set(ui->instanceToolBar->getVisibilityState()); event->accept(); emit isClosing(); } void MainWindow::changeEvent(QEvent* event) { if (event->type() == QEvent::LanguageChange) { retranslateUi(); } QMainWindow::changeEvent(event); } void MainWindow::instanceActivated(QModelIndex index) { if (!index.isValid()) return; QString id = index.data(InstanceList::InstanceIDRole).toString(); InstancePtr inst = APPLICATION->instances()->getInstanceById(id); if (!inst) return; activateInstance(inst); } void MainWindow::on_actionLaunchInstance_triggered() { if (m_selectedInstance && !m_selectedInstance->isRunning()) { APPLICATION->launch(m_selectedInstance); } } void MainWindow::activateInstance(InstancePtr instance) { APPLICATION->launch(instance); } void MainWindow::on_actionKillInstance_triggered() { if (m_selectedInstance && m_selectedInstance->isRunning()) { APPLICATION->kill(m_selectedInstance); } } void MainWindow::on_actionCreateInstanceShortcut_triggered() { if (!m_selectedInstance) return; auto desktopPath = FS::getDesktopDir(); if (desktopPath.isEmpty()) { // TODO come up with an alternative solution (open "save file" dialog) QMessageBox::critical(this, tr("Create instance shortcut"), tr("Couldn't find desktop?!")); return; } QString desktopFilePath; QString appPath = QApplication::applicationFilePath(); QString iconPath; QStringList args; #if defined(Q_OS_MACOS) appPath = QApplication::applicationFilePath(); if (appPath.startsWith("/private/var/")) { QMessageBox::critical(this, tr("Create instance shortcut"), tr("The launcher is in the folder it was extracted from, therefore it cannot create shortcuts.")); return; } auto pIcon = APPLICATION->icons()->icon(m_selectedInstance->iconKey()); if (pIcon == nullptr) { pIcon = APPLICATION->icons()->icon("grass"); } iconPath = FS::PathCombine(m_selectedInstance->instanceRoot(), "Icon.icns"); QFile iconFile(iconPath); if (!iconFile.open(QFile::WriteOnly)) { QMessageBox::critical(this, tr("Create instance Application"), tr("Failed to create icon for Application.")); return; } QIcon icon = pIcon->icon(); bool success = icon.pixmap(1024, 1024).save(iconPath, "ICNS"); iconFile.close(); if (!success) { iconFile.remove(); QMessageBox::critical(this, tr("Create instance Application"), tr("Failed to create icon for Application.")); return; } #elif defined(Q_OS_LINUX) || defined(Q_OS_FREEBSD) || defined(Q_OS_OPENBSD) if (appPath.startsWith("/tmp/.mount_")) { // AppImage! appPath = QProcessEnvironment::systemEnvironment().value(QStringLiteral("APPIMAGE")); if (appPath.isEmpty()) { QMessageBox::critical(this, tr("Create instance shortcut"), tr("Launcher is running as misconfigured AppImage? ($APPIMAGE environment variable is missing)")); } else if (appPath.endsWith("/")) { appPath.chop(1); } } auto icon = APPLICATION->icons()->icon(m_selectedInstance->iconKey()); if (icon == nullptr) { icon = APPLICATION->icons()->icon("grass"); } iconPath = FS::PathCombine(m_selectedInstance->instanceRoot(), "icon.png"); QFile iconFile(iconPath); if (!iconFile.open(QFile::WriteOnly)) { QMessageBox::critical(this, tr("Create instance shortcut"), tr("Failed to create icon for shortcut.")); return; } bool success = icon->icon().pixmap(64, 64).save(&iconFile, "PNG"); iconFile.close(); if (!success) { iconFile.remove(); QMessageBox::critical(this, tr("Create instance shortcut"), tr("Failed to create icon for shortcut.")); return; } if (DesktopServices::isFlatpak()) { desktopFilePath = FS::PathCombine(desktopPath, FS::RemoveInvalidFilenameChars(m_selectedInstance->name()) + ".desktop"); QFileDialog fileDialog; // workaround to make sure the portal file dialog opens in the desktop directory fileDialog.setDirectoryUrl(desktopPath); desktopFilePath = fileDialog.getSaveFileName(this, tr("Create Shortcut"), desktopFilePath, tr("Desktop Entries") + " (*.desktop)"); if (desktopFilePath.isEmpty()) return; // file dialog canceled by user appPath = "flatpak"; QString flatpakAppId = BuildConfig.LAUNCHER_DESKTOPFILENAME; flatpakAppId.remove(".desktop"); args.append({ "run", flatpakAppId }); } #elif defined(Q_OS_WIN) auto icon = APPLICATION->icons()->icon(m_selectedInstance->iconKey()); if (icon == nullptr) { icon = APPLICATION->icons()->icon("grass"); } iconPath = FS::PathCombine(m_selectedInstance->instanceRoot(), "icon.ico"); // part of fix for weird bug involving the window icon being replaced // dunno why it happens, but this 2-line fix seems to be enough, so w/e auto appIcon = APPLICATION->getThemedIcon("logo"); QFile iconFile(iconPath); if (!iconFile.open(QFile::WriteOnly)) { QMessageBox::critical(this, tr("Create instance shortcut"), tr("Failed to create icon for shortcut.")); return; } bool success = icon->icon().pixmap(64, 64).save(&iconFile, "ICO"); iconFile.close(); // restore original window icon QGuiApplication::setWindowIcon(appIcon); if (!success) { iconFile.remove(); QMessageBox::critical(this, tr("Create instance shortcut"), tr("Failed to create icon for shortcut.")); return; } #else QMessageBox::critical(this, tr("Create instance shortcut"), tr("Not supported on your platform!")); return; #endif args.append({ "--launch", m_selectedInstance->id() }); if (FS::createShortcut(desktopFilePath, appPath, args, m_selectedInstance->name(), iconPath)) { #if not defined(Q_OS_MACOS) QMessageBox::information(this, tr("Create instance shortcut"), tr("Created a shortcut to this instance on your desktop!")); #else QMessageBox::information(this, tr("Create instance shortcut"), tr("Created a shortcut to this instance!")); #endif } else { #if not defined(Q_OS_MACOS) iconFile.remove(); #endif QMessageBox::critical(this, tr("Create instance shortcut"), tr("Failed to create instance shortcut!")); } } void MainWindow::taskEnd() { QObject* sender = QObject::sender(); if (sender == m_versionLoadTask) m_versionLoadTask = NULL; sender->deleteLater(); } void MainWindow::startTask(Task* task) { connect(task, SIGNAL(succeeded()), SLOT(taskEnd())); connect(task, SIGNAL(failed(QString)), SLOT(taskEnd())); task->start(); } void MainWindow::instanceChanged(const QModelIndex& current, [[maybe_unused]] const QModelIndex& previous) { if (!current.isValid()) { APPLICATION->settings()->set("SelectedInstance", QString()); selectionBad(); return; } if (m_selectedInstance) { disconnect(m_selectedInstance.get(), &BaseInstance::runningStatusChanged, this, &MainWindow::refreshCurrentInstance); disconnect(m_selectedInstance.get(), &BaseInstance::profilerChanged, this, &MainWindow::refreshCurrentInstance); } QString id = current.data(InstanceList::InstanceIDRole).toString(); m_selectedInstance = APPLICATION->instances()->getInstanceById(id); if (m_selectedInstance) { ui->instanceToolBar->setEnabled(true); setInstanceActionsEnabled(true); ui->actionLaunchInstance->setEnabled(m_selectedInstance->canLaunch()); ui->actionKillInstance->setEnabled(m_selectedInstance->isRunning()); ui->actionExportInstance->setEnabled(m_selectedInstance->canExport()); renameButton->setText(m_selectedInstance->name()); m_statusLeft->setText(m_selectedInstance->getStatusbarDescription()); updateStatusCenter(); updateInstanceToolIcon(m_selectedInstance->iconKey()); updateLaunchButton(); APPLICATION->settings()->set("SelectedInstance", m_selectedInstance->id()); connect(m_selectedInstance.get(), &BaseInstance::runningStatusChanged, this, &MainWindow::refreshCurrentInstance); connect(m_selectedInstance.get(), &BaseInstance::profilerChanged, this, &MainWindow::refreshCurrentInstance); } else { APPLICATION->settings()->set("SelectedInstance", QString()); selectionBad(); return; } } void MainWindow::instanceSelectRequest(QString id) { setSelectedInstanceById(id); } void MainWindow::instanceDataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight) { auto current = view->selectionModel()->currentIndex(); QItemSelection test(topLeft, bottomRight); if (test.contains(current)) { instanceChanged(current, current); } } void MainWindow::selectionBad() { // start by reseting everything... m_selectedInstance = nullptr; m_statusLeft->setText(tr("No instance selected")); statusBar()->clearMessage(); ui->instanceToolBar->setEnabled(false); setInstanceActionsEnabled(false); updateLaunchButton(); renameButton->setText(tr("Rename Instance")); updateInstanceToolIcon("grass"); // ...and then see if we can enable the previously selected instance setSelectedInstanceById(APPLICATION->settings()->get("SelectedInstance").toString()); } void MainWindow::checkInstancePathForProblems() { QString instanceFolder = APPLICATION->settings()->get("InstanceDir").toString(); if (FS::checkProblemticPathJava(QDir(instanceFolder))) { QMessageBox warning(this); warning.setText(tr("Your instance folder contains \'!\' and this is known to cause Java problems!")); warning.setInformativeText(tr("You have now two options: <br/>" " - change the instance folder in the settings <br/>" " - move this installation of %1 to a different folder") .arg(BuildConfig.LAUNCHER_DISPLAYNAME)); warning.setDefaultButton(QMessageBox::Ok); warning.exec(); } auto tempFolderText = tr("This is a problem: <br/>" " - The launcher will likely be deleted without warning by the operating system <br/>" " - close the launcher now and extract it to a real location, not a temporary folder"); QString pathfoldername = QDir(instanceFolder).absolutePath(); if (pathfoldername.contains("Rar$", Qt::CaseInsensitive)) { QMessageBox warning(this); warning.setText(tr("Your instance folder contains \'Rar$\' - that means you haven't extracted the launcher archive!")); warning.setInformativeText(tempFolderText); warning.setDefaultButton(QMessageBox::Ok); warning.exec(); } else if (pathfoldername.startsWith(QDir::tempPath()) || pathfoldername.contains("/TempState/")) { QMessageBox warning(this); warning.setText(tr("Your instance folder is in a temporary folder: \'%1\'!").arg(QDir::tempPath())); warning.setInformativeText(tempFolderText); warning.setDefaultButton(QMessageBox::Ok); warning.exec(); } } void MainWindow::updateStatusCenter() { m_statusCenter->setVisible(APPLICATION->settings()->get("ShowGlobalGameTime").toBool()); int timePlayed = APPLICATION->instances()->getTotalPlayTime(); if (timePlayed > 0) { m_statusCenter->setText( tr("Total playtime: %1") .arg(Time::prettifyDuration(timePlayed, APPLICATION->settings()->get("ShowGameTimeWithoutDays").toBool()))); } } // "Instance actions" are actions that require an instance to be selected (i.e. "new instance" is not here) // Actions that also require other conditions (e.g. a running instance) won't be changed. void MainWindow::setInstanceActionsEnabled(bool enabled) { ui->actionEditInstance->setEnabled(enabled); ui->actionChangeInstGroup->setEnabled(enabled); ui->actionViewSelectedInstFolder->setEnabled(enabled); ui->actionExportInstance->setEnabled(enabled); ui->actionDeleteInstance->setEnabled(enabled); ui->actionCopyInstance->setEnabled(enabled); ui->actionCreateInstanceShortcut->setEnabled(enabled); } void MainWindow::refreshCurrentInstance() { auto current = view->selectionModel()->currentIndex(); instanceChanged(current, current); }
65,957
C++
.cpp
1,514
36.354029
140
0.670173
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,954
InstanceWindow.cpp
PrismLauncher_PrismLauncher/launcher/ui/InstanceWindow.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * Copyright (C) 2023 TheKodeToad <TheKodeToad@proton.me> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 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 "InstanceWindow.h" #include "Application.h" #include <qlayoutitem.h> #include <QCloseEvent> #include <QHBoxLayout> #include <QMessageBox> #include <QPushButton> #include <QScrollBar> #include "ui/widgets/PageContainer.h" #include "InstancePageProvider.h" #include "icons/IconList.h" InstanceWindow::InstanceWindow(InstancePtr instance, QWidget* parent) : QMainWindow(parent), m_instance(instance) { setAttribute(Qt::WA_DeleteOnClose); auto icon = APPLICATION->icons()->getIcon(m_instance->iconKey()); QString windowTitle = tr("Console window for ") + m_instance->name(); // Set window properties { setWindowIcon(icon); setWindowTitle(windowTitle); } // Add page container { auto provider = std::make_shared<InstancePageProvider>(m_instance); m_container = new PageContainer(provider.get(), "console", this); m_container->setParentContainer(this); setCentralWidget(m_container); setContentsMargins(0, 0, 0, 0); } // Add custom buttons to the page container layout. { auto horizontalLayout = new QHBoxLayout(this); horizontalLayout->setObjectName(QStringLiteral("horizontalLayout")); horizontalLayout->setContentsMargins(6, -1, 6, -1); auto btnHelp = new QPushButton(this); btnHelp->setText(tr("Help")); horizontalLayout->addWidget(btnHelp); connect(btnHelp, &QPushButton::clicked, m_container, &PageContainer::help); auto spacer = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); horizontalLayout->addSpacerItem(spacer); m_launchButton = new QToolButton(this); m_launchButton->setText(tr("&Launch")); m_launchButton->setToolTip(tr("Launch the instance")); m_launchButton->setPopupMode(QToolButton::MenuButtonPopup); m_launchButton->setMinimumWidth(80); // HACK!! horizontalLayout->addWidget(m_launchButton); connect(m_launchButton, &QPushButton::clicked, this, [this] { APPLICATION->launch(m_instance); }); m_killButton = new QPushButton(this); m_killButton->setText(tr("&Kill")); m_killButton->setToolTip(tr("Kill the running instance")); m_killButton->setShortcut(QKeySequence(tr("Ctrl+K"))); horizontalLayout->addWidget(m_killButton); connect(m_killButton, &QPushButton::clicked, this, [this] { APPLICATION->kill(m_instance); }); updateButtons(); m_closeButton = new QPushButton(this); m_closeButton->setText(tr("Close")); horizontalLayout->addWidget(m_closeButton); connect(m_closeButton, &QPushButton::clicked, this, &QMainWindow::close); m_container->addButtons(horizontalLayout); connect(m_instance.get(), &BaseInstance::profilerChanged, this, &InstanceWindow::updateButtons); connect(APPLICATION, &Application::globalSettingsClosed, this, &InstanceWindow::updateButtons); } // restore window state { auto base64State = APPLICATION->settings()->get("ConsoleWindowState").toByteArray(); restoreState(QByteArray::fromBase64(base64State)); auto base64Geometry = APPLICATION->settings()->get("ConsoleWindowGeometry").toByteArray(); restoreGeometry(QByteArray::fromBase64(base64Geometry)); } // set up instance and launch process recognition { auto launchTask = m_instance->getLaunchTask(); instanceLaunchTaskChanged(launchTask); connect(m_instance.get(), &BaseInstance::launchTaskChanged, this, &InstanceWindow::instanceLaunchTaskChanged); connect(m_instance.get(), &BaseInstance::runningStatusChanged, this, &InstanceWindow::runningStateChanged); } // set up instance destruction detection { connect(m_instance.get(), &BaseInstance::statusChanged, this, &InstanceWindow::on_instanceStatusChanged); } // add ourself as the modpack page's instance window { static_cast<ManagedPackPage*>(m_container->getPage("managed_pack"))->setInstanceWindow(this); } show(); } void InstanceWindow::on_instanceStatusChanged(BaseInstance::Status, BaseInstance::Status newStatus) { if (newStatus == BaseInstance::Status::Gone) { m_doNotSave = true; close(); } } void InstanceWindow::updateButtons() { m_launchButton->setEnabled(m_instance->canLaunch()); m_killButton->setEnabled(m_instance->isRunning()); QMenu* launchMenu = m_launchButton->menu(); if (launchMenu) launchMenu->clear(); else launchMenu = new QMenu(this); m_instance->populateLaunchMenu(launchMenu); m_launchButton->setMenu(launchMenu); } void InstanceWindow::instanceLaunchTaskChanged(shared_qobject_ptr<LaunchTask> proc) { m_proc = proc; } void InstanceWindow::runningStateChanged(bool running) { updateButtons(); m_container->refreshContainer(); if (running) { selectPage("log"); } } void InstanceWindow::closeEvent(QCloseEvent* event) { bool proceed = true; if (!m_doNotSave) { proceed &= m_container->prepareToClose(); } if (!proceed) { return; } APPLICATION->settings()->set("ConsoleWindowState", saveState().toBase64()); APPLICATION->settings()->set("ConsoleWindowGeometry", saveGeometry().toBase64()); emit isClosing(); event->accept(); } bool InstanceWindow::saveAll() { return m_container->saveAll(); } QString InstanceWindow::instanceId() { return m_instance->id(); } bool InstanceWindow::selectPage(QString pageId) { return m_container->selectPage(pageId); } void InstanceWindow::refreshContainer() { m_container->refreshContainer(); } BasePage* InstanceWindow::selectedPage() const { return m_container->selectedPage(); } bool InstanceWindow::requestClose() { if (m_container->prepareToClose()) { close(); return true; } return false; }
7,492
C++
.cpp
194
33.793814
118
0.707341
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,955
GuiUtil.cpp
PrismLauncher_PrismLauncher/launcher/ui/GuiUtil.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Lenny McLennington <lenny@sneed.church> * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * Copyright (C) 2022 TheKodeToad <TheKodeToad@proton.me> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 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 "GuiUtil.h" #include <QApplication> #include <QClipboard> #include <QFileDialog> #include <QStandardPaths> #include "net/PasteUpload.h" #include "ui/dialogs/CustomMessageBox.h" #include "ui/dialogs/ProgressDialog.h" #include <BuildConfig.h> #include <DesktopServices.h> #include <settings/SettingsObject.h> #include "Application.h" std::optional<QString> GuiUtil::uploadPaste(const QString& name, const QString& text, QWidget* parentWidget) { ProgressDialog dialog(parentWidget); auto pasteTypeSetting = static_cast<PasteUpload::PasteType>(APPLICATION->settings()->get("PastebinType").toInt()); auto pasteCustomAPIBaseSetting = APPLICATION->settings()->get("PastebinCustomAPIBase").toString(); { QUrl baseUrl; if (pasteCustomAPIBaseSetting.isEmpty()) baseUrl = PasteUpload::PasteTypes[pasteTypeSetting].defaultBase; else baseUrl = pasteCustomAPIBaseSetting; if (baseUrl.isValid()) { auto response = CustomMessageBox::selectable(parentWidget, QObject::tr("Confirm Upload"), QObject::tr("You are about to upload \"%1\" to %2.\n" "You should double-check for personal information.\n\n" "Are you sure?") .arg(name, baseUrl.host()), QMessageBox::Warning, QMessageBox::Yes | QMessageBox::No, QMessageBox::No) ->exec(); if (response != QMessageBox::Yes) return {}; } } std::unique_ptr<PasteUpload> paste(new PasteUpload(parentWidget, text, pasteCustomAPIBaseSetting, pasteTypeSetting)); dialog.execWithTask(paste.get()); if (!paste->wasSuccessful()) { CustomMessageBox::selectable(parentWidget, QObject::tr("Upload failed"), paste->failReason(), QMessageBox::Critical)->exec(); return QString(); } else { const QString link = paste->pasteLink(); setClipboardText(link); CustomMessageBox::selectable( parentWidget, QObject::tr("Upload finished"), QObject::tr("The <a href=\"%1\">link to the uploaded log</a> has been placed in your clipboard.").arg(link), QMessageBox::Information) ->exec(); return link; } } void GuiUtil::setClipboardText(const QString& text) { QApplication::clipboard()->setText(text); } static QStringList BrowseForFileInternal(QString context, QString caption, QString filter, QString defaultPath, QWidget* parentWidget, bool single) { static QMap<QString, QString> savedPaths; QFileDialog w(parentWidget, caption); QSet<QString> locations; auto f = [&locations](QStandardPaths::StandardLocation l) { QString location = QStandardPaths::writableLocation(l); QFileInfo finfo(location); if (!finfo.exists()) { return; } locations.insert(location); }; f(QStandardPaths::DesktopLocation); f(QStandardPaths::DocumentsLocation); f(QStandardPaths::DownloadLocation); f(QStandardPaths::HomeLocation); QList<QUrl> urls; for (auto location : locations) { urls.append(QUrl::fromLocalFile(location)); } urls.append(QUrl::fromLocalFile(defaultPath)); w.setFileMode(single ? QFileDialog::ExistingFile : QFileDialog::ExistingFiles); w.setAcceptMode(QFileDialog::AcceptOpen); w.setNameFilter(filter); QString pathToOpen; if (savedPaths.contains(context)) { pathToOpen = savedPaths[context]; } else { pathToOpen = defaultPath; } if (!pathToOpen.isEmpty()) { QFileInfo finfo(pathToOpen); if (finfo.exists() && finfo.isDir()) { w.setDirectory(finfo.absoluteFilePath()); } } w.setSidebarUrls(urls); if (w.exec()) { savedPaths[context] = w.directory().absolutePath(); return w.selectedFiles(); } savedPaths[context] = w.directory().absolutePath(); return {}; } QString GuiUtil::BrowseForFile(QString context, QString caption, QString filter, QString defaultPath, QWidget* parentWidget) { auto resultList = BrowseForFileInternal(context, caption, filter, defaultPath, parentWidget, true); if (resultList.size()) { return resultList[0]; } return QString(); } QStringList GuiUtil::BrowseForFiles(QString context, QString caption, QString filter, QString defaultPath, QWidget* parentWidget) { return BrowseForFileInternal(context, caption, filter, defaultPath, parentWidget, false); }
6,573
C++
.cpp
153
34.699346
133
0.648492
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
28,956
JavaWizardPage.cpp
PrismLauncher_PrismLauncher/launcher/ui/setupwizard/JavaWizardPage.cpp
#include "JavaWizardPage.h" #include "Application.h" #include <QFileDialog> #include <QGroupBox> #include <QLabel> #include <QLineEdit> #include <QPushButton> #include <QSpinBox> #include <QToolButton> #include <QVBoxLayout> #include <sys.h> #include "JavaCommon.h" #include "ui/widgets/JavaSettingsWidget.h" #include "ui/widgets/VersionSelectWidget.h" JavaWizardPage::JavaWizardPage(QWidget* parent) : BaseWizardPage(parent) { setupUi(); } void JavaWizardPage::setupUi() { setObjectName(QStringLiteral("javaPage")); QVBoxLayout* layout = new QVBoxLayout(this); m_java_widget = new JavaSettingsWidget(this); layout->addWidget(m_java_widget); setLayout(layout); retranslate(); } void JavaWizardPage::refresh() { m_java_widget->refresh(); } void JavaWizardPage::initializePage() { m_java_widget->initialize(); } bool JavaWizardPage::wantsRefreshButton() { return true; } bool JavaWizardPage::validatePage() { auto settings = APPLICATION->settings(); auto result = m_java_widget->validate(); settings->set("AutomaticJavaSwitch", m_java_widget->autoDetectJava()); settings->set("AutomaticJavaDownload", m_java_widget->autoDownloadJava()); settings->set("UserAskedAboutAutomaticJavaDownload", true); switch (result) { default: case JavaSettingsWidget::ValidationStatus::Bad: { return false; } case JavaSettingsWidget::ValidationStatus::AllOK: { settings->set("JavaPath", m_java_widget->javaPath()); } /* fallthrough */ case JavaSettingsWidget::ValidationStatus::JavaBad: { // Memory auto s = APPLICATION->settings(); s->set("MinMemAlloc", m_java_widget->minHeapSize()); s->set("MaxMemAlloc", m_java_widget->maxHeapSize()); if (m_java_widget->permGenEnabled()) { s->set("PermGen", m_java_widget->permGenSize()); } else { s->reset("PermGen"); } return true; } } } void JavaWizardPage::retranslate() { setTitle(tr("Java")); setSubTitle( tr("Please select how much memory to allocate to instances and if Prism Launcher should manage Java automatically or manually.")); m_java_widget->retranslate(); }
2,301
C++
.cpp
75
25.56
138
0.677813
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
28,957
AutoJavaWizardPage.cpp
PrismLauncher_PrismLauncher/launcher/ui/setupwizard/AutoJavaWizardPage.cpp
#include "AutoJavaWizardPage.h" #include "ui_AutoJavaWizardPage.h" #include "Application.h" AutoJavaWizardPage::AutoJavaWizardPage(QWidget* parent) : BaseWizardPage(parent), ui(new Ui::AutoJavaWizardPage) { ui->setupUi(this); } AutoJavaWizardPage::~AutoJavaWizardPage() { delete ui; } void AutoJavaWizardPage::initializePage() {} bool AutoJavaWizardPage::validatePage() { auto s = APPLICATION->settings(); if (!ui->previousSettingsRadioButton->isChecked()) { s->set("AutomaticJavaSwitch", true); s->set("AutomaticJavaDownload", true); } s->set("UserAskedAboutAutomaticJavaDownload", true); return true; } void AutoJavaWizardPage::retranslate() { ui->retranslateUi(this); }
728
C++
.cpp
26
24.884615
112
0.746763
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,958
ThemeWizardPage.cpp
PrismLauncher_PrismLauncher/launcher/ui/setupwizard/ThemeWizardPage.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Tayou <git@tayou.org> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "ThemeWizardPage.h" #include "ui_ThemeWizardPage.h" #include "Application.h" #include "ui/themes/ITheme.h" #include "ui/themes/ThemeManager.h" #include "ui/widgets/ThemeCustomizationWidget.h" #include "ui_ThemeCustomizationWidget.h" ThemeWizardPage::ThemeWizardPage(QWidget* parent) : BaseWizardPage(parent), ui(new Ui::ThemeWizardPage) { ui->setupUi(this); connect(ui->themeCustomizationWidget, &ThemeCustomizationWidget::currentIconThemeChanged, this, &ThemeWizardPage::updateIcons); connect(ui->themeCustomizationWidget, &ThemeCustomizationWidget::currentCatChanged, this, &ThemeWizardPage::updateCat); updateIcons(); updateCat(); } ThemeWizardPage::~ThemeWizardPage() { delete ui; } void ThemeWizardPage::updateIcons() { qDebug() << "Setting Icons"; ui->previewIconButton0->setIcon(APPLICATION->getThemedIcon("new")); ui->previewIconButton1->setIcon(APPLICATION->getThemedIcon("centralmods")); ui->previewIconButton2->setIcon(APPLICATION->getThemedIcon("viewfolder")); ui->previewIconButton3->setIcon(APPLICATION->getThemedIcon("launch")); ui->previewIconButton4->setIcon(APPLICATION->getThemedIcon("copy")); ui->previewIconButton5->setIcon(APPLICATION->getThemedIcon("export")); ui->previewIconButton6->setIcon(APPLICATION->getThemedIcon("delete")); ui->previewIconButton7->setIcon(APPLICATION->getThemedIcon("about")); ui->previewIconButton8->setIcon(APPLICATION->getThemedIcon("settings")); ui->previewIconButton9->setIcon(APPLICATION->getThemedIcon("cat")); update(); repaint(); parentWidget()->update(); } void ThemeWizardPage::updateCat() { qDebug() << "Setting Cat"; ui->catImagePreviewButton->setIcon(QIcon(QString(R"(%1)").arg(APPLICATION->themeManager()->getCatPack()))); } void ThemeWizardPage::retranslate() { ui->retranslateUi(this); }
2,590
C++
.cpp
62
38.919355
131
0.759524
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,959
LanguageWizardPage.cpp
PrismLauncher_PrismLauncher/launcher/ui/setupwizard/LanguageWizardPage.cpp
#include "LanguageWizardPage.h" #include <Application.h> #include <translations/TranslationsModel.h> #include <BuildConfig.h> #include <QVBoxLayout> #include "ui/widgets/LanguageSelectionWidget.h" LanguageWizardPage::LanguageWizardPage(QWidget* parent) : BaseWizardPage(parent) { setObjectName(QStringLiteral("languagePage")); auto layout = new QVBoxLayout(this); mainWidget = new LanguageSelectionWidget(this); layout->setContentsMargins(0, 0, 0, 0); layout->addWidget(mainWidget); retranslate(); } LanguageWizardPage::~LanguageWizardPage() {} bool LanguageWizardPage::wantsRefreshButton() { return true; } void LanguageWizardPage::refresh() { auto translations = APPLICATION->translations(); translations->downloadIndex(); } bool LanguageWizardPage::validatePage() { auto settings = APPLICATION->settings(); QString key = mainWidget->getSelectedLanguageKey(); settings->set("Language", key); return true; } void LanguageWizardPage::retranslate() { setTitle(tr("Language")); setSubTitle(tr("Select the language to use in %1").arg(BuildConfig.LAUNCHER_DISPLAYNAME)); mainWidget->retranslate(); }
1,168
C++
.cpp
38
27.842105
94
0.766488
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
28,960
PasteWizardPage.cpp
PrismLauncher_PrismLauncher/launcher/ui/setupwizard/PasteWizardPage.cpp
#include "PasteWizardPage.h" #include "ui_PasteWizardPage.h" #include "Application.h" #include "net/PasteUpload.h" PasteWizardPage::PasteWizardPage(QWidget* parent) : BaseWizardPage(parent), ui(new Ui::PasteWizardPage) { ui->setupUi(this); } PasteWizardPage::~PasteWizardPage() { delete ui; } void PasteWizardPage::initializePage() {} bool PasteWizardPage::validatePage() { auto s = APPLICATION->settings(); QString prevPasteURL = s->get("PastebinURL").toString(); s->reset("PastebinURL"); if (ui->previousSettingsRadioButton->isChecked()) { bool usingDefaultBase = prevPasteURL == PasteUpload::PasteTypes.at(PasteUpload::PasteType::NullPointer).defaultBase; s->set("PastebinType", PasteUpload::PasteType::NullPointer); if (!usingDefaultBase) s->set("PastebinCustomAPIBase", prevPasteURL); } return true; } void PasteWizardPage::retranslate() { ui->retranslateUi(this); }
951
C++
.cpp
30
28.066667
124
0.733042
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,961
SetupWizard.cpp
PrismLauncher_PrismLauncher/launcher/ui/setupwizard/SetupWizard.cpp
#include "SetupWizard.h" #include "JavaWizardPage.h" #include "LanguageWizardPage.h" #include <Application.h> #include <FileSystem.h> #include "translations/TranslationsModel.h" #include <BuildConfig.h> #include <QAbstractButton> SetupWizard::SetupWizard(QWidget* parent) : QWizard(parent) { setObjectName(QStringLiteral("SetupWizard")); resize(620, 660); setMinimumSize(300, 400); // make it ugly everywhere to avoid variability in theming setWizardStyle(QWizard::ClassicStyle); setOptions(QWizard::NoCancelButton | QWizard::IndependentPages | QWizard::HaveCustomButton1); retranslate(); connect(this, &QWizard::currentIdChanged, this, &SetupWizard::pageChanged); } void SetupWizard::retranslate() { setButtonText(QWizard::NextButton, tr("&Next >")); setButtonText(QWizard::BackButton, tr("< &Back")); setButtonText(QWizard::FinishButton, tr("&Finish")); setButtonText(QWizard::CustomButton1, tr("&Refresh")); setWindowTitle(tr("%1 Quick Setup").arg(BuildConfig.LAUNCHER_DISPLAYNAME)); } BaseWizardPage* SetupWizard::getBasePage(int id) { if (id == -1) return nullptr; auto pagePtr = page(id); if (!pagePtr) return nullptr; return dynamic_cast<BaseWizardPage*>(pagePtr); } BaseWizardPage* SetupWizard::getCurrentBasePage() { return getBasePage(currentId()); } void SetupWizard::pageChanged(int id) { auto basePagePtr = getBasePage(id); if (!basePagePtr) { return; } if (basePagePtr->wantsRefreshButton()) { setButtonLayout({ QWizard::CustomButton1, QWizard::Stretch, QWizard::BackButton, QWizard::NextButton, QWizard::FinishButton }); auto customButton = button(QWizard::CustomButton1); connect(customButton, &QAbstractButton::clicked, [this]() { auto basePagePtr = getCurrentBasePage(); if (basePagePtr) { basePagePtr->refresh(); } }); } else { setButtonLayout({ QWizard::Stretch, QWizard::BackButton, QWizard::NextButton, QWizard::FinishButton }); } } void SetupWizard::changeEvent(QEvent* event) { if (event->type() == QEvent::LanguageChange) { retranslate(); } QWizard::changeEvent(event); } SetupWizard::~SetupWizard() {}
2,272
C++
.cpp
67
29.268657
135
0.70497
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
28,962
LoginWizardPage.cpp
PrismLauncher_PrismLauncher/launcher/ui/setupwizard/LoginWizardPage.cpp
#include "LoginWizardPage.h" #include "minecraft/auth/AccountList.h" #include "ui/dialogs/MSALoginDialog.h" #include "ui_LoginWizardPage.h" #include "Application.h" LoginWizardPage::LoginWizardPage(QWidget* parent) : BaseWizardPage(parent), ui(new Ui::LoginWizardPage) { ui->setupUi(this); } LoginWizardPage::~LoginWizardPage() { delete ui; } void LoginWizardPage::initializePage() {} bool LoginWizardPage::validatePage() { return true; } void LoginWizardPage::retranslate() { ui->retranslateUi(this); } void LoginWizardPage::on_pushButton_clicked() { wizard()->hide(); auto account = MSALoginDialog::newAccount(nullptr); wizard()->show(); if (account) { APPLICATION->accounts()->addAccount(account); APPLICATION->accounts()->setDefaultAccount(account); if (wizard()->currentId() == wizard()->pageIds().last()) { wizard()->accept(); } else { wizard()->next(); } } }
973
C++
.cpp
37
22.405405
103
0.685684
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,963
CustomPage.cpp
PrismLauncher_PrismLauncher/launcher/ui/pages/modplatform/CustomPage.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 Jamie Mansfield <jmansfield@cadixdev.org> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 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 "CustomPage.h" #include "ui_CustomPage.h" #include <QTabBar> #include "Application.h" #include "Filter.h" #include "Version.h" #include "meta/Index.h" #include "meta/VersionList.h" #include "minecraft/VanillaInstanceCreationTask.h" #include "ui/dialogs/NewInstanceDialog.h" CustomPage::CustomPage(NewInstanceDialog* dialog, QWidget* parent) : QWidget(parent), dialog(dialog), ui(new Ui::CustomPage) { ui->setupUi(this); connect(ui->versionList, &VersionSelectWidget::selectedVersionChanged, this, &CustomPage::setSelectedVersion); filterChanged(); connect(ui->alphaFilter, &QCheckBox::stateChanged, this, &CustomPage::filterChanged); connect(ui->betaFilter, &QCheckBox::stateChanged, this, &CustomPage::filterChanged); connect(ui->snapshotFilter, &QCheckBox::stateChanged, this, &CustomPage::filterChanged); connect(ui->releaseFilter, &QCheckBox::stateChanged, this, &CustomPage::filterChanged); connect(ui->experimentsFilter, &QCheckBox::stateChanged, this, &CustomPage::filterChanged); connect(ui->refreshBtn, &QPushButton::clicked, this, &CustomPage::refresh); connect(ui->loaderVersionList, &VersionSelectWidget::selectedVersionChanged, this, &CustomPage::setSelectedLoaderVersion); connect(ui->noneFilter, &QRadioButton::toggled, this, &CustomPage::loaderFilterChanged); connect(ui->forgeFilter, &QRadioButton::toggled, this, &CustomPage::loaderFilterChanged); connect(ui->fabricFilter, &QRadioButton::toggled, this, &CustomPage::loaderFilterChanged); connect(ui->quiltFilter, &QRadioButton::toggled, this, &CustomPage::loaderFilterChanged); connect(ui->liteLoaderFilter, &QRadioButton::toggled, this, &CustomPage::loaderFilterChanged); connect(ui->loaderRefreshBtn, &QPushButton::clicked, this, &CustomPage::loaderRefresh); } void CustomPage::openedImpl() { if (!initialized) { auto vlist = APPLICATION->metadataIndex()->get("net.minecraft"); ui->versionList->initialize(vlist.get()); initialized = true; } else { suggestCurrent(); } } void CustomPage::refresh() { ui->versionList->loadList(); } void CustomPage::loaderRefresh() { if (ui->noneFilter->isChecked()) return; ui->loaderVersionList->loadList(); } void CustomPage::filterChanged() { QStringList out; if (ui->alphaFilter->isChecked()) out << "(alpha)"; if (ui->betaFilter->isChecked()) out << "(beta)"; if (ui->snapshotFilter->isChecked()) out << "(snapshot)"; if (ui->releaseFilter->isChecked()) out << "(release)"; if (ui->experimentsFilter->isChecked()) out << "(experiment)"; auto regexp = out.join('|'); ui->versionList->setFilter(BaseVersionList::TypeRole, new RegexpFilter(regexp, false)); } void CustomPage::loaderFilterChanged() { QString minecraftVersion; if (m_selectedVersion) { minecraftVersion = m_selectedVersion->descriptor(); } else { ui->loaderVersionList->setExactFilter(BaseVersionList::ParentVersionRole, "AAA"); // empty list ui->loaderVersionList->setEmptyString(tr("No Minecraft version is selected.")); ui->loaderVersionList->setEmptyMode(VersionListView::String); return; } if (ui->noneFilter->isChecked()) { ui->loaderVersionList->setExactFilter(BaseVersionList::ParentVersionRole, "AAA"); // empty list ui->loaderVersionList->setEmptyString(tr("No mod loader is selected.")); ui->loaderVersionList->setEmptyMode(VersionListView::String); return; } else if (ui->neoForgeFilter->isChecked()) { ui->loaderVersionList->setExactFilter(BaseVersionList::ParentVersionRole, minecraftVersion); m_selectedLoader = "net.neoforged"; } else if (ui->forgeFilter->isChecked()) { ui->loaderVersionList->setExactFilter(BaseVersionList::ParentVersionRole, minecraftVersion); m_selectedLoader = "net.minecraftforge"; } else if (ui->fabricFilter->isChecked()) { // FIXME: dirty hack because the launcher is unaware of Fabric's dependencies if (Version(minecraftVersion) >= Version("1.14")) // Fabric/Quilt supported ui->loaderVersionList->setExactFilter(BaseVersionList::ParentVersionRole, ""); else // Fabric/Quilt unsupported ui->loaderVersionList->setExactFilter(BaseVersionList::ParentVersionRole, "AAA"); // clear list m_selectedLoader = "net.fabricmc.fabric-loader"; } else if (ui->quiltFilter->isChecked()) { // FIXME: dirty hack because the launcher is unaware of Quilt's dependencies (same as Fabric) if (Version(minecraftVersion) >= Version("1.14")) // Fabric/Quilt supported ui->loaderVersionList->setExactFilter(BaseVersionList::ParentVersionRole, ""); else // Fabric/Quilt unsupported ui->loaderVersionList->setExactFilter(BaseVersionList::ParentVersionRole, "AAA"); // clear list m_selectedLoader = "org.quiltmc.quilt-loader"; } else if (ui->liteLoaderFilter->isChecked()) { ui->loaderVersionList->setExactFilter(BaseVersionList::ParentVersionRole, minecraftVersion); m_selectedLoader = "com.mumfrey.liteloader"; } auto vlist = APPLICATION->metadataIndex()->get(m_selectedLoader); ui->loaderVersionList->initialize(vlist.get()); ui->loaderVersionList->selectRecommended(); ui->loaderVersionList->setEmptyString(tr("No versions are currently available for Minecraft %1").arg(minecraftVersion)); } CustomPage::~CustomPage() { delete ui; } bool CustomPage::shouldDisplay() const { return true; } void CustomPage::retranslate() { ui->retranslateUi(this); } BaseVersion::Ptr CustomPage::selectedVersion() const { return m_selectedVersion; } BaseVersion::Ptr CustomPage::selectedLoaderVersion() const { return m_selectedLoaderVersion; } QString CustomPage::selectedLoader() const { return m_selectedLoader; } void CustomPage::suggestCurrent() { if (!isOpened) { return; } if (!m_selectedVersion) { dialog->setSuggestedPack(); return; } // There isn't a selected version if the version list is empty if (ui->loaderVersionList->selectedVersion() == nullptr) dialog->setSuggestedPack(m_selectedVersion->descriptor(), new VanillaCreationTask(m_selectedVersion)); else { dialog->setSuggestedPack(m_selectedVersion->descriptor(), new VanillaCreationTask(m_selectedVersion, m_selectedLoader, m_selectedLoaderVersion)); } dialog->setSuggestedIcon("default"); } void CustomPage::setSelectedVersion(BaseVersion::Ptr version) { m_selectedVersion = version; suggestCurrent(); loaderFilterChanged(); } void CustomPage::setSelectedLoaderVersion(BaseVersion::Ptr version) { m_selectedLoaderVersion = version; suggestCurrent(); }
8,540
C++
.cpp
197
38.80203
126
0.707006
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,964
OptionalModDialog.cpp
PrismLauncher_PrismLauncher/launcher/ui/pages/modplatform/OptionalModDialog.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2023 Trial97 <alexandru.tripon97@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "OptionalModDialog.h" #include "ui_OptionalModDialog.h" OptionalModDialog::OptionalModDialog(QWidget* parent, const QStringList& mods) : QDialog(parent), ui(new Ui::OptionalModDialog) { ui->setupUi(this); for (const QString& mod : mods) { auto item = new QListWidgetItem(mod, ui->list); item->setFlags(item->flags() | Qt::ItemIsUserCheckable); item->setCheckState(Qt::Unchecked); item->setData(Qt::UserRole, mod); } connect(ui->selectAllButton, &QPushButton::clicked, ui->list, [this] { for (int i = 0; i < ui->list->count(); i++) ui->list->item(i)->setCheckState(Qt::Checked); }); connect(ui->clearAllButton, &QPushButton::clicked, ui->list, [this] { for (int i = 0; i < ui->list->count(); i++) ui->list->item(i)->setCheckState(Qt::Unchecked); }); connect(ui->list, &QListWidget::itemActivated, [](QListWidgetItem* item) { if (item->checkState() == Qt::Checked) item->setCheckState(Qt::Unchecked); else item->setCheckState(Qt::Checked); }); ui->buttonBox->button(QDialogButtonBox::Cancel)->setText(tr("Cancel")); ui->buttonBox->button(QDialogButtonBox::Ok)->setText(tr("OK")); } OptionalModDialog::~OptionalModDialog() { delete ui; } QStringList OptionalModDialog::getResult() { QStringList result; result.reserve(ui->list->count()); for (int i = 0; i < ui->list->count(); i++) { auto item = ui->list->item(i); if (item->checkState() == Qt::Checked) result.append(item->data(Qt::UserRole).toString()); } return result; }
2,390
C++
.cpp
60
35.016667
127
0.668244
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,965
ShaderPackPage.cpp
PrismLauncher_PrismLauncher/launcher/ui/pages/modplatform/ShaderPackPage.cpp
// SPDX-FileCopyrightText: 2023 flowln <flowlnlnln@gmail.com> // // SPDX-License-Identifier: GPL-3.0-only #include "ShaderPackPage.h" #include "modplatform/ModIndex.h" #include "ui_ResourcePage.h" #include "ShaderPackModel.h" #include "Application.h" #include "ui/dialogs/ResourceDownloadDialog.h" #include <QRegularExpression> namespace ResourceDownload { ShaderPackResourcePage::ShaderPackResourcePage(ShaderPackDownloadDialog* dialog, BaseInstance& instance) : ResourcePage(dialog, instance) { connect(m_ui->packView, &QListView::doubleClicked, this, &ShaderPackResourcePage::onResourceSelected); } /******** Callbacks to events in the UI (set up in the derived classes) ********/ void ShaderPackResourcePage::triggerSearch() { m_ui->packView->selectionModel()->setCurrentIndex({}, QItemSelectionModel::SelectionFlag::ClearAndSelect); m_ui->packView->clearSelection(); m_ui->packDescription->clear(); m_ui->versionSelectionBox->clear(); updateSelectionButton(); static_cast<ShaderPackResourceModel*>(m_model)->searchWithTerm(getSearchTerm(), m_ui->sortByBox->currentData().toUInt()); m_fetchProgress.watch(m_model->activeSearchJob().get()); } QMap<QString, QString> ShaderPackResourcePage::urlHandlers() const { QMap<QString, QString> map; map.insert(QRegularExpression::anchoredPattern("(?:www\\.)?modrinth\\.com\\/shaders\\/([^\\/]+)\\/?"), "modrinth"); map.insert(QRegularExpression::anchoredPattern("(?:www\\.)?curseforge\\.com\\/minecraft\\/customization\\/([^\\/]+)\\/?"), "curseforge"); map.insert(QRegularExpression::anchoredPattern("minecraft\\.curseforge\\.com\\/projects\\/([^\\/]+)\\/?"), "curseforge"); return map; } void ShaderPackResourcePage::addResourceToPage(ModPlatform::IndexedPack::Ptr pack, ModPlatform::IndexedVersion& version, const std::shared_ptr<ResourceFolderModel> base_model) { bool is_indexed = !APPLICATION->settings()->get("ModMetadataDisabled").toBool(); QString custom_target_folder; if (version.loaders & ModPlatform::Cauldron) custom_target_folder = QStringLiteral("resourcepacks"); m_model->addPack(pack, version, base_model, is_indexed, custom_target_folder); } } // namespace ResourceDownload
2,335
C++
.cpp
46
45.456522
137
0.711775
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,966
ImportPage.cpp
PrismLauncher_PrismLauncher/launcher/ui/pages/modplatform/ImportPage.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 Jamie Mansfield <jmansfield@cadixdev.org> * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 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 "ImportPage.h" #include "ui/dialogs/ProgressDialog.h" #include "ui_ImportPage.h" #include <QFileDialog> #include <QMimeDatabase> #include <QValidator> #include <utility> #include "ui/dialogs/CustomMessageBox.h" #include "ui/dialogs/NewInstanceDialog.h" #include "modplatform/flame/FlameAPI.h" #include "Json.h" #include "InstanceImportTask.h" #include "net/NetJob.h" class UrlValidator : public QValidator { public: using QValidator::QValidator; State validate(QString& in, [[maybe_unused]] int& pos) const { const QUrl url(in); if (url.isValid() && !url.isRelative() && !url.isEmpty()) { return Acceptable; } else if (QFile::exists(in)) { return Acceptable; } else { return Intermediate; } } }; ImportPage::ImportPage(NewInstanceDialog* dialog, QWidget* parent) : QWidget(parent), ui(new Ui::ImportPage), dialog(dialog) { ui->setupUi(this); ui->modpackEdit->setValidator(new UrlValidator(ui->modpackEdit)); connect(ui->modpackEdit, &QLineEdit::textChanged, this, &ImportPage::updateState); } ImportPage::~ImportPage() { delete ui; } bool ImportPage::shouldDisplay() const { return true; } void ImportPage::retranslate() { ui->retranslateUi(this); } void ImportPage::openedImpl() { updateState(); } void ImportPage::updateState() { if (!isOpened) { return; } if (ui->modpackEdit->hasAcceptableInput()) { QString input = ui->modpackEdit->text().trimmed(); auto url = QUrl::fromUserInput(input); if (url.isLocalFile()) { // FIXME: actually do some validation of what's inside here... this is fake AF QFileInfo fi(input); // Allow non-latin people to use ZIP files! bool isZip = QMimeDatabase().mimeTypeForUrl(url).suffixes().contains("zip"); // mrpack is a modrinth pack bool isMRPack = fi.suffix() == "mrpack"; if (fi.exists() && (isZip || isMRPack)) { auto extra_info = QMap(m_extra_info); qDebug() << "Pack Extra Info" << extra_info << m_extra_info; dialog->setSuggestedPack(fi.completeBaseName(), new InstanceImportTask(url, this, std::move(extra_info))); dialog->setSuggestedIcon("default"); } } else if (url.scheme() == "curseforge") { // need to find the download link for the modpack // format of url curseforge://install?addonId=IDHERE&fileId=IDHERE QUrlQuery query(url); if (query.allQueryItemValues("addonId").isEmpty() || query.allQueryItemValues("fileId").isEmpty()) { qDebug() << "Invalid curseforge link:" << url; return; } auto addonId = query.allQueryItemValues("addonId")[0]; auto fileId = query.allQueryItemValues("fileId")[0]; auto array = std::make_shared<QByteArray>(); auto api = FlameAPI(); auto job = api.getFile(addonId, fileId, array); connect(job.get(), &NetJob::failed, this, [this](QString reason) { CustomMessageBox::selectable(this, tr("Error"), reason, QMessageBox::Critical)->show(); }); connect(job.get(), &NetJob::succeeded, this, [this, array, addonId, fileId] { qDebug() << "Returned CFURL Json:\n" << array->toStdString().c_str(); auto doc = Json::requireDocument(*array); auto data = Json::ensureObject(Json::ensureObject(doc.object()), "data"); // No way to find out if it's a mod or a modpack before here // And also we need to check if it ends with .zip, instead of any better way auto fileName = Json::ensureString(data, "fileName"); if (fileName.endsWith(".zip")) { // Have to use ensureString then use QUrl to get proper url encoding auto dl_url = QUrl(Json::ensureString(data, "downloadUrl", "", "downloadUrl")); if (!dl_url.isValid()) { CustomMessageBox::selectable( this, tr("Error"), tr("The modpack %1 is blocked for third-parties! Please download it manually.").arg(fileName), QMessageBox::Critical) ->show(); return; } QFileInfo dl_file(dl_url.fileName()); QString pack_name = Json::ensureString(data, "displayName", dl_file.completeBaseName(), "displayName"); QMap<QString, QString> extra_info; extra_info.insert("pack_id", addonId); extra_info.insert("pack_version_id", fileId); dialog->setSuggestedPack(pack_name, new InstanceImportTask(dl_url, this, std::move(extra_info))); dialog->setSuggestedIcon("default"); } else { CustomMessageBox::selectable(this, tr("Error"), tr("This url isn't a valid modpack !"), QMessageBox::Critical)->show(); } }); ProgressDialog dlUrlDialod(this); dlUrlDialod.setSkipButton(true, tr("Abort")); dlUrlDialod.execWithTask(job.get()); return; } else { if (input.endsWith("?client=y")) { input.chop(9); input.append("/file"); url = QUrl::fromUserInput(input); } // hook, line and sinker. QFileInfo fi(url.fileName()); auto extra_info = QMap(m_extra_info); dialog->setSuggestedPack(fi.completeBaseName(), new InstanceImportTask(url, this, std::move(extra_info))); dialog->setSuggestedIcon("default"); } } else { dialog->setSuggestedPack(); } } void ImportPage::setUrl(const QString& url) { ui->modpackEdit->setText(url); updateState(); } void ImportPage::setExtraInfo(const QMap<QString, QString>& extra_info) { m_extra_info = extra_info; updateState(); } void ImportPage::on_modpackBtn_clicked() { const QMimeType zip = QMimeDatabase().mimeTypeForName("application/zip"); auto filter = tr("Supported files") + QString(" (%1 *.mrpack)").arg(zip.globPatterns().join(" ")); filter += ";;" + zip.filterString(); //: Option for filtering for *.mrpack files when importing filter += ";;" + tr("Modrinth pack") + " (*.mrpack)"; const QUrl url = QFileDialog::getOpenFileUrl(this, tr("Choose modpack"), modpackUrl(), filter); if (url.isValid()) { if (url.isLocalFile()) { ui->modpackEdit->setText(url.toLocalFile()); } else { ui->modpackEdit->setText(url.toString()); } } } QUrl ImportPage::modpackUrl() const { const QUrl url(ui->modpackEdit->text()); if (url.isValid() && !url.isRelative() && !url.host().isEmpty()) { return url; } else { return QUrl::fromLocalFile(ui->modpackEdit->text()); } }
8,693
C++
.cpp
205
34.15122
139
0.614703
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,967
TexturePackModel.cpp
PrismLauncher_PrismLauncher/launcher/ui/pages/modplatform/TexturePackModel.cpp
// SPDX-FileCopyrightText: 2023 flowln <flowlnlnln@gmail.com> // // SPDX-License-Identifier: GPL-3.0-only #include "TexturePackModel.h" #include "Application.h" #include "meta/Index.h" #include "meta/Version.h" static std::list<Version> s_availableVersions = {}; namespace ResourceDownload { TexturePackResourceModel::TexturePackResourceModel(BaseInstance const& inst, ResourceAPI* api) : ResourcePackResourceModel(inst, api), m_version_list(APPLICATION->metadataIndex()->get("net.minecraft")) { if (!m_version_list->isLoaded()) { qDebug() << "Loading version list..."; m_task = m_version_list->getLoadTask(); if (!m_task->isRunning()) m_task->start(); } } void waitOnVersionListLoad(Meta::VersionList::Ptr version_list) { QEventLoop load_version_list_loop; QTimer time_limit_for_list_load; time_limit_for_list_load.setTimerType(Qt::TimerType::CoarseTimer); time_limit_for_list_load.setSingleShot(true); time_limit_for_list_load.callOnTimeout(&load_version_list_loop, &QEventLoop::quit); time_limit_for_list_load.start(4000); auto task = version_list->getLoadTask(); QObject::connect(task.get(), &Task::finished, &load_version_list_loop, &QEventLoop::quit); if (!task->isRunning()) task->start(); load_version_list_loop.exec(); if (time_limit_for_list_load.isActive()) time_limit_for_list_load.stop(); } ResourceAPI::SearchArgs TexturePackResourceModel::createSearchArguments() { if (s_availableVersions.empty()) waitOnVersionListLoad(m_version_list); auto args = ResourcePackResourceModel::createSearchArguments(); if (!m_version_list->isLoaded()) { qCritical() << "The version list could not be loaded. Falling back to showing all entries."; return args; } if (s_availableVersions.empty()) { for (auto&& version : m_version_list->versions()) { // FIXME: This duplicates the logic in meta for the 'texturepacks' trait. However, we don't have access to that // information from the index file alone. Also, downloading every version's file isn't a very good idea. if (auto ver = version->toComparableVersion(); ver <= maximumTexturePackVersion()) s_availableVersions.push_back(ver); } } Q_ASSERT(!s_availableVersions.empty()); args.versions = s_availableVersions; return args; } ResourceAPI::VersionSearchArgs TexturePackResourceModel::createVersionsArguments(QModelIndex& entry) { auto args = ResourcePackResourceModel::createVersionsArguments(entry); if (!m_version_list->isLoaded()) { qCritical() << "The version list could not be loaded. Falling back to showing all entries."; return args; } args.mcVersions = s_availableVersions; return args; } } // namespace ResourceDownload
2,879
C++
.cpp
67
37.641791
123
0.703293
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,968
ResourcePackModel.cpp
PrismLauncher_PrismLauncher/launcher/ui/pages/modplatform/ResourcePackModel.cpp
// SPDX-FileCopyrightText: 2023 flowln <flowlnlnln@gmail.com> // // SPDX-License-Identifier: GPL-3.0-only #include "ResourcePackModel.h" #include <QMessageBox> namespace ResourceDownload { ResourcePackResourceModel::ResourcePackResourceModel(BaseInstance const& base_inst, ResourceAPI* api) : ResourceModel(api), m_base_instance(base_inst) {} /******** Make data requests ********/ ResourceAPI::SearchArgs ResourcePackResourceModel::createSearchArguments() { auto sort = getCurrentSortingMethodByIndex(); return { ModPlatform::ResourceType::RESOURCE_PACK, m_next_search_offset, m_search_term, sort }; } ResourceAPI::VersionSearchArgs ResourcePackResourceModel::createVersionsArguments(QModelIndex& entry) { auto& pack = m_packs[entry.row()]; return { *pack }; } ResourceAPI::ProjectInfoArgs ResourcePackResourceModel::createInfoArguments(QModelIndex& entry) { auto& pack = m_packs[entry.row()]; return { *pack }; } void ResourcePackResourceModel::searchWithTerm(const QString& term, unsigned int sort) { if (m_search_term == term && m_search_term.isNull() == term.isNull() && m_current_sort_index == sort) { return; } setSearchTerm(term); m_current_sort_index = sort; refresh(); } } // namespace ResourceDownload
1,282
C++
.cpp
35
33.685714
107
0.748178
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,969
ModModel.cpp
PrismLauncher_PrismLauncher/launcher/ui/pages/modplatform/ModModel.cpp
// SPDX-FileCopyrightText: 2023 flowln <flowlnlnln@gmail.com> // // SPDX-License-Identifier: GPL-3.0-only #include "ModModel.h" #include "minecraft/MinecraftInstance.h" #include "minecraft/PackProfile.h" #include "minecraft/mod/ModFolderModel.h" #include <QMessageBox> #include <algorithm> namespace ResourceDownload { ModModel::ModModel(BaseInstance& base_inst, ResourceAPI* api) : ResourceModel(api), m_base_instance(base_inst) {} /******** Make data requests ********/ ResourceAPI::SearchArgs ModModel::createSearchArguments() { auto profile = static_cast<MinecraftInstance const&>(m_base_instance).getPackProfile(); Q_ASSERT(profile); Q_ASSERT(m_filter); std::optional<std::list<Version>> versions{}; std::optional<QStringList> categories{}; auto loaders = profile->getSupportedModLoaders(); // Version filter if (!m_filter->versions.empty()) versions = m_filter->versions; if (m_filter->loaders) loaders = m_filter->loaders; if (!m_filter->categoryIds.empty()) categories = m_filter->categoryIds; auto side = m_filter->side; auto sort = getCurrentSortingMethodByIndex(); return { ModPlatform::ResourceType::MOD, m_next_search_offset, m_search_term, sort, loaders, versions, side, categories, m_filter->openSource }; } ResourceAPI::VersionSearchArgs ModModel::createVersionsArguments(QModelIndex& entry) { auto& pack = *m_packs[entry.row()]; auto profile = static_cast<MinecraftInstance const&>(m_base_instance).getPackProfile(); Q_ASSERT(profile); Q_ASSERT(m_filter); std::optional<std::list<Version>> versions{}; auto loaders = profile->getSupportedModLoaders(); if (!m_filter->versions.empty()) versions = m_filter->versions; if (m_filter->loaders) loaders = m_filter->loaders; return { pack, versions, loaders }; } ResourceAPI::ProjectInfoArgs ModModel::createInfoArguments(QModelIndex& entry) { auto& pack = *m_packs[entry.row()]; return { pack }; } void ModModel::searchWithTerm(const QString& term, unsigned int sort, bool filter_changed) { if (m_search_term == term && m_search_term.isNull() == term.isNull() && m_current_sort_index == sort && !filter_changed) { return; } setSearchTerm(term); m_current_sort_index = sort; refresh(); } bool ModModel::isPackInstalled(ModPlatform::IndexedPack::Ptr pack) const { auto allMods = static_cast<MinecraftInstance&>(m_base_instance).loaderModList()->allMods(); return std::any_of(allMods.cbegin(), allMods.cend(), [pack](Mod* mod) { if (auto meta = mod->metadata(); meta) return meta->provider == pack->provider && meta->project_id == pack->addonId; return false; }); } QVariant ModModel::getInstalledPackVersion(ModPlatform::IndexedPack::Ptr pack) const { auto allMods = static_cast<MinecraftInstance&>(m_base_instance).loaderModList()->allMods(); for (auto mod : allMods) { if (auto meta = mod->metadata(); meta && meta->provider == pack->provider && meta->project_id == pack->addonId) { return meta->version(); } } return {}; } bool checkSide(QString filter, QString value) { return filter.isEmpty() || value.isEmpty() || filter == "both" || value == "both" || filter == value; } bool ModModel::checkFilters(ModPlatform::IndexedPack::Ptr pack) { if (!m_filter) return true; return !(m_filter->hideInstalled && isPackInstalled(pack)) && checkSide(m_filter->side, pack->side); } bool ModModel::checkVersionFilters(const ModPlatform::IndexedVersion& v) { if (!m_filter) return true; auto loaders = static_cast<MinecraftInstance&>(m_base_instance).getPackProfile()->getSupportedModLoaders(); if (m_filter->loaders) loaders = m_filter->loaders; return (!optedOut(v) && // is opted out(aka curseforge download link) (!loaders.has_value() || !v.loaders || loaders.value() & v.loaders) && // loaders checkSide(m_filter->side, v.side) && // side (m_filter->releases.empty() || // releases std::find(m_filter->releases.cbegin(), m_filter->releases.cend(), v.version_type) != m_filter->releases.cend()) && m_filter->checkMcVersions(v.mcVersion)); // mcVersions } } // namespace ResourceDownload
4,475
C++
.cpp
105
37.819048
140
0.662523
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,970
ModPage.cpp
PrismLauncher_PrismLauncher/launcher/ui/pages/modplatform/ModPage.cpp
// SPDX-FileCopyrightText: 2023 flowln <flowlnlnln@gmail.com> // // SPDX-License-Identifier: GPL-3.0-only AND Apache-2.0 /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * Copyright (C) 2022 TheKodeToad <TheKodeToad@proton.me> * Copyright (c) 2023 Trial97 <alexandru.tripon97@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 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 "ModPage.h" #include "ui_ResourcePage.h" #include <QDesktopServices> #include <QKeyEvent> #include <QRegularExpression> #include <memory> #include "Application.h" #include "ResourceDownloadTask.h" #include "minecraft/MinecraftInstance.h" #include "minecraft/PackProfile.h" #include "ui/dialogs/ResourceDownloadDialog.h" namespace ResourceDownload { ModPage::ModPage(ModDownloadDialog* dialog, BaseInstance& instance) : ResourcePage(dialog, instance) { connect(m_ui->resourceFilterButton, &QPushButton::clicked, this, &ModPage::filterMods); connect(m_ui->packView, &QListView::doubleClicked, this, &ModPage::onResourceSelected); } void ModPage::setFilterWidget(unique_qobject_ptr<ModFilterWidget>& widget) { if (m_filter_widget) disconnect(m_filter_widget.get(), nullptr, nullptr, nullptr); auto old = m_ui->splitter->replaceWidget(0, widget.get()); // because we replaced the widget we also need to delete it if (old) { delete old; } m_filter_widget.swap(widget); m_filter = m_filter_widget->getFilter(); connect(m_filter_widget.get(), &ModFilterWidget::filterChanged, this, &ModPage::triggerSearch); prepareProviderCategories(); } /******** Callbacks to events in the UI (set up in the derived classes) ********/ void ModPage::filterMods() { m_filter_widget->setHidden(!m_filter_widget->isHidden()); } void ModPage::triggerSearch() { auto changed = m_filter_widget->changed(); m_filter = m_filter_widget->getFilter(); m_ui->packView->selectionModel()->setCurrentIndex({}, QItemSelectionModel::SelectionFlag::ClearAndSelect); m_ui->packView->clearSelection(); m_ui->packDescription->clear(); m_ui->versionSelectionBox->clear(); updateSelectionButton(); static_cast<ModModel*>(m_model)->searchWithTerm(getSearchTerm(), m_ui->sortByBox->currentData().toUInt(), changed); m_fetchProgress.watch(m_model->activeSearchJob().get()); } QMap<QString, QString> ModPage::urlHandlers() const { QMap<QString, QString> map; map.insert(QRegularExpression::anchoredPattern("(?:www\\.)?modrinth\\.com\\/mod\\/([^\\/]+)\\/?"), "modrinth"); map.insert(QRegularExpression::anchoredPattern("(?:www\\.)?curseforge\\.com\\/minecraft\\/mc-mods\\/([^\\/]+)\\/?"), "curseforge"); map.insert(QRegularExpression::anchoredPattern("minecraft\\.curseforge\\.com\\/projects\\/([^\\/]+)\\/?"), "curseforge"); return map; } /******** Make changes to the UI ********/ void ModPage::addResourceToPage(ModPlatform::IndexedPack::Ptr pack, ModPlatform::IndexedVersion& version, const std::shared_ptr<ResourceFolderModel> base_model) { bool is_indexed = !APPLICATION->settings()->get("ModMetadataDisabled").toBool(); m_model->addPack(pack, version, base_model, is_indexed); } } // namespace ResourceDownload
4,585
C++
.cpp
103
41.116505
135
0.716207
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,971
ResourcePage.cpp
PrismLauncher_PrismLauncher/launcher/ui/pages/modplatform/ResourcePage.cpp
// SPDX-FileCopyrightText: 2023 flowln <flowlnlnln@gmail.com> // // SPDX-License-Identifier: GPL-3.0-only AND Apache-2.0 /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * Copyright (C) 2023 TheKodeToad <TheKodeToad@proton.me> * Copyright (c) 2023 Trial97 <alexandru.tripon97@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 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 "ResourcePage.h" #include "modplatform/ModIndex.h" #include "ui/dialogs/CustomMessageBox.h" #include "ui_ResourcePage.h" #include <StringUtils.h> #include <QDesktopServices> #include <QKeyEvent> #include "Markdown.h" #include "Application.h" #include "ui/dialogs/ResourceDownloadDialog.h" #include "ui/pages/modplatform/ResourceModel.h" #include "ui/widgets/ProjectItem.h" namespace ResourceDownload { ResourcePage::ResourcePage(ResourceDownloadDialog* parent, BaseInstance& base_instance) : QWidget(parent), m_baseInstance(base_instance), m_ui(new Ui::ResourcePage), m_parentDialog(parent), m_fetchProgress(this, false) { m_ui->setupUi(this); m_ui->searchEdit->installEventFilter(this); m_ui->versionSelectionBox->view()->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); m_ui->versionSelectionBox->view()->parentWidget()->setMaximumHeight(300); m_searchTimer.setTimerType(Qt::TimerType::CoarseTimer); m_searchTimer.setSingleShot(true); connect(&m_searchTimer, &QTimer::timeout, this, &ResourcePage::triggerSearch); // hide progress bar to prevent weird artifact m_fetchProgress.hide(); m_fetchProgress.hideIfInactive(true); m_fetchProgress.setFixedHeight(24); m_fetchProgress.progressFormat(""); m_ui->verticalLayout->insertWidget(1, &m_fetchProgress); m_ui->packView->setItemDelegate(new ProjectItemDelegate(this)); m_ui->packView->installEventFilter(this); connect(m_ui->packDescription, &QTextBrowser::anchorClicked, this, &ResourcePage::openUrl); } ResourcePage::~ResourcePage() { delete m_ui; if (m_model) delete m_model; } void ResourcePage::retranslate() { m_ui->retranslateUi(this); } void ResourcePage::openedImpl() { if (!supportsFiltering()) { m_ui->resourceFilterButton->setVisible(false); m_ui->filterWidget->hide(); } //: String in the search bar of the mod downloading dialog m_ui->searchEdit->setPlaceholderText(tr("Search for %1...").arg(resourcesString())); m_ui->resourceSelectionButton->setText(tr("Select %1 for download").arg(resourceString())); updateSelectionButton(); triggerSearch(); m_ui->searchEdit->setFocus(); } auto ResourcePage::eventFilter(QObject* watched, QEvent* event) -> bool { if (event->type() == QEvent::KeyPress) { auto* keyEvent = static_cast<QKeyEvent*>(event); if (watched == m_ui->searchEdit) { if (keyEvent->key() == Qt::Key_Return) { triggerSearch(); keyEvent->accept(); return true; } else { if (m_searchTimer.isActive()) m_searchTimer.stop(); m_searchTimer.start(350); } } else if (watched == m_ui->packView) { if (keyEvent->key() == Qt::Key_Return) { onResourceSelected(); // To have the 'select mod' button outlined instead of the 'review and confirm' one m_ui->resourceSelectionButton->setFocus(Qt::FocusReason::ShortcutFocusReason); m_ui->packView->setFocus(Qt::FocusReason::NoFocusReason); keyEvent->accept(); return true; } } } return QWidget::eventFilter(watched, event); } QString ResourcePage::getSearchTerm() const { return m_ui->searchEdit->text(); } void ResourcePage::setSearchTerm(QString term) { m_ui->searchEdit->setText(term); } void ResourcePage::addSortings() { Q_ASSERT(m_model); auto sorts = m_model->getSortingMethods(); std::sort(sorts.begin(), sorts.end(), [](auto const& l, auto const& r) { return l.index < r.index; }); for (auto&& sorting : sorts) m_ui->sortByBox->addItem(sorting.readable_name, QVariant(sorting.index)); } bool ResourcePage::setCurrentPack(ModPlatform::IndexedPack::Ptr pack) { QVariant v; v.setValue(pack); return m_model->setData(m_ui->packView->currentIndex(), v, Qt::UserRole); } ModPlatform::IndexedPack::Ptr ResourcePage::getCurrentPack() const { return m_model->data(m_ui->packView->currentIndex(), Qt::UserRole).value<ModPlatform::IndexedPack::Ptr>(); } void ResourcePage::updateUi() { auto current_pack = getCurrentPack(); if (!current_pack) { m_ui->packDescription->setHtml({}); m_ui->packDescription->flush(); return; } QString text = ""; QString name = current_pack->name; if (current_pack->websiteUrl.isEmpty()) text = name; else text = "<a href=\"" + current_pack->websiteUrl + "\">" + name + "</a>"; if (!current_pack->authors.empty()) { auto authorToStr = [](ModPlatform::ModpackAuthor& author) -> QString { if (author.url.isEmpty()) { return author.name; } return QString("<a href=\"%1\">%2</a>").arg(author.url, author.name); }; QStringList authorStrs; for (auto& author : current_pack->authors) { authorStrs.push_back(authorToStr(author)); } text += "<br>" + tr(" by ") + authorStrs.join(", "); } if (current_pack->extraDataLoaded) { if (current_pack->extraData.status == "archived") { text += "<br><br>" + tr("<b>This project has been archived. It will not receive any further updates unless the author decides " "to unarchive the project.</b>"); } if (!current_pack->extraData.donate.isEmpty()) { text += "<br><br>" + tr("Donate information: "); auto donateToStr = [](ModPlatform::DonationData& donate) -> QString { return QString("<a href=\"%1\">%2</a>").arg(donate.url, donate.platform); }; QStringList donates; for (auto& donate : current_pack->extraData.donate) { donates.append(donateToStr(donate)); } text += donates.join(", "); } if (!current_pack->extraData.issuesUrl.isEmpty() || !current_pack->extraData.sourceUrl.isEmpty() || !current_pack->extraData.wikiUrl.isEmpty() || !current_pack->extraData.discordUrl.isEmpty()) { text += "<br><br>" + tr("External links:") + "<br>"; } if (!current_pack->extraData.issuesUrl.isEmpty()) text += "- " + tr("Issues: <a href=%1>%1</a>").arg(current_pack->extraData.issuesUrl) + "<br>"; if (!current_pack->extraData.wikiUrl.isEmpty()) text += "- " + tr("Wiki: <a href=%1>%1</a>").arg(current_pack->extraData.wikiUrl) + "<br>"; if (!current_pack->extraData.sourceUrl.isEmpty()) text += "- " + tr("Source code: <a href=%1>%1</a>").arg(current_pack->extraData.sourceUrl) + "<br>"; if (!current_pack->extraData.discordUrl.isEmpty()) text += "- " + tr("Discord: <a href=%1>%1</a>").arg(current_pack->extraData.discordUrl) + "<br>"; } text += "<hr>"; m_ui->packDescription->setHtml(StringUtils::htmlListPatch( text + (current_pack->extraData.body.isEmpty() ? current_pack->description : markdownToHTML(current_pack->extraData.body)))); m_ui->packDescription->flush(); } void ResourcePage::updateSelectionButton() { if (!isOpened || m_selectedVersionIndex < 0) { m_ui->resourceSelectionButton->setEnabled(false); return; } m_ui->resourceSelectionButton->setEnabled(true); if (auto current_pack = getCurrentPack(); current_pack) { if (current_pack->versionsLoaded && current_pack->versions.empty()) { m_ui->resourceSelectionButton->setEnabled(false); qWarning() << tr("No version available for the selected pack"); } else if (!current_pack->isVersionSelected(m_selectedVersionIndex)) m_ui->resourceSelectionButton->setText(tr("Select %1 for download").arg(resourceString())); else m_ui->resourceSelectionButton->setText(tr("Deselect %1 for download").arg(resourceString())); } else { qWarning() << "Tried to update the selected button but there is not a pack selected"; } } void ResourcePage::updateVersionList() { auto current_pack = getCurrentPack(); m_ui->versionSelectionBox->blockSignals(true); m_ui->versionSelectionBox->clear(); m_ui->versionSelectionBox->blockSignals(false); if (current_pack) { auto installedVersion = m_model->getInstalledPackVersion(current_pack); for (int i = 0; i < current_pack->versions.size(); i++) { auto& version = current_pack->versions[i]; if (!m_model->checkVersionFilters(version)) continue; auto versionText = version.version; if (version.version_type.isValid()) { versionText += QString(" [%1]").arg(version.version_type.toString()); } if (version.fileId == installedVersion) { versionText += tr(" [installed]", "Mod version select"); } m_ui->versionSelectionBox->addItem(versionText, QVariant(i)); } } if (m_ui->versionSelectionBox->count() == 0) { m_ui->versionSelectionBox->addItem(tr("No valid version found."), QVariant(-1)); m_ui->resourceSelectionButton->setText(tr("Cannot select invalid version :(")); } updateSelectionButton(); } void ResourcePage::onSelectionChanged(QModelIndex curr, [[maybe_unused]] QModelIndex prev) { if (!curr.isValid()) { return; } auto current_pack = getCurrentPack(); bool request_load = false; if (!current_pack || !current_pack->versionsLoaded) { m_ui->resourceSelectionButton->setText(tr("Loading versions...")); m_ui->resourceSelectionButton->setEnabled(false); request_load = true; } else { updateVersionList(); } if (current_pack && !current_pack->extraDataLoaded) request_load = true; if (request_load) m_model->loadEntry(curr); updateUi(); } void ResourcePage::onVersionSelectionChanged(int index) { m_selectedVersionIndex = m_ui->versionSelectionBox->itemData(index).toInt(); updateSelectionButton(); } void ResourcePage::addResourceToDialog(ModPlatform::IndexedPack::Ptr pack, ModPlatform::IndexedVersion& version) { m_parentDialog->addResource(pack, version); } void ResourcePage::removeResourceFromDialog(const QString& pack_name) { m_parentDialog->removeResource(pack_name); } void ResourcePage::addResourceToPage(ModPlatform::IndexedPack::Ptr pack, ModPlatform::IndexedVersion& ver, const std::shared_ptr<ResourceFolderModel> base_model) { bool is_indexed = !APPLICATION->settings()->get("ModMetadataDisabled").toBool(); m_model->addPack(pack, ver, base_model, is_indexed); } void ResourcePage::removeResourceFromPage(const QString& name) { m_model->removePack(name); } void ResourcePage::onResourceSelected() { if (m_selectedVersionIndex < 0) return; auto current_pack = getCurrentPack(); if (!current_pack || !current_pack->versionsLoaded || current_pack->versions.size() < m_selectedVersionIndex) return; auto& version = current_pack->versions[m_selectedVersionIndex]; Q_ASSERT(!version.downloadUrl.isNull()); if (version.is_currently_selected) removeResourceFromDialog(current_pack->name); else addResourceToDialog(current_pack, version); // Save the modified pack (and prevent warning in release build) [[maybe_unused]] bool set = setCurrentPack(current_pack); Q_ASSERT(set); updateSelectionButton(); /* Force redraw on the resource list when the selection changes */ m_ui->packView->repaint(); } void ResourcePage::openUrl(const QUrl& url) { // do not allow other url schemes for security reasons if (!(url.scheme() == "http" || url.scheme() == "https")) { qWarning() << "Unsupported scheme" << url.scheme(); return; } // detect URLs and search instead const QString address = url.host() + url.path(); QRegularExpressionMatch match; QString page; auto handlers = urlHandlers(); for (auto it = handlers.constKeyValueBegin(); it != handlers.constKeyValueEnd(); it++) { auto&& [regex, candidate] = *it; if (match = QRegularExpression(regex).match(address); match.hasMatch()) { page = candidate; break; } } if (!page.isNull() && !m_doNotJumpToMod) { const QString slug = match.captured(1); // ensure the user isn't opening the same mod if (auto current_pack = getCurrentPack(); current_pack && slug != current_pack->slug) { m_parentDialog->selectPage(page); auto newPage = m_parentDialog->selectedPage(); QLineEdit* searchEdit = newPage->m_ui->searchEdit; auto model = newPage->m_model; QListView* view = newPage->m_ui->packView; auto jump = [url, slug, model, view] { for (int row = 0; row < model->rowCount({}); row++) { const QModelIndex index = model->index(row); const auto pack = model->data(index, Qt::UserRole).value<ModPlatform::IndexedPack::Ptr>(); if (pack->slug == slug) { view->setCurrentIndex(index); return; } } // The final fallback. QDesktopServices::openUrl(url); }; searchEdit->setText(slug); newPage->triggerSearch(); if (model->hasActiveSearchJob()) connect(model->activeSearchJob().get(), &Task::finished, jump); else jump(); return; } } // open in the user's web browser QDesktopServices::openUrl(url); } void ResourcePage::openProject(QVariant projectID) { m_ui->sortByBox->hide(); m_ui->searchEdit->hide(); m_ui->resourceFilterButton->hide(); m_ui->packView->hide(); m_ui->resourceSelectionButton->hide(); m_doNotJumpToMod = true; auto buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, this); auto okBtn = buttonBox->button(QDialogButtonBox::Ok); okBtn->setDefault(true); okBtn->setAutoDefault(true); okBtn->setText(tr("Reinstall")); okBtn->setShortcut(tr("Ctrl+Return")); okBtn->setEnabled(false); auto cancelBtn = buttonBox->button(QDialogButtonBox::Cancel); cancelBtn->setDefault(false); cancelBtn->setAutoDefault(false); cancelBtn->setText(tr("Cancel")); connect(okBtn, &QPushButton::clicked, this, [this] { onResourceSelected(); m_parentDialog->accept(); }); connect(cancelBtn, &QPushButton::clicked, m_parentDialog, &ResourceDownloadDialog::reject); m_ui->gridLayout_4->addWidget(buttonBox, 1, 2); connect(m_ui->versionSelectionBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [this, okBtn](int index) { okBtn->setEnabled(m_ui->versionSelectionBox->itemData(index).toInt() >= 0); }); auto jump = [this] { for (int row = 0; row < m_model->rowCount({}); row++) { const QModelIndex index = m_model->index(row); m_ui->packView->setCurrentIndex(index); return; } m_ui->packDescription->setText(tr("The resource was not found")); }; m_ui->searchEdit->setText("#" + projectID.toString()); triggerSearch(); if (m_model->hasActiveSearchJob()) connect(m_model->activeSearchJob().get(), &Task::finished, jump); else jump(); } } // namespace ResourceDownload
17,445
C++
.cpp
414
35.099034
139
0.645138
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,972
ShaderPackModel.cpp
PrismLauncher_PrismLauncher/launcher/ui/pages/modplatform/ShaderPackModel.cpp
// SPDX-FileCopyrightText: 2023 flowln <flowlnlnln@gmail.com> // // SPDX-License-Identifier: GPL-3.0-only #include "ShaderPackModel.h" #include <QMessageBox> namespace ResourceDownload { ShaderPackResourceModel::ShaderPackResourceModel(BaseInstance const& base_inst, ResourceAPI* api) : ResourceModel(api), m_base_instance(base_inst) {} /******** Make data requests ********/ ResourceAPI::SearchArgs ShaderPackResourceModel::createSearchArguments() { auto sort = getCurrentSortingMethodByIndex(); return { ModPlatform::ResourceType::SHADER_PACK, m_next_search_offset, m_search_term, sort }; } ResourceAPI::VersionSearchArgs ShaderPackResourceModel::createVersionsArguments(QModelIndex& entry) { auto& pack = m_packs[entry.row()]; return { *pack }; } ResourceAPI::ProjectInfoArgs ShaderPackResourceModel::createInfoArguments(QModelIndex& entry) { auto& pack = m_packs[entry.row()]; return { *pack }; } void ShaderPackResourceModel::searchWithTerm(const QString& term, unsigned int sort) { if (m_search_term == term && m_search_term.isNull() == term.isNull() && m_current_sort_index == sort) { return; } setSearchTerm(term); m_current_sort_index = sort; refresh(); } } // namespace ResourceDownload
1,266
C++
.cpp
35
33.228571
107
0.744873
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,973
ResourceModel.cpp
PrismLauncher_PrismLauncher/launcher/ui/pages/modplatform/ResourceModel.cpp
// SPDX-FileCopyrightText: 2023 flowln <flowlnlnln@gmail.com> // // SPDX-License-Identifier: GPL-3.0-only #include "ResourceModel.h" #include <QCryptographicHash> #include <QIcon> #include <QList> #include <QMessageBox> #include <QPixmapCache> #include <QUrl> #include <algorithm> #include <memory> #include "Application.h" #include "BuildConfig.h" #include "Json.h" #include "net/ApiDownload.h" #include "net/NetJob.h" #include "modplatform/ModIndex.h" #include "ui/widgets/ProjectItem.h" namespace ResourceDownload { QHash<ResourceModel*, bool> ResourceModel::s_running_models; ResourceModel::ResourceModel(ResourceAPI* api) : QAbstractListModel(), m_api(api) { s_running_models.insert(this, true); if (APPLICATION_DYN) { m_current_info_job.setMaxConcurrent(APPLICATION->settings()->get("NumberOfConcurrentDownloads").toInt()); } } ResourceModel::~ResourceModel() { s_running_models.find(this).value() = false; } auto ResourceModel::data(const QModelIndex& index, int role) const -> QVariant { int pos = index.row(); if (pos >= m_packs.size() || pos < 0 || !index.isValid()) { return QString("INVALID INDEX %1").arg(pos); } auto pack = m_packs.at(pos); switch (role) { case Qt::ToolTipRole: { if (pack->description.length() > 100) { // some magic to prevent to long tooltips and replace html linebreaks QString edit = pack->description.left(97); edit = edit.left(edit.lastIndexOf("<br>")).left(edit.lastIndexOf(" ")).append("..."); return edit; } return pack->description; } case Qt::DecorationRole: { if (APPLICATION_DYN) { if (auto icon_or_none = const_cast<ResourceModel*>(this)->getIcon(const_cast<QModelIndex&>(index), pack->logoUrl); icon_or_none.has_value()) return icon_or_none.value(); return APPLICATION->getThemedIcon("screenshot-placeholder"); } else { return {}; } } case Qt::SizeHintRole: return QSize(0, 58); case Qt::UserRole: { QVariant v; v.setValue(pack); return v; } // Custom data case UserDataTypes::TITLE: return pack->name; case UserDataTypes::DESCRIPTION: return pack->description; case UserDataTypes::SELECTED: return pack->isAnyVersionSelected(); case UserDataTypes::INSTALLED: return this->isPackInstalled(pack); default: break; } return {}; } QHash<int, QByteArray> ResourceModel::roleNames() const { QHash<int, QByteArray> roles; roles[Qt::ToolTipRole] = "toolTip"; roles[Qt::DecorationRole] = "decoration"; roles[Qt::SizeHintRole] = "sizeHint"; roles[Qt::UserRole] = "pack"; roles[UserDataTypes::TITLE] = "title"; roles[UserDataTypes::DESCRIPTION] = "description"; roles[UserDataTypes::SELECTED] = "selected"; roles[UserDataTypes::INSTALLED] = "installed"; return roles; } bool ResourceModel::setData(const QModelIndex& index, const QVariant& value, [[maybe_unused]] int role) { int pos = index.row(); if (pos >= m_packs.size() || pos < 0 || !index.isValid()) return false; m_packs[pos] = value.value<ModPlatform::IndexedPack::Ptr>(); emit dataChanged(index, index); return true; } QString ResourceModel::debugName() const { return "ResourceDownload (Model)"; } void ResourceModel::fetchMore(const QModelIndex& parent) { if (parent.isValid() || m_search_state == SearchState::Finished) return; search(); } void ResourceModel::search() { if (hasActiveSearchJob()) return; if (m_search_term.startsWith("#")) { auto projectId = m_search_term.mid(1); if (!projectId.isEmpty()) { ResourceAPI::ProjectInfoCallbacks callbacks; callbacks.on_fail = [this](QString reason) { if (!s_running_models.constFind(this).value()) return; searchRequestFailed(reason, -1); }; callbacks.on_abort = [this] { if (!s_running_models.constFind(this).value()) return; searchRequestAborted(); }; callbacks.on_succeed = [this](auto& doc, auto& pack) { if (!s_running_models.constFind(this).value()) return; searchRequestForOneSucceeded(doc); }; if (auto job = m_api->getProjectInfo({ projectId }, std::move(callbacks)); job) runSearchJob(job); return; } } auto args{ createSearchArguments() }; auto callbacks{ createSearchCallbacks() }; // Use defaults if no callbacks are set if (!callbacks.on_succeed) callbacks.on_succeed = [this](auto& doc) { if (!s_running_models.constFind(this).value()) return; searchRequestSucceeded(doc); }; if (!callbacks.on_fail) callbacks.on_fail = [this](QString reason, int network_error_code) { if (!s_running_models.constFind(this).value()) return; searchRequestFailed(reason, network_error_code); }; if (!callbacks.on_abort) callbacks.on_abort = [this] { if (!s_running_models.constFind(this).value()) return; searchRequestAborted(); }; if (auto job = m_api->searchProjects(std::move(args), std::move(callbacks)); job) runSearchJob(job); } void ResourceModel::loadEntry(QModelIndex& entry) { auto const& pack = m_packs[entry.row()]; if (!hasActiveInfoJob()) m_current_info_job.clear(); if (!pack->versionsLoaded) { auto args{ createVersionsArguments(entry) }; auto callbacks{ createVersionsCallbacks(entry) }; // Use default if no callbacks are set if (!callbacks.on_succeed) callbacks.on_succeed = [this, entry](auto& doc, auto pack) { if (!s_running_models.constFind(this).value()) return; versionRequestSucceeded(doc, pack, entry); }; if (!callbacks.on_fail) callbacks.on_fail = [](QString reason, int) { QMessageBox::critical(nullptr, tr("Error"), tr("A network error occurred. Could not load project versions: %1").arg(reason)); }; if (auto job = m_api->getProjectVersions(std::move(args), std::move(callbacks)); job) runInfoJob(job); } if (!pack->extraDataLoaded) { auto args{ createInfoArguments(entry) }; auto callbacks{ createInfoCallbacks(entry) }; // Use default if no callbacks are set if (!callbacks.on_succeed) callbacks.on_succeed = [this, entry](auto& doc, auto& newpack) { if (!s_running_models.constFind(this).value()) return; auto pack = newpack; infoRequestSucceeded(doc, pack, entry); }; if (!callbacks.on_fail) callbacks.on_fail = [this](QString reason) { if (!s_running_models.constFind(this).value()) return; QMessageBox::critical(nullptr, tr("Error"), tr("A network error occurred. Could not load project info: %1").arg(reason)); }; if (!callbacks.on_abort) callbacks.on_abort = [this] { if (!s_running_models.constFind(this).value()) return; qCritical() << tr("The request was aborted for an unknown reason"); }; if (auto job = m_api->getProjectInfo(std::move(args), std::move(callbacks)); job) runInfoJob(job); } } void ResourceModel::refresh() { bool reset_requested = false; if (hasActiveInfoJob()) { m_current_info_job.abort(); reset_requested = true; } if (hasActiveSearchJob()) { m_current_search_job->abort(); reset_requested = true; } if (reset_requested) { m_search_state = SearchState::ResetRequested; return; } clearData(); m_search_state = SearchState::None; m_next_search_offset = 0; search(); } void ResourceModel::clearData() { beginResetModel(); m_packs.clear(); endResetModel(); } void ResourceModel::runSearchJob(Task::Ptr ptr) { m_current_search_job.reset(ptr); // clean up first m_current_search_job->start(); } void ResourceModel::runInfoJob(Task::Ptr ptr) { if (!m_current_info_job.isRunning()) m_current_info_job.clear(); m_current_info_job.addTask(ptr); if (!m_current_info_job.isRunning()) m_current_info_job.run(); } std::optional<ResourceAPI::SortingMethod> ResourceModel::getCurrentSortingMethodByIndex() const { std::optional<ResourceAPI::SortingMethod> sort{}; { // Find sorting method by ID auto sorting_methods = getSortingMethods(); auto method = std::find_if(sorting_methods.constBegin(), sorting_methods.constEnd(), [this](auto const& e) { return m_current_sort_index == e.index; }); if (method != sorting_methods.constEnd()) sort = *method; } return sort; } std::optional<QIcon> ResourceModel::getIcon(QModelIndex& index, const QUrl& url) { QPixmap pixmap; if (QPixmapCache::find(url.toString(), &pixmap)) return { pixmap }; if (!m_current_icon_job) { m_current_icon_job.reset(new NetJob("IconJob", APPLICATION->network())); m_current_icon_job->setAskRetry(false); } if (m_currently_running_icon_actions.contains(url)) return {}; if (m_failed_icon_actions.contains(url)) return {}; auto cache_entry = APPLICATION->metacache()->resolveEntry( metaEntryBase(), QString("logos/%1").arg(QString(QCryptographicHash::hash(url.toEncoded(), QCryptographicHash::Algorithm::Sha1).toHex()))); auto icon_fetch_action = Net::ApiDownload::makeCached(url, cache_entry); auto full_file_path = cache_entry->getFullPath(); connect(icon_fetch_action.get(), &Task::succeeded, this, [this, url, full_file_path, index] { auto icon = QIcon(full_file_path); QPixmapCache::insert(url.toString(), icon.pixmap(icon.actualSize({ 64, 64 }))); m_currently_running_icon_actions.remove(url); emit dataChanged(index, index, { Qt::DecorationRole }); }); connect(icon_fetch_action.get(), &Task::failed, this, [this, url] { m_currently_running_icon_actions.remove(url); m_failed_icon_actions.insert(url); }); m_currently_running_icon_actions.insert(url); m_current_icon_job->addNetAction(icon_fetch_action); if (!m_current_icon_job->isRunning()) QMetaObject::invokeMethod(m_current_icon_job.get(), &NetJob::start); return {}; } // No 'forgor to implement' shall pass here :blobfox_knife: #define NEED_FOR_CALLBACK_ASSERT(name) \ Q_ASSERT_X(0 != 0, #name, "You NEED to re-implement this if you intend on using the default callbacks.") QJsonArray ResourceModel::documentToArray([[maybe_unused]] QJsonDocument& doc) const { NEED_FOR_CALLBACK_ASSERT("documentToArray"); return {}; } void ResourceModel::loadIndexedPack(ModPlatform::IndexedPack&, QJsonObject&) { NEED_FOR_CALLBACK_ASSERT("loadIndexedPack"); } void ResourceModel::loadExtraPackInfo(ModPlatform::IndexedPack&, QJsonObject&) { NEED_FOR_CALLBACK_ASSERT("loadExtraPackInfo"); } void ResourceModel::loadIndexedPackVersions(ModPlatform::IndexedPack&, QJsonArray&) { NEED_FOR_CALLBACK_ASSERT("loadIndexedPackVersions"); } /* Default callbacks */ void ResourceModel::searchRequestSucceeded(QJsonDocument& doc) { QList<ModPlatform::IndexedPack::Ptr> newList; auto packs = documentToArray(doc); for (auto packRaw : packs) { auto packObj = packRaw.toObject(); ModPlatform::IndexedPack::Ptr pack = std::make_shared<ModPlatform::IndexedPack>(); try { loadIndexedPack(*pack, packObj); if (auto sel = std::find_if(m_selected.begin(), m_selected.end(), [&pack](const DownloadTaskPtr i) { const auto ipack = i->getPack(); return ipack->provider == pack->provider && ipack->addonId == pack->addonId; }); sel != m_selected.end()) { newList.append(sel->get()->getPack()); } else newList.append(pack); } catch (const JSONValidationError& e) { qWarning() << "Error while loading resource from " << debugName() << ": " << e.cause(); continue; } } if (packs.size() < 25) { m_search_state = SearchState::Finished; } else { m_next_search_offset += 25; m_search_state = SearchState::CanFetchMore; } QList<ModPlatform::IndexedPack::Ptr> filteredNewList; for (auto p : newList) if (checkFilters(p)) filteredNewList << p; // When you have a Qt build with assertions turned on, proceeding here will abort the application if (filteredNewList.size() == 0) return; beginInsertRows(QModelIndex(), m_packs.size(), m_packs.size() + filteredNewList.size() - 1); m_packs.append(filteredNewList); endInsertRows(); } void ResourceModel::searchRequestForOneSucceeded(QJsonDocument& doc) { ModPlatform::IndexedPack::Ptr pack = std::make_shared<ModPlatform::IndexedPack>(); try { auto obj = Json::requireObject(doc); if (obj.contains("data")) obj = Json::requireObject(obj, "data"); loadIndexedPack(*pack, obj); } catch (const JSONValidationError& e) { qDebug() << doc; qWarning() << "Error while reading " << debugName() << " resource info: " << e.cause(); } m_search_state = SearchState::Finished; beginInsertRows(QModelIndex(), m_packs.size(), m_packs.size() + 1); m_packs.append(pack); endInsertRows(); } void ResourceModel::searchRequestFailed([[maybe_unused]] QString reason, int network_error_code) { switch (network_error_code) { default: // Network error QMessageBox::critical(nullptr, tr("Error"), tr("A network error occurred. Could not load mods.")); break; case 409: // 409 Gone, notify user to update QMessageBox::critical(nullptr, tr("Error"), QString("%1").arg(tr("API version too old!\nPlease update %1!").arg(BuildConfig.LAUNCHER_DISPLAYNAME))); break; } m_search_state = SearchState::Finished; } void ResourceModel::searchRequestAborted() { if (m_search_state != SearchState::ResetRequested) qCritical() << "Search task in" << debugName() << "aborted by an unknown reason!"; // Retry fetching clearData(); m_next_search_offset = 0; search(); } void ResourceModel::versionRequestSucceeded(QJsonDocument& doc, ModPlatform::IndexedPack& pack, const QModelIndex& index) { auto current_pack = data(index, Qt::UserRole).value<ModPlatform::IndexedPack::Ptr>(); // Check if the index is still valid for this resource or not if (pack.addonId != current_pack->addonId) return; try { auto arr = doc.isObject() ? Json::ensureArray(doc.object(), "data") : doc.array(); loadIndexedPackVersions(*current_pack, arr); } catch (const JSONValidationError& e) { qDebug() << doc; qWarning() << "Error while reading " << debugName() << " resource version: " << e.cause(); } // Cache info :^) QVariant new_pack; new_pack.setValue(current_pack); if (!setData(index, new_pack, Qt::UserRole)) { qWarning() << "Failed to cache resource versions!"; return; } emit versionListUpdated(); } void ResourceModel::infoRequestSucceeded(QJsonDocument& doc, ModPlatform::IndexedPack& pack, const QModelIndex& index) { auto current_pack = data(index, Qt::UserRole).value<ModPlatform::IndexedPack::Ptr>(); // Check if the index is still valid for this resource or not if (pack.addonId != current_pack->addonId) return; try { auto obj = Json::requireObject(doc); loadExtraPackInfo(*current_pack, obj); } catch (const JSONValidationError& e) { qDebug() << doc; qWarning() << "Error while reading " << debugName() << " resource info: " << e.cause(); } // Cache info :^) QVariant new_pack; new_pack.setValue(current_pack); if (!setData(index, new_pack, Qt::UserRole)) { qWarning() << "Failed to cache resource info!"; return; } emit projectInfoUpdated(); } void ResourceModel::addPack(ModPlatform::IndexedPack::Ptr pack, ModPlatform::IndexedVersion& version, const std::shared_ptr<ResourceFolderModel> packs, bool is_indexed, QString custom_target_folder) { version.is_currently_selected = true; m_selected.append(makeShared<ResourceDownloadTask>(pack, version, packs, is_indexed, custom_target_folder)); } void ResourceModel::removePack(const QString& rem) { auto pred = [&rem](const DownloadTaskPtr i) { return rem == i->getName(); }; #if QT_VERSION >= QT_VERSION_CHECK(6, 1, 0) m_selected.removeIf(pred); #else { for (auto it = m_selected.begin(); it != m_selected.end();) if (pred(*it)) it = m_selected.erase(it); else ++it; } #endif auto pack = std::find_if(m_packs.begin(), m_packs.end(), [&rem](const ModPlatform::IndexedPack::Ptr i) { return rem == i->name; }); if (pack == m_packs.end()) { // ignore it if is not in the current search return; } if (!pack->get()->versionsLoaded) { return; } for (auto& ver : pack->get()->versions) ver.is_currently_selected = false; } bool ResourceModel::checkVersionFilters(const ModPlatform::IndexedVersion& v) { return (!optedOut(v)); } } // namespace ResourceDownload
18,502
C++
.cpp
483
30.416149
138
0.616256
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,974
ResourcePackPage.cpp
PrismLauncher_PrismLauncher/launcher/ui/pages/modplatform/ResourcePackPage.cpp
// SPDX-FileCopyrightText: 2023 flowln <flowlnlnln@gmail.com> // // SPDX-License-Identifier: GPL-3.0-only #include "ResourcePackPage.h" #include "ui_ResourcePage.h" #include "ResourcePackModel.h" #include "ui/dialogs/ResourceDownloadDialog.h" #include <QRegularExpression> namespace ResourceDownload { ResourcePackResourcePage::ResourcePackResourcePage(ResourceDownloadDialog* dialog, BaseInstance& instance) : ResourcePage(dialog, instance) { connect(m_ui->packView, &QListView::doubleClicked, this, &ResourcePackResourcePage::onResourceSelected); } /******** Callbacks to events in the UI (set up in the derived classes) ********/ void ResourcePackResourcePage::triggerSearch() { m_ui->packView->selectionModel()->setCurrentIndex({}, QItemSelectionModel::SelectionFlag::ClearAndSelect); m_ui->packView->clearSelection(); m_ui->packDescription->clear(); m_ui->versionSelectionBox->clear(); updateSelectionButton(); static_cast<ResourcePackResourceModel*>(m_model)->searchWithTerm(getSearchTerm(), m_ui->sortByBox->currentData().toUInt()); m_fetchProgress.watch(m_model->activeSearchJob().get()); } QMap<QString, QString> ResourcePackResourcePage::urlHandlers() const { QMap<QString, QString> map; map.insert(QRegularExpression::anchoredPattern("(?:www\\.)?modrinth\\.com\\/resourcepack\\/([^\\/]+)\\/?"), "modrinth"); map.insert(QRegularExpression::anchoredPattern("(?:www\\.)?curseforge\\.com\\/minecraft\\/texture-packs\\/([^\\/]+)\\/?"), "curseforge"); map.insert(QRegularExpression::anchoredPattern("minecraft\\.curseforge\\.com\\/projects\\/([^\\/]+)\\/?"), "curseforge"); return map; } } // namespace ResourceDownload
1,705
C++
.cpp
34
46.823529
139
0.734177
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,975
ModrinthResourcePages.cpp
PrismLauncher_PrismLauncher/launcher/ui/pages/modplatform/modrinth/ModrinthResourcePages.cpp
// SPDX-FileCopyrightText: 2023 flowln <flowlnlnln@gmail.com> // // SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * Copyright (c) 2023 Trial97 <alexandru.tripon97@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 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 "ModrinthResourcePages.h" #include "ui_ResourcePage.h" #include "modplatform/modrinth/ModrinthAPI.h" #include "ui/dialogs/ResourceDownloadDialog.h" #include "ui/pages/modplatform/modrinth/ModrinthResourceModels.h" namespace ResourceDownload { ModrinthModPage::ModrinthModPage(ModDownloadDialog* dialog, BaseInstance& instance) : ModPage(dialog, instance) { m_model = new ModrinthModModel(instance); m_ui->packView->setModel(m_model); addSortings(); // sometimes Qt just ignores virtual slots and doesn't work as intended it seems, // so it's best not to connect them in the parent's constructor... connect(m_ui->sortByBox, SIGNAL(currentIndexChanged(int)), this, SLOT(triggerSearch())); connect(m_ui->packView->selectionModel(), &QItemSelectionModel::currentChanged, this, &ModrinthModPage::onSelectionChanged); connect(m_ui->versionSelectionBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &ModrinthModPage::onVersionSelectionChanged); connect(m_ui->resourceSelectionButton, &QPushButton::clicked, this, &ModrinthModPage::onResourceSelected); m_ui->packDescription->setMetaEntry(metaEntryBase()); } ModrinthResourcePackPage::ModrinthResourcePackPage(ResourcePackDownloadDialog* dialog, BaseInstance& instance) : ResourcePackResourcePage(dialog, instance) { m_model = new ModrinthResourcePackModel(instance); m_ui->packView->setModel(m_model); addSortings(); // sometimes Qt just ignores virtual slots and doesn't work as intended it seems, // so it's best not to connect them in the parent's constructor... connect(m_ui->sortByBox, SIGNAL(currentIndexChanged(int)), this, SLOT(triggerSearch())); connect(m_ui->packView->selectionModel(), &QItemSelectionModel::currentChanged, this, &ModrinthResourcePackPage::onSelectionChanged); connect(m_ui->versionSelectionBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &ModrinthResourcePackPage::onVersionSelectionChanged); connect(m_ui->resourceSelectionButton, &QPushButton::clicked, this, &ModrinthResourcePackPage::onResourceSelected); m_ui->packDescription->setMetaEntry(metaEntryBase()); } ModrinthTexturePackPage::ModrinthTexturePackPage(TexturePackDownloadDialog* dialog, BaseInstance& instance) : TexturePackResourcePage(dialog, instance) { m_model = new ModrinthTexturePackModel(instance); m_ui->packView->setModel(m_model); addSortings(); // sometimes Qt just ignores virtual slots and doesn't work as intended it seems, // so it's best not to connect them in the parent's constructor... connect(m_ui->sortByBox, SIGNAL(currentIndexChanged(int)), this, SLOT(triggerSearch())); connect(m_ui->packView->selectionModel(), &QItemSelectionModel::currentChanged, this, &ModrinthTexturePackPage::onSelectionChanged); connect(m_ui->versionSelectionBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &ModrinthTexturePackPage::onVersionSelectionChanged); connect(m_ui->resourceSelectionButton, &QPushButton::clicked, this, &ModrinthTexturePackPage::onResourceSelected); m_ui->packDescription->setMetaEntry(metaEntryBase()); } ModrinthShaderPackPage::ModrinthShaderPackPage(ShaderPackDownloadDialog* dialog, BaseInstance& instance) : ShaderPackResourcePage(dialog, instance) { m_model = new ModrinthShaderPackModel(instance); m_ui->packView->setModel(m_model); addSortings(); // sometimes Qt just ignores virtual slots and doesn't work as intended it seems, // so it's best not to connect them in the parent's constructor... connect(m_ui->sortByBox, SIGNAL(currentIndexChanged(int)), this, SLOT(triggerSearch())); connect(m_ui->packView->selectionModel(), &QItemSelectionModel::currentChanged, this, &ModrinthShaderPackPage::onSelectionChanged); connect(m_ui->versionSelectionBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &ModrinthShaderPackPage::onVersionSelectionChanged); connect(m_ui->resourceSelectionButton, &QPushButton::clicked, this, &ModrinthShaderPackPage::onResourceSelected); m_ui->packDescription->setMetaEntry(metaEntryBase()); } // I don't know why, but doing this on the parent class makes it so that // other mod providers start loading before being selected, at least with // my Qt, so we need to implement this in every derived class... auto ModrinthModPage::shouldDisplay() const -> bool { return true; } auto ModrinthResourcePackPage::shouldDisplay() const -> bool { return true; } auto ModrinthTexturePackPage::shouldDisplay() const -> bool { return true; } auto ModrinthShaderPackPage::shouldDisplay() const -> bool { return true; } unique_qobject_ptr<ModFilterWidget> ModrinthModPage::createFilterWidget() { return ModFilterWidget::create(&static_cast<MinecraftInstance&>(m_baseInstance), true, this); } void ModrinthModPage::prepareProviderCategories() { auto response = std::make_shared<QByteArray>(); auto task = ModrinthAPI::getModCategories(response); QObject::connect(task.get(), &Task::succeeded, [this, response]() { auto categories = ModrinthAPI::loadModCategories(response); m_filter_widget->setCategories(categories); }); task->start(); }; } // namespace ResourceDownload
6,940
C++
.cpp
136
47.580882
137
0.761947
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,976
ModrinthModel.cpp
PrismLauncher_PrismLauncher/launcher/ui/pages/modplatform/modrinth/ModrinthModel.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 flowln <flowlnlnln@gmail.com> * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 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 "ModrinthModel.h" #include "BuildConfig.h" #include "Json.h" #include "modplatform/modrinth/ModrinthAPI.h" #include "net/NetJob.h" #include "ui/widgets/ProjectItem.h" #include "net/ApiDownload.h" #include <QMessageBox> namespace Modrinth { ModpackListModel::ModpackListModel(ModrinthPage* parent) : QAbstractListModel(parent), m_parent(parent) {} auto ModpackListModel::debugName() const -> QString { return m_parent->debugName(); } /******** Make data requests ********/ void ModpackListModel::fetchMore(const QModelIndex& parent) { if (parent.isValid()) return; if (nextSearchOffset == 0) { qWarning() << "fetchMore with 0 offset is wrong..."; return; } performPaginatedSearch(); } auto ModpackListModel::data(const QModelIndex& index, int role) const -> QVariant { int pos = index.row(); if (pos >= modpacks.size() || pos < 0 || !index.isValid()) { return QString("INVALID INDEX %1").arg(pos); } Modrinth::Modpack pack = modpacks.at(pos); switch (role) { case Qt::ToolTipRole: { if (pack.description.length() > 100) { // some magic to prevent to long tooltips and replace html linebreaks QString edit = pack.description.left(97); edit = edit.left(edit.lastIndexOf("<br>")).left(edit.lastIndexOf(" ")).append("..."); return edit; } return pack.description; } case Qt::DecorationRole: { if (m_logoMap.contains(pack.iconName)) return m_logoMap.value(pack.iconName); QIcon icon = APPLICATION->getThemedIcon("screenshot-placeholder"); ((ModpackListModel*)this)->requestLogo(pack.iconName, pack.iconUrl.toString()); return icon; } case Qt::UserRole: { QVariant v; v.setValue(pack); return v; } case Qt::SizeHintRole: return QSize(0, 58); // Custom data case UserDataTypes::TITLE: return pack.name; case UserDataTypes::DESCRIPTION: return pack.description; case UserDataTypes::SELECTED: return false; case UserDataTypes::INSTALLED: return false; default: break; } return {}; } bool ModpackListModel::setData(const QModelIndex& index, const QVariant& value, [[maybe_unused]] int role) { int pos = index.row(); if (pos >= modpacks.size() || pos < 0 || !index.isValid()) return false; modpacks[pos] = value.value<Modrinth::Modpack>(); return true; } void ModpackListModel::performPaginatedSearch() { if (hasActiveSearchJob()) return; if (currentSearchTerm.startsWith("#")) { auto projectId = currentSearchTerm.mid(1); if (!projectId.isEmpty()) { ResourceAPI::ProjectInfoCallbacks callbacks; callbacks.on_fail = [this](QString reason) { searchRequestFailed(reason); }; callbacks.on_succeed = [this](auto& doc, auto& pack) { searchRequestForOneSucceeded(doc); }; callbacks.on_abort = [this] { qCritical() << "Search task aborted by an unknown reason!"; searchRequestFailed("Aborted"); }; static const ModrinthAPI api; if (auto job = api.getProjectInfo({ projectId }, std::move(callbacks)); job) { jobPtr = job; jobPtr->start(); } return; } } // TODO: Move to standalone API ResourceAPI::SortingMethod sort{}; sort.name = currentSort; auto searchUrl = ModrinthAPI().getSearchURL({ ModPlatform::ResourceType::MODPACK, nextSearchOffset, currentSearchTerm, sort, m_filter->loaders, m_filter->versions, "", m_filter->categoryIds, m_filter->openSource }); auto netJob = makeShared<NetJob>("Modrinth::SearchModpack", APPLICATION->network()); netJob->addNetAction(Net::ApiDownload::makeByteArray(QUrl(searchUrl.value()), m_allResponse)); QObject::connect(netJob.get(), &NetJob::succeeded, this, [this] { QJsonParseError parseError{}; QJsonDocument doc = QJsonDocument::fromJson(*m_allResponse, &parseError); if (parseError.error != QJsonParseError::NoError) { qWarning() << "Error while parsing JSON response from " << debugName() << " at " << parseError.offset << " reason: " << parseError.errorString(); qWarning() << *m_allResponse; return; } searchRequestFinished(doc); }); QObject::connect(netJob.get(), &NetJob::failed, this, &ModpackListModel::searchRequestFailed); jobPtr = netJob; jobPtr->start(); } void ModpackListModel::refresh() { if (hasActiveSearchJob()) { jobPtr->abort(); searchState = ResetRequested; return; } beginResetModel(); modpacks.clear(); endResetModel(); searchState = None; nextSearchOffset = 0; performPaginatedSearch(); } static auto sortFromIndex(int index) -> QString { switch (index) { default: case 0: return "relevance"; case 1: return "downloads"; case 2: return "follows"; case 3: return "newest"; case 4: return "updated"; } } void ModpackListModel::searchWithTerm(const QString& term, const int sort, std::shared_ptr<ModFilterWidget::Filter> filter, bool filterChanged) { if (sort > 5 || sort < 0) return; auto sort_str = sortFromIndex(sort); if (currentSearchTerm == term && currentSearchTerm.isNull() == term.isNull() && currentSort == sort_str && !filterChanged) { return; } currentSearchTerm = term; currentSort = sort_str; m_filter = filter; refresh(); } void ModpackListModel::getLogo(const QString& logo, const QString& logoUrl, LogoCallback callback) { if (m_logoMap.contains(logo)) { callback(APPLICATION->metacache()->resolveEntry(m_parent->metaEntryBase(), QString("logos/%1").arg(logo))->getFullPath()); } else { requestLogo(logo, logoUrl); } } void ModpackListModel::requestLogo(QString logo, QString url) { if (m_loadingLogos.contains(logo) || m_failedLogos.contains(logo) || url.isEmpty()) { return; } MetaEntryPtr entry = APPLICATION->metacache()->resolveEntry(m_parent->metaEntryBase(), QString("logos/%1").arg(logo)); auto job = new NetJob(QString("%1 Icon Download %2").arg(m_parent->debugName()).arg(logo), APPLICATION->network()); job->setAskRetry(false); job->addNetAction(Net::ApiDownload::makeCached(QUrl(url), entry)); auto fullPath = entry->getFullPath(); QObject::connect(job, &NetJob::succeeded, this, [this, logo, fullPath, job] { job->deleteLater(); emit logoLoaded(logo, QIcon(fullPath)); if (waitingCallbacks.contains(logo)) { waitingCallbacks.value(logo)(fullPath); } }); QObject::connect(job, &NetJob::failed, this, [this, logo, job] { job->deleteLater(); emit logoFailed(logo); }); job->start(); m_loadingLogos.append(logo); } /******** Request callbacks ********/ void ModpackListModel::logoLoaded(QString logo, QIcon out) { m_loadingLogos.removeAll(logo); m_logoMap.insert(logo, out); for (int i = 0; i < modpacks.size(); i++) { if (modpacks[i].iconName == logo) { emit dataChanged(createIndex(i, 0), createIndex(i, 0), { Qt::DecorationRole }); } } } void ModpackListModel::logoFailed(QString logo) { m_failedLogos.append(logo); m_loadingLogos.removeAll(logo); } void ModpackListModel::searchRequestFinished(QJsonDocument& doc_all) { jobPtr.reset(); QList<Modrinth::Modpack> newList; auto packs_all = doc_all.object().value("hits").toArray(); for (auto packRaw : packs_all) { auto packObj = packRaw.toObject(); Modrinth::Modpack pack; try { Modrinth::loadIndexedPack(pack, packObj); newList.append(pack); } catch (const JSONValidationError& e) { qWarning() << "Error while loading mod from " << m_parent->debugName() << ": " << e.cause(); continue; } } if (packs_all.size() < m_modpacks_per_page) { searchState = Finished; } else { nextSearchOffset += m_modpacks_per_page; searchState = CanPossiblyFetchMore; } // When you have a Qt build with assertions turned on, proceeding here will abort the application if (newList.size() == 0) return; beginInsertRows(QModelIndex(), modpacks.size(), modpacks.size() + newList.size() - 1); modpacks.append(newList); endInsertRows(); } void ModpackListModel::searchRequestForOneSucceeded(QJsonDocument& doc) { jobPtr.reset(); auto packObj = doc.object(); Modrinth::Modpack pack; try { Modrinth::loadIndexedPack(pack, packObj); pack.id = Json::ensureString(packObj, "id", pack.id); } catch (const JSONValidationError& e) { qWarning() << "Error while loading mod from " << m_parent->debugName() << ": " << e.cause(); return; } beginInsertRows(QModelIndex(), modpacks.size(), modpacks.size() + 1); modpacks.append({ pack }); endInsertRows(); } void ModpackListModel::searchRequestFailed(QString reason) { auto failed_action = dynamic_cast<NetJob*>(jobPtr.get())->getFailedActions().at(0); if (failed_action->replyStatusCode() == -1) { // Network error QMessageBox::critical(nullptr, tr("Error"), tr("A network error occurred. Could not load modpacks.")); } else if (failed_action->replyStatusCode() == 409) { // 409 Gone, notify user to update QMessageBox::critical(nullptr, tr("Error"), //: %1 refers to the launcher itself QString("%1 %2") .arg(m_parent->displayName()) .arg(tr("API version too old!\nPlease update %1!").arg(BuildConfig.LAUNCHER_DISPLAYNAME))); } jobPtr.reset(); if (searchState == ResetRequested) { beginResetModel(); modpacks.clear(); endResetModel(); nextSearchOffset = 0; performPaginatedSearch(); } else { searchState = Finished; } } } // namespace Modrinth /******** Helpers ********/
12,219
C++
.cpp
322
30.767081
140
0.628263
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,977
ModrinthPage.cpp
PrismLauncher_PrismLauncher/launcher/ui/pages/modplatform/modrinth/ModrinthPage.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 flowln <flowlnlnln@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * Copyright 2021-2022 kb1000 * * 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 "ModrinthPage.h" #include "Version.h" #include "modplatform/modrinth/ModrinthAPI.h" #include "ui/dialogs/CustomMessageBox.h" #include "ui_ModrinthPage.h" #include "ModrinthModel.h" #include "BuildConfig.h" #include "InstanceImportTask.h" #include "Json.h" #include "Markdown.h" #include "StringUtils.h" #include "ui/widgets/ProjectItem.h" #include "net/ApiDownload.h" #include <QComboBox> #include <QKeyEvent> #include <QPushButton> ModrinthPage::ModrinthPage(NewInstanceDialog* dialog, QWidget* parent) : QWidget(parent), ui(new Ui::ModrinthPage), dialog(dialog), m_fetch_progress(this, false) { ui->setupUi(this); createFilterWidget(); ui->searchEdit->installEventFilter(this); m_model = new Modrinth::ModpackListModel(this); ui->packView->setModel(m_model); ui->versionSelectionBox->view()->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); ui->versionSelectionBox->view()->parentWidget()->setMaximumHeight(300); m_search_timer.setTimerType(Qt::TimerType::CoarseTimer); m_search_timer.setSingleShot(true); connect(&m_search_timer, &QTimer::timeout, this, &ModrinthPage::triggerSearch); m_fetch_progress.hideIfInactive(true); m_fetch_progress.setFixedHeight(24); m_fetch_progress.progressFormat(""); ui->verticalLayout->insertWidget(1, &m_fetch_progress); ui->sortByBox->addItem(tr("Sort by Relevance")); ui->sortByBox->addItem(tr("Sort by Total Downloads")); ui->sortByBox->addItem(tr("Sort by Follows")); ui->sortByBox->addItem(tr("Sort by Newest")); ui->sortByBox->addItem(tr("Sort by Last Updated")); connect(ui->sortByBox, SIGNAL(currentIndexChanged(int)), this, SLOT(triggerSearch())); connect(ui->packView->selectionModel(), &QItemSelectionModel::currentChanged, this, &ModrinthPage::onSelectionChanged); connect(ui->versionSelectionBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &ModrinthPage::onVersionSelectionChanged); ui->packView->setItemDelegate(new ProjectItemDelegate(this)); ui->packDescription->setMetaEntry(metaEntryBase()); } ModrinthPage::~ModrinthPage() { delete ui; } void ModrinthPage::retranslate() { ui->retranslateUi(this); } void ModrinthPage::openedImpl() { BasePage::openedImpl(); suggestCurrent(); triggerSearch(); } bool ModrinthPage::eventFilter(QObject* watched, QEvent* event) { if (watched == ui->searchEdit && event->type() == QEvent::KeyPress) { auto* keyEvent = reinterpret_cast<QKeyEvent*>(event); if (keyEvent->key() == Qt::Key_Return) { this->triggerSearch(); keyEvent->accept(); return true; } else { if (m_search_timer.isActive()) m_search_timer.stop(); m_search_timer.start(350); } } return QObject::eventFilter(watched, event); } bool checkVersionFilters(const Modrinth::ModpackVersion& v, std::shared_ptr<ModFilterWidget::Filter> filter) { if (!filter) return true; return ((!filter->loaders || !v.loaders || filter->loaders & v.loaders) && // loaders (filter->releases.empty() || // releases std::find(filter->releases.cbegin(), filter->releases.cend(), v.version_type) != filter->releases.cend()) && filter->checkMcVersions({ v.gameVersion })); // gameVersion} } void ModrinthPage::onSelectionChanged(QModelIndex curr, [[maybe_unused]] QModelIndex prev) { ui->versionSelectionBox->clear(); if (!curr.isValid()) { if (isOpened) { dialog->setSuggestedPack(); } return; } current = m_model->data(curr, Qt::UserRole).value<Modrinth::Modpack>(); auto name = current.name; if (!current.extraInfoLoaded) { qDebug() << "Loading modrinth modpack information"; auto netJob = new NetJob(QString("Modrinth::PackInformation(%1)").arg(current.name), APPLICATION->network()); auto response = std::make_shared<QByteArray>(); QString id = current.id; netJob->addNetAction(Net::ApiDownload::makeByteArray(QString("%1/project/%2").arg(BuildConfig.MODRINTH_PROD_URL, id), response)); QObject::connect(netJob, &NetJob::succeeded, this, [this, response, id, curr] { if (id != current.id) { return; // wrong request? } QJsonParseError parse_error; QJsonDocument doc = QJsonDocument::fromJson(*response, &parse_error); if (parse_error.error != QJsonParseError::NoError) { qWarning() << "Error while parsing JSON response from Modrinth at " << parse_error.offset << " reason: " << parse_error.errorString(); qWarning() << *response; return; } auto obj = Json::requireObject(doc); try { Modrinth::loadIndexedInfo(current, obj); } catch (const JSONValidationError& e) { qDebug() << *response; qWarning() << "Error while reading modrinth modpack version: " << e.cause(); } updateUI(); QVariant current_updated; current_updated.setValue(current); if (!m_model->setData(curr, current_updated, Qt::UserRole)) qWarning() << "Failed to cache extra info for the current pack!"; suggestCurrent(); }); QObject::connect(netJob, &NetJob::finished, this, [response, netJob] { netJob->deleteLater(); }); connect(netJob, &NetJob::failed, [this](QString reason) { CustomMessageBox::selectable(this, tr("Error"), reason, QMessageBox::Critical)->exec(); }); netJob->start(); } else updateUI(); if (!current.versionsLoaded || m_filterWidget->changed()) { qDebug() << "Loading modrinth modpack versions"; auto netJob = new NetJob(QString("Modrinth::PackVersions(%1)").arg(current.name), APPLICATION->network()); auto response = std::make_shared<QByteArray>(); QString id = current.id; netJob->addNetAction( Net::ApiDownload::makeByteArray(QString("%1/project/%2/version").arg(BuildConfig.MODRINTH_PROD_URL, id), response)); QObject::connect(netJob, &NetJob::succeeded, this, [this, response, id, curr] { if (id != current.id) { return; // wrong request? } QJsonParseError parse_error; QJsonDocument doc = QJsonDocument::fromJson(*response, &parse_error); if (parse_error.error != QJsonParseError::NoError) { qWarning() << "Error while parsing JSON response from Modrinth at " << parse_error.offset << " reason: " << parse_error.errorString(); qWarning() << *response; return; } try { Modrinth::loadIndexedVersions(current, doc); } catch (const JSONValidationError& e) { qDebug() << *response; qWarning() << "Error while reading modrinth modpack version: " << e.cause(); } auto pred = [this](const Modrinth::ModpackVersion& v) { return !checkVersionFilters(v, m_filterWidget->getFilter()); }; #if QT_VERSION >= QT_VERSION_CHECK(6, 1, 0) current.versions.removeIf(pred); #else for (auto it = current.versions.begin(); it != current.versions.end();) if (pred(*it)) it = current.versions.erase(it); else ++it; #endif for (auto version : current.versions) { auto release_type = version.version_type.isValid() ? QString(" [%1]").arg(version.version_type.toString()) : ""; auto mcVersion = !version.gameVersion.isEmpty() && !version.name.contains(version.gameVersion) ? QString(" for %1").arg(version.gameVersion) : ""; auto versionStr = !version.name.contains(version.version) ? version.version : ""; ui->versionSelectionBox->addItem(QString("%1%2 — %3%4").arg(version.name, mcVersion, versionStr, release_type), QVariant(version.id)); } QVariant current_updated; current_updated.setValue(current); if (!m_model->setData(curr, current_updated, Qt::UserRole)) qWarning() << "Failed to cache versions for the current pack!"; suggestCurrent(); }); QObject::connect(netJob, &NetJob::finished, this, [response, netJob] { netJob->deleteLater(); }); connect(netJob, &NetJob::failed, [this](QString reason) { CustomMessageBox::selectable(this, tr("Error"), reason, QMessageBox::Critical)->exec(); }); netJob->start(); } else { for (auto version : current.versions) { if (!version.name.contains(version.version)) ui->versionSelectionBox->addItem(QString("%1 - %2").arg(version.name, version.version), QVariant(version.id)); else ui->versionSelectionBox->addItem(version.name, QVariant(version.id)); } suggestCurrent(); } } void ModrinthPage::updateUI() { QString text = ""; if (current.extra.projectUrl.isEmpty()) text = current.name; else text = "<a href=\"" + current.extra.projectUrl + "\">" + current.name + "</a>"; // TODO: Implement multiple authors with links text += "<br>" + tr(" by ") + QString("<a href=%1>%2</a>").arg(std::get<1>(current.author).toString(), std::get<0>(current.author)); if (current.extraInfoLoaded) { if (current.extra.status == "archived") { text += "<br><br>" + tr("<b>This project has been archived. It will not receive any further updates unless the author decides " "to unarchive the project.</b>"); } if (!current.extra.donate.isEmpty()) { text += "<br><br>" + tr("Donate information: "); auto donateToStr = [](Modrinth::DonationData& donate) -> QString { return QString("<a href=\"%1\">%2</a>").arg(donate.url, donate.platform); }; QStringList donates; for (auto& donate : current.extra.donate) { donates.append(donateToStr(donate)); } text += donates.join(", "); } if (!current.extra.issuesUrl.isEmpty() || !current.extra.sourceUrl.isEmpty() || !current.extra.wikiUrl.isEmpty() || !current.extra.discordUrl.isEmpty()) { text += "<br><br>" + tr("External links:") + "<br>"; } if (!current.extra.issuesUrl.isEmpty()) text += "- " + tr("Issues: <a href=%1>%1</a>").arg(current.extra.issuesUrl) + "<br>"; if (!current.extra.wikiUrl.isEmpty()) text += "- " + tr("Wiki: <a href=%1>%1</a>").arg(current.extra.wikiUrl) + "<br>"; if (!current.extra.sourceUrl.isEmpty()) text += "- " + tr("Source code: <a href=%1>%1</a>").arg(current.extra.sourceUrl) + "<br>"; if (!current.extra.discordUrl.isEmpty()) text += "- " + tr("Discord: <a href=%1>%1</a>").arg(current.extra.discordUrl) + "<br>"; } text += "<hr>"; text += markdownToHTML(current.extra.body.toUtf8()); ui->packDescription->setHtml(StringUtils::htmlListPatch(text + current.description)); ui->packDescription->flush(); } void ModrinthPage::suggestCurrent() { if (!isOpened) { return; } if (selectedVersion.isEmpty()) { dialog->setSuggestedPack(); return; } for (auto& ver : current.versions) { if (ver.id == selectedVersion) { QMap<QString, QString> extra_info; extra_info.insert("pack_id", current.id); extra_info.insert("pack_version_id", ver.id); dialog->setSuggestedPack(current.name, ver.version, new InstanceImportTask(ver.download_url, this, std::move(extra_info))); auto iconName = current.iconName; m_model->getLogo(iconName, current.iconUrl.toString(), [this, iconName](QString logo) { dialog->setSuggestedIconFromFile(logo, iconName); }); break; } } } void ModrinthPage::triggerSearch() { ui->packView->selectionModel()->setCurrentIndex({}, QItemSelectionModel::SelectionFlag::ClearAndSelect); ui->packView->clearSelection(); ui->packDescription->clear(); ui->versionSelectionBox->clear(); m_model->searchWithTerm(ui->searchEdit->text(), ui->sortByBox->currentIndex(), m_filterWidget->getFilter(), m_filterWidget->changed()); m_fetch_progress.watch(m_model->activeSearchJob().get()); } void ModrinthPage::onVersionSelectionChanged(int index) { if (index == -1) { selectedVersion = ""; return; } selectedVersion = ui->versionSelectionBox->itemData(index).toString(); suggestCurrent(); } void ModrinthPage::setSearchTerm(QString term) { ui->searchEdit->setText(term); } QString ModrinthPage::getSerachTerm() const { return ui->searchEdit->text(); } void ModrinthPage::createFilterWidget() { auto widget = ModFilterWidget::create(nullptr, true, this); m_filterWidget.swap(widget); auto old = ui->splitter->replaceWidget(0, m_filterWidget.get()); // because we replaced the widget we also need to delete it if (old) { delete old; } connect(ui->filterButton, &QPushButton::clicked, this, [this] { m_filterWidget->setHidden(!m_filterWidget->isHidden()); }); connect(m_filterWidget.get(), &ModFilterWidget::filterChanged, this, &ModrinthPage::triggerSearch); auto response = std::make_shared<QByteArray>(); m_categoriesTask = ModrinthAPI::getModCategories(response); QObject::connect(m_categoriesTask.get(), &Task::succeeded, [this, response]() { auto categories = ModrinthAPI::loadCategories(response, "modpack"); m_filterWidget->setCategories(categories); }); m_categoriesTask->start(); }
15,714
C++
.cpp
341
38.096774
139
0.629942
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,978
ModrinthResourceModels.cpp
PrismLauncher_PrismLauncher/launcher/ui/pages/modplatform/modrinth/ModrinthResourceModels.cpp
// SPDX-FileCopyrightText: 2023 flowln <flowlnlnln@gmail.com> // // SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "ModrinthResourceModels.h" #include "modplatform/modrinth/ModrinthAPI.h" #include "modplatform/modrinth/ModrinthPackIndex.h" namespace ResourceDownload { ModrinthModModel::ModrinthModModel(BaseInstance& base) : ModModel(base, new ModrinthAPI) {} void ModrinthModModel::loadIndexedPack(ModPlatform::IndexedPack& m, QJsonObject& obj) { ::Modrinth::loadIndexedPack(m, obj); } void ModrinthModModel::loadExtraPackInfo(ModPlatform::IndexedPack& m, QJsonObject& obj) { ::Modrinth::loadExtraPackData(m, obj); } void ModrinthModModel::loadIndexedPackVersions(ModPlatform::IndexedPack& m, QJsonArray& arr) { ::Modrinth::loadIndexedPackVersions(m, arr, &m_base_instance); } auto ModrinthModModel::loadDependencyVersions(const ModPlatform::Dependency& m, QJsonArray& arr) -> ModPlatform::IndexedVersion { return ::Modrinth::loadDependencyVersions(m, arr, &m_base_instance); } auto ModrinthModModel::documentToArray(QJsonDocument& obj) const -> QJsonArray { return obj.object().value("hits").toArray(); } ModrinthResourcePackModel::ModrinthResourcePackModel(const BaseInstance& base) : ResourcePackResourceModel(base, new ModrinthAPI) {} void ModrinthResourcePackModel::loadIndexedPack(ModPlatform::IndexedPack& m, QJsonObject& obj) { ::Modrinth::loadIndexedPack(m, obj); } void ModrinthResourcePackModel::loadExtraPackInfo(ModPlatform::IndexedPack& m, QJsonObject& obj) { ::Modrinth::loadExtraPackData(m, obj); } void ModrinthResourcePackModel::loadIndexedPackVersions(ModPlatform::IndexedPack& m, QJsonArray& arr) { ::Modrinth::loadIndexedPackVersions(m, arr, &m_base_instance); } auto ModrinthResourcePackModel::documentToArray(QJsonDocument& obj) const -> QJsonArray { return obj.object().value("hits").toArray(); } ModrinthTexturePackModel::ModrinthTexturePackModel(const BaseInstance& base) : TexturePackResourceModel(base, new ModrinthAPI) {} void ModrinthTexturePackModel::loadIndexedPack(ModPlatform::IndexedPack& m, QJsonObject& obj) { ::Modrinth::loadIndexedPack(m, obj); } void ModrinthTexturePackModel::loadExtraPackInfo(ModPlatform::IndexedPack& m, QJsonObject& obj) { ::Modrinth::loadExtraPackData(m, obj); } void ModrinthTexturePackModel::loadIndexedPackVersions(ModPlatform::IndexedPack& m, QJsonArray& arr) { ::Modrinth::loadIndexedPackVersions(m, arr, &m_base_instance); } auto ModrinthTexturePackModel::documentToArray(QJsonDocument& obj) const -> QJsonArray { return obj.object().value("hits").toArray(); } ModrinthShaderPackModel::ModrinthShaderPackModel(const BaseInstance& base) : ShaderPackResourceModel(base, new ModrinthAPI) {} void ModrinthShaderPackModel::loadIndexedPack(ModPlatform::IndexedPack& m, QJsonObject& obj) { ::Modrinth::loadIndexedPack(m, obj); } void ModrinthShaderPackModel::loadExtraPackInfo(ModPlatform::IndexedPack& m, QJsonObject& obj) { ::Modrinth::loadExtraPackData(m, obj); } void ModrinthShaderPackModel::loadIndexedPackVersions(ModPlatform::IndexedPack& m, QJsonArray& arr) { ::Modrinth::loadIndexedPackVersions(m, arr, &m_base_instance); } auto ModrinthShaderPackModel::documentToArray(QJsonDocument& obj) const -> QJsonArray { return obj.object().value("hits").toArray(); } } // namespace ResourceDownload
4,060
C++
.cpp
96
40.166667
132
0.792587
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,979
AtlPage.cpp
PrismLauncher_PrismLauncher/launcher/ui/pages/modplatform/atlauncher/AtlPage.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 Jamie Mansfield <jmansfield@cadixdev.org> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2020-2021 Jamie Mansfield <jmansfield@cadixdev.org> * Copyright 2021 Philip T <me@phit.link> * * 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 "AtlPage.h" #include "ui/widgets/ProjectItem.h" #include "ui_AtlPage.h" #include "BuildConfig.h" #include "StringUtils.h" #include "AtlUserInteractionSupportImpl.h" #include "modplatform/atlauncher/ATLPackInstallTask.h" #include "ui/dialogs/NewInstanceDialog.h" #include <QMessageBox> AtlPage::AtlPage(NewInstanceDialog* dialog, QWidget* parent) : QWidget(parent), ui(new Ui::AtlPage), dialog(dialog) { ui->setupUi(this); filterModel = new Atl::FilterModel(this); listModel = new Atl::ListModel(this); filterModel->setSourceModel(listModel); ui->packView->setModel(filterModel); ui->packView->setSortingEnabled(true); ui->packView->header()->hide(); ui->packView->setIndentation(0); ui->versionSelectionBox->view()->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); ui->versionSelectionBox->view()->parentWidget()->setMaximumHeight(300); for (int i = 0; i < filterModel->getAvailableSortings().size(); i++) { ui->sortByBox->addItem(filterModel->getAvailableSortings().keys().at(i)); } ui->sortByBox->setCurrentText(filterModel->translateCurrentSorting()); connect(ui->searchEdit, &QLineEdit::textChanged, this, &AtlPage::triggerSearch); connect(ui->sortByBox, &QComboBox::currentTextChanged, this, &AtlPage::onSortingSelectionChanged); connect(ui->packView->selectionModel(), &QItemSelectionModel::currentChanged, this, &AtlPage::onSelectionChanged); connect(ui->versionSelectionBox, &QComboBox::currentTextChanged, this, &AtlPage::onVersionSelectionChanged); ui->packView->setItemDelegate(new ProjectItemDelegate(this)); } AtlPage::~AtlPage() { delete ui; } bool AtlPage::shouldDisplay() const { return true; } void AtlPage::retranslate() { ui->retranslateUi(this); } void AtlPage::openedImpl() { if (!initialized) { listModel->request(); initialized = true; } suggestCurrent(); } void AtlPage::suggestCurrent() { if (!isOpened) { return; } if (selectedVersion.isEmpty()) { dialog->setSuggestedPack(); return; } auto uiSupport = new AtlUserInteractionSupportImpl(this); dialog->setSuggestedPack(selected.name, selectedVersion, new ATLauncher::PackInstallTask(uiSupport, selected.name, selectedVersion)); auto editedLogoName = "atl_" + selected.safeName; auto url = QString(BuildConfig.ATL_DOWNLOAD_SERVER_URL + "launcher/images/%1").arg(selected.safeName); listModel->getLogo(selected.safeName, url, [this, editedLogoName](QString logo) { dialog->setSuggestedIconFromFile(logo, editedLogoName); }); } void AtlPage::triggerSearch() { filterModel->setSearchTerm(ui->searchEdit->text()); } void AtlPage::onSortingSelectionChanged(QString sort) { auto toSet = filterModel->getAvailableSortings().value(sort); filterModel->setSorting(toSet); } void AtlPage::onSelectionChanged(QModelIndex first, [[maybe_unused]] QModelIndex second) { ui->versionSelectionBox->clear(); if (!first.isValid()) { if (isOpened) { dialog->setSuggestedPack(); } return; } selected = filterModel->data(first, Qt::UserRole).value<ATLauncher::IndexedPack>(); ui->packDescription->setHtml(StringUtils::htmlListPatch(selected.description.replace("\n", "<br>"))); for (const auto& version : selected.versions) { ui->versionSelectionBox->addItem(version.version); } suggestCurrent(); } void AtlPage::onVersionSelectionChanged(QString version) { if (version.isNull() || version.isEmpty()) { selectedVersion = ""; return; } selectedVersion = version; suggestCurrent(); } void AtlPage::setSearchTerm(QString term) { ui->searchEdit->setText(term); } QString AtlPage::getSerachTerm() const { return ui->searchEdit->text(); }
5,425
C++
.cpp
144
33.923611
137
0.724138
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
28,980
AtlListModel.cpp
PrismLauncher_PrismLauncher/launcher/ui/pages/modplatform/atlauncher/AtlListModel.cpp
/* * Copyright 2020-2021 Jamie Mansfield <jmansfield@cadixdev.org> * * 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 "AtlListModel.h" #include <Application.h> #include <BuildConfig.h> #include <Json.h> #include "net/ApiDownload.h" #include "ui/widgets/ProjectItem.h" namespace Atl { ListModel::ListModel(QObject* parent) : QAbstractListModel(parent) {} ListModel::~ListModel() {} int ListModel::rowCount(const QModelIndex& parent) const { return parent.isValid() ? 0 : modpacks.size(); } int ListModel::columnCount(const QModelIndex& parent) const { return parent.isValid() ? 0 : 1; } QVariant ListModel::data(const QModelIndex& index, int role) const { int pos = index.row(); if (pos >= modpacks.size() || pos < 0 || !index.isValid()) { return QString("INVALID INDEX %1").arg(pos); } ATLauncher::IndexedPack pack = modpacks.at(pos); switch (role) { case Qt::ToolTipRole: { if (pack.description.length() > 100) { // some magic to prevent to long tooltips and replace html linebreaks QString edit = pack.description.left(97); edit = edit.left(edit.lastIndexOf("<br>")).left(edit.lastIndexOf(" ")).append("..."); return edit; } return pack.description; } case Qt::DecorationRole: { if (m_logoMap.contains(pack.safeName)) { return (m_logoMap.value(pack.safeName)); } auto icon = APPLICATION->getThemedIcon("atlauncher-placeholder"); auto url = QString(BuildConfig.ATL_DOWNLOAD_SERVER_URL + "launcher/images/%1").arg(pack.safeName); ((ListModel*)this)->requestLogo(pack.safeName, url); return icon; } case Qt::UserRole: { QVariant v; v.setValue(pack); return v; } case Qt::DisplayRole: return pack.name; case Qt::SizeHintRole: return QSize(0, 58); // Custom data case UserDataTypes::TITLE: return pack.name; case UserDataTypes::DESCRIPTION: return pack.description; case UserDataTypes::SELECTED: return false; case UserDataTypes::INSTALLED: return false; default: break; } return {}; } void ListModel::request() { beginResetModel(); modpacks.clear(); endResetModel(); auto netJob = makeShared<NetJob>("Atl::Request", APPLICATION->network()); auto url = QString(BuildConfig.ATL_DOWNLOAD_SERVER_URL + "launcher/json/packsnew.json"); netJob->addNetAction(Net::ApiDownload::makeByteArray(QUrl(url), response)); jobPtr = netJob; jobPtr->start(); QObject::connect(netJob.get(), &NetJob::succeeded, this, &ListModel::requestFinished); QObject::connect(netJob.get(), &NetJob::failed, this, &ListModel::requestFailed); } void ListModel::requestFinished() { jobPtr.reset(); QJsonParseError parse_error; QJsonDocument doc = QJsonDocument::fromJson(*response, &parse_error); if (parse_error.error != QJsonParseError::NoError) { qWarning() << "Error while parsing JSON response from ATL at " << parse_error.offset << " reason: " << parse_error.errorString(); qWarning() << *response; return; } QList<ATLauncher::IndexedPack> newList; auto packs = doc.array(); for (auto packRaw : packs) { auto packObj = packRaw.toObject(); ATLauncher::IndexedPack pack; try { ATLauncher::loadIndexedPack(pack, packObj); } catch (const JSONValidationError& e) { qDebug() << QString::fromUtf8(*response); qWarning() << "Error while reading pack manifest from ATLauncher: " << e.cause(); return; } // ignore packs without a published version if (pack.versions.length() == 0) continue; // only display public packs (for now) if (pack.type != ATLauncher::PackType::Public) continue; // ignore "system" packs (Vanilla, Vanilla with Forge, etc) if (pack.system) continue; newList.append(pack); } beginInsertRows(QModelIndex(), modpacks.size(), modpacks.size() + newList.size() - 1); modpacks.append(newList); endInsertRows(); } void ListModel::requestFailed(QString reason) { jobPtr.reset(); } void ListModel::getLogo(const QString& logo, const QString& logoUrl, LogoCallback callback) { if (m_logoMap.contains(logo)) { callback(APPLICATION->metacache()->resolveEntry("ATLauncherPacks", QString("logos/%1").arg(logo))->getFullPath()); } else { requestLogo(logo, logoUrl); } } void ListModel::logoFailed(QString logo) { m_failedLogos.append(logo); m_loadingLogos.removeAll(logo); } void ListModel::logoLoaded(QString logo, QIcon out) { m_loadingLogos.removeAll(logo); m_logoMap.insert(logo, out); for (int i = 0; i < modpacks.size(); i++) { if (modpacks[i].safeName == logo) { emit dataChanged(createIndex(i, 0), createIndex(i, 0), { Qt::DecorationRole }); } } } void ListModel::requestLogo(QString file, QString url) { if (m_loadingLogos.contains(file) || m_failedLogos.contains(file)) { return; } MetaEntryPtr entry = APPLICATION->metacache()->resolveEntry("ATLauncherPacks", QString("logos/%1").arg(file)); auto job = new NetJob(QString("ATLauncher Icon Download %1").arg(file), APPLICATION->network()); job->setAskRetry(false); job->addNetAction(Net::ApiDownload::makeCached(QUrl(url), entry)); auto fullPath = entry->getFullPath(); QObject::connect(job, &NetJob::succeeded, this, [this, file, fullPath, job] { job->deleteLater(); emit logoLoaded(file, QIcon(fullPath)); if (waitingCallbacks.contains(file)) { waitingCallbacks.value(file)(fullPath); } }); QObject::connect(job, &NetJob::failed, this, [this, file, job] { job->deleteLater(); emit logoFailed(file); }); job->start(); m_loadingLogos.append(file); } } // namespace Atl
6,715
C++
.cpp
183
30.169399
137
0.645574
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,981
AtlOptionalModDialog.cpp
PrismLauncher_PrismLauncher/launcher/ui/pages/modplatform/atlauncher/AtlOptionalModDialog.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 Jamie Mansfield <jmansfield@cadixdev.org> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2021 Jamie Mansfield <jmansfield@cadixdev.org> * * 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 "AtlOptionalModDialog.h" #include "ui_AtlOptionalModDialog.h" #include <QInputDialog> #include <QMessageBox> #include "Application.h" #include "BuildConfig.h" #include "Json.h" #include "modplatform/atlauncher/ATLShareCode.h" #include "net/ApiDownload.h" AtlOptionalModListModel::AtlOptionalModListModel(QWidget* parent, ATLauncher::PackVersion version, QVector<ATLauncher::VersionMod> mods) : QAbstractListModel(parent), m_version(version), m_mods(mods) { // fill mod index for (int i = 0; i < m_mods.size(); i++) { auto mod = m_mods.at(i); m_index[mod.name] = i; } // set initial state for (int i = 0; i < m_mods.size(); i++) { auto mod = m_mods.at(i); m_selection[mod.name] = false; setMod(mod, i, mod.selected, false); } } QVector<QString> AtlOptionalModListModel::getResult() { QVector<QString> result; for (const auto& mod : m_mods) { if (m_selection[mod.name]) { result.push_back(mod.name); } } return result; } int AtlOptionalModListModel::rowCount(const QModelIndex& parent) const { return parent.isValid() ? 0 : m_mods.size(); } int AtlOptionalModListModel::columnCount(const QModelIndex& parent) const { // Enabled, Name, Description return parent.isValid() ? 0 : 3; } QVariant AtlOptionalModListModel::data(const QModelIndex& index, int role) const { auto row = index.row(); auto mod = m_mods.at(row); if (role == Qt::DisplayRole) { if (index.column() == NameColumn) { return mod.name; } if (index.column() == DescriptionColumn) { return mod.description; } } else if (role == Qt::ToolTipRole) { if (index.column() == DescriptionColumn) { return mod.description; } } else if (role == Qt::ForegroundRole) { if (!mod.colour.isEmpty() && m_version.colours.contains(mod.colour)) { return QColor(QString("#%1").arg(m_version.colours[mod.colour])); } } else if (role == Qt::CheckStateRole) { if (index.column() == EnabledColumn) { return m_selection[mod.name] ? Qt::Checked : Qt::Unchecked; } } return {}; } bool AtlOptionalModListModel::setData(const QModelIndex& index, [[maybe_unused]] const QVariant& value, int role) { if (role == Qt::CheckStateRole) { auto row = index.row(); auto mod = m_mods.at(row); toggleMod(mod, row); return true; } return false; } QVariant AtlOptionalModListModel::headerData(int section, Qt::Orientation orientation, int role) const { if (role == Qt::DisplayRole && orientation == Qt::Horizontal) { switch (section) { case EnabledColumn: return QString(); case NameColumn: return QString("Name"); case DescriptionColumn: return QString("Description"); } } return {}; } Qt::ItemFlags AtlOptionalModListModel::flags(const QModelIndex& index) const { auto flags = QAbstractListModel::flags(index); if (index.isValid() && index.column() == EnabledColumn) { flags |= Qt::ItemIsUserCheckable; } return flags; } void AtlOptionalModListModel::useShareCode(const QString& code) { m_jobPtr.reset(new NetJob("Atl::Request", APPLICATION->network())); auto url = QString(BuildConfig.ATL_API_BASE_URL + "share-codes/" + code); m_jobPtr->addNetAction(Net::ApiDownload::makeByteArray(QUrl(url), m_response)); connect(m_jobPtr.get(), &NetJob::succeeded, this, &AtlOptionalModListModel::shareCodeSuccess); connect(m_jobPtr.get(), &NetJob::failed, this, &AtlOptionalModListModel::shareCodeFailure); m_jobPtr->start(); } void AtlOptionalModListModel::shareCodeSuccess() { m_jobPtr.reset(); QJsonParseError parse_error{}; auto doc = QJsonDocument::fromJson(*m_response, &parse_error); if (parse_error.error != QJsonParseError::NoError) { qWarning() << "Error while parsing JSON response from ATL at " << parse_error.offset << " reason: " << parse_error.errorString(); qWarning() << *m_response; return; } auto obj = doc.object(); ATLauncher::ShareCodeResponse response; try { ATLauncher::loadShareCodeResponse(response, obj); } catch (const JSONValidationError& e) { qDebug() << QString::fromUtf8(*m_response); qWarning() << "Error while reading response from ATLauncher: " << e.cause(); return; } if (response.error) { // fixme: plumb in an error message qWarning() << "ATLauncher API Response Error" << response.message; return; } // FIXME: verify pack and version, error if not matching. // Clear the current selection for (const auto& mod : m_mods) { m_selection[mod.name] = false; } // Make the selections, as per the share code. for (const auto& mod : response.data.mods) { m_selection[mod.name] = mod.selected; } emit dataChanged(AtlOptionalModListModel::index(0, EnabledColumn), AtlOptionalModListModel::index(m_mods.size() - 1, EnabledColumn)); } void AtlOptionalModListModel::shareCodeFailure([[maybe_unused]] const QString& reason) { m_jobPtr.reset(); // fixme: plumb in an error message } void AtlOptionalModListModel::selectRecommended() { for (const auto& mod : m_mods) { m_selection[mod.name] = mod.recommended; } emit dataChanged(AtlOptionalModListModel::index(0, EnabledColumn), AtlOptionalModListModel::index(m_mods.size() - 1, EnabledColumn)); } void AtlOptionalModListModel::clearAll() { for (const auto& mod : m_mods) { m_selection[mod.name] = false; } emit dataChanged(AtlOptionalModListModel::index(0, EnabledColumn), AtlOptionalModListModel::index(m_mods.size() - 1, EnabledColumn)); } void AtlOptionalModListModel::toggleMod(ATLauncher::VersionMod mod, int index) { auto enable = !m_selection[mod.name]; // If there is a warning for the mod, display that first (if we would be enabling the mod) if (enable && !mod.warning.isEmpty() && m_version.warnings.contains(mod.warning)) { auto message = QString("%1<br><br>%2").arg(m_version.warnings[mod.warning], tr("Are you sure that you want to enable this mod?")); // fixme: avoid casting here auto result = QMessageBox::warning((QWidget*)this->parent(), tr("Warning"), message, QMessageBox::Yes | QMessageBox::No); if (result != QMessageBox::Yes) { return; } } setMod(mod, index, enable); } void AtlOptionalModListModel::setMod(ATLauncher::VersionMod mod, int index, bool enable, bool shouldEmit) { if (m_selection[mod.name] == enable) return; m_selection[mod.name] = enable; // disable other mods in the group, if applicable if (enable && !mod.group.isEmpty()) { for (int i = 0; i < m_mods.size(); i++) { if (index == i) continue; auto other = m_mods.at(i); if (mod.group == other.group) { setMod(other, i, false, shouldEmit); } } } for (const auto& dependencyName : mod.depends) { auto dependencyIndex = m_index[dependencyName]; auto dependencyMod = m_mods.at(dependencyIndex); // enable/disable dependencies if (enable) { setMod(dependencyMod, dependencyIndex, true, shouldEmit); } // if the dependency is 'effectively hidden', then track which mods // depend on it - so we can efficiently disable it when no more dependents // depend on it. auto dependents = m_dependents[dependencyName]; if (enable) { dependents.append(mod.name); } else { dependents.removeAll(mod.name); // if there are no longer any dependents, let's disable the mod if (dependencyMod.effectively_hidden && dependents.isEmpty()) { setMod(dependencyMod, dependencyIndex, false, shouldEmit); } } } // disable mods that depend on this one, if disabling if (!enable) { auto dependents = m_dependents[mod.name]; for (const auto& dependencyName : dependents) { auto dependencyIndex = m_index[dependencyName]; auto dependencyMod = m_mods.at(dependencyIndex); setMod(dependencyMod, dependencyIndex, false, shouldEmit); } } if (shouldEmit) { emit dataChanged(AtlOptionalModListModel::index(index, EnabledColumn), AtlOptionalModListModel::index(index, EnabledColumn)); } } AtlOptionalModDialog::AtlOptionalModDialog(QWidget* parent, ATLauncher::PackVersion version, QVector<ATLauncher::VersionMod> mods) : QDialog(parent), ui(new Ui::AtlOptionalModDialog) { ui->setupUi(this); listModel = new AtlOptionalModListModel(this, version, mods); ui->treeView->setModel(listModel); ui->treeView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); ui->treeView->header()->setSectionResizeMode(AtlOptionalModListModel::NameColumn, QHeaderView::ResizeToContents); ui->treeView->header()->setSectionResizeMode(AtlOptionalModListModel::DescriptionColumn, QHeaderView::Stretch); connect(ui->shareCodeButton, &QPushButton::clicked, this, &AtlOptionalModDialog::useShareCode); connect(ui->selectRecommendedButton, &QPushButton::clicked, listModel, &AtlOptionalModListModel::selectRecommended); connect(ui->clearAllButton, &QPushButton::clicked, listModel, &AtlOptionalModListModel::clearAll); connect(ui->installButton, &QPushButton::clicked, this, &QDialog::accept); } AtlOptionalModDialog::~AtlOptionalModDialog() { delete ui; } void AtlOptionalModDialog::useShareCode() { bool ok; auto shareCode = QInputDialog::getText(this, tr("Select a share code"), tr("Share code:"), QLineEdit::Normal, "", &ok); if (!ok) { // If the user cancels the dialog, we don't need to show any error dialogs. return; } if (shareCode.isEmpty()) { QMessageBox box; box.setIcon(QMessageBox::Warning); box.setText(tr("No share code specified!")); box.exec(); return; } listModel->useShareCode(shareCode); }
11,838
C++
.cpp
297
34.060606
138
0.67169
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,982
AtlFilterModel.cpp
PrismLauncher_PrismLauncher/launcher/ui/pages/modplatform/atlauncher/AtlFilterModel.cpp
/* * Copyright 2020-2021 Jamie Mansfield <jmansfield@cadixdev.org> * * 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 "AtlFilterModel.h" #include <QDebug> #include <Version.h> #include <modplatform/atlauncher/ATLPackIndex.h> #include "StringUtils.h" namespace Atl { FilterModel::FilterModel(QObject* parent) : QSortFilterProxyModel(parent) { currentSorting = Sorting::ByPopularity; sortings.insert(tr("Sort by Popularity"), Sorting::ByPopularity); sortings.insert(tr("Sort by Name"), Sorting::ByName); sortings.insert(tr("Sort by Game Version"), Sorting::ByGameVersion); searchTerm = ""; } const QMap<QString, FilterModel::Sorting> FilterModel::getAvailableSortings() { return sortings; } QString FilterModel::translateCurrentSorting() { return sortings.key(currentSorting); } void FilterModel::setSorting(Sorting sorting) { currentSorting = sorting; invalidate(); } FilterModel::Sorting FilterModel::getCurrentSorting() { return currentSorting; } void FilterModel::setSearchTerm(const QString term) { searchTerm = term.trimmed(); invalidate(); } bool FilterModel::filterAcceptsRow(int sourceRow, const QModelIndex& sourceParent) const { if (searchTerm.isEmpty()) { return true; } QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent); ATLauncher::IndexedPack pack = sourceModel()->data(index, Qt::UserRole).value<ATLauncher::IndexedPack>(); if (searchTerm.startsWith("#")) return QString::number(pack.id) == searchTerm.mid(1); return pack.name.contains(searchTerm, Qt::CaseInsensitive); } bool FilterModel::lessThan(const QModelIndex& left, const QModelIndex& right) const { ATLauncher::IndexedPack leftPack = sourceModel()->data(left, Qt::UserRole).value<ATLauncher::IndexedPack>(); ATLauncher::IndexedPack rightPack = sourceModel()->data(right, Qt::UserRole).value<ATLauncher::IndexedPack>(); if (currentSorting == ByPopularity) { return leftPack.position > rightPack.position; } else if (currentSorting == ByGameVersion) { Version lv(leftPack.versions.at(0).minecraft); Version rv(rightPack.versions.at(0).minecraft); return lv < rv; } else if (currentSorting == ByName) { return StringUtils::naturalCompare(leftPack.name, rightPack.name, Qt::CaseSensitive) >= 0; } // Invalid sorting set, somehow... qWarning() << "Invalid sorting set!"; return true; } } // namespace Atl
2,995
C++
.cpp
80
34
114
0.739476
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
28,983
AtlUserInteractionSupportImpl.cpp
PrismLauncher_PrismLauncher/launcher/ui/pages/modplatform/atlauncher/AtlUserInteractionSupportImpl.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 Jamie Mansfield <jmansfield@cadixdev.org> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2020-2021 Jamie Mansfield <jmansfield@cadixdev.org> * * 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 "AtlUserInteractionSupportImpl.h" #include <QMessageBox> #include "AtlOptionalModDialog.h" #include "ui/dialogs/VersionSelectDialog.h" AtlUserInteractionSupportImpl::AtlUserInteractionSupportImpl(QWidget* parent) : m_parent(parent) {} std::optional<QVector<QString>> AtlUserInteractionSupportImpl::chooseOptionalMods(ATLauncher::PackVersion version, QVector<ATLauncher::VersionMod> mods) { AtlOptionalModDialog optionalModDialog(m_parent, version, mods); auto result = optionalModDialog.exec(); if (result == QDialog::Rejected) { return {}; } return optionalModDialog.getResult(); } QString AtlUserInteractionSupportImpl::chooseVersion(Meta::VersionList::Ptr vlist, QString minecraftVersion) { VersionSelectDialog vselect(vlist.get(), "Choose Version", m_parent, false); if (minecraftVersion != nullptr) { vselect.setExactFilter(BaseVersionList::ParentVersionRole, minecraftVersion); vselect.setEmptyString(tr("No versions are currently available for Minecraft %1").arg(minecraftVersion)); } else { vselect.setEmptyString(tr("No versions are currently available")); } vselect.setEmptyErrorString(tr("Couldn't load or download the version lists!")); // select recommended build for (int i = 0; i < vlist->versions().size(); i++) { auto version = vlist->versions().at(i); auto reqs = version->requiredSet(); // filter by minecraft version, if the loader depends on a certain version. if (minecraftVersion != nullptr) { auto iter = std::find_if(reqs.begin(), reqs.end(), [](const Meta::Require& req) { return req.uid == "net.minecraft"; }); if (iter == reqs.end()) continue; if (iter->equalsVersion != minecraftVersion) continue; } // first recommended build we find, we use. if (version->isRecommended()) { vselect.setCurrentVersion(version->descriptor()); break; } } vselect.exec(); return vselect.selectedVersion()->descriptor(); } void AtlUserInteractionSupportImpl::displayMessage(QString message) { QMessageBox::information(m_parent, tr("Installing"), message); }
3,839
C++
.cpp
84
40.22619
132
0.697196
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,984
FlameResourcePages.cpp
PrismLauncher_PrismLauncher/launcher/ui/pages/modplatform/flame/FlameResourcePages.cpp
// SPDX-FileCopyrightText: 2023 flowln <flowlnlnln@gmail.com> // // SPDX-License-Identifier: GPL-3.0-only AND Apache-2.0 /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * Copyright (C) 2022 TheKodeToad <TheKodeToad@proton.me> * Copyright (c) 2023 Trial97 <alexandru.tripon97@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 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 "FlameResourcePages.h" #include <QList> #include <memory> #include "modplatform/ModIndex.h" #include "modplatform/flame/FlameAPI.h" #include "ui_ResourcePage.h" #include "FlameResourceModels.h" #include "ui/dialogs/ResourceDownloadDialog.h" namespace ResourceDownload { FlameModPage::FlameModPage(ModDownloadDialog* dialog, BaseInstance& instance) : ModPage(dialog, instance) { m_model = new FlameModModel(instance); m_ui->packView->setModel(m_model); addSortings(); // sometimes Qt just ignores virtual slots and doesn't work as intended it seems, // so it's best not to connect them in the parent's contructor... connect(m_ui->sortByBox, SIGNAL(currentIndexChanged(int)), this, SLOT(triggerSearch())); connect(m_ui->packView->selectionModel(), &QItemSelectionModel::currentChanged, this, &FlameModPage::onSelectionChanged); connect(m_ui->versionSelectionBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &FlameModPage::onVersionSelectionChanged); connect(m_ui->resourceSelectionButton, &QPushButton::clicked, this, &FlameModPage::onResourceSelected); m_ui->packDescription->setMetaEntry(metaEntryBase()); } void FlameModPage::openUrl(const QUrl& url) { if (url.scheme().isEmpty()) { QString query = url.query(QUrl::FullyDecoded); if (query.startsWith("remoteUrl=")) { // attempt to resolve url from warning page query.remove(0, 10); ModPage::openUrl({ QUrl::fromPercentEncoding(query.toUtf8()) }); // double decoding is necessary return; } } ModPage::openUrl(url); } FlameResourcePackPage::FlameResourcePackPage(ResourcePackDownloadDialog* dialog, BaseInstance& instance) : ResourcePackResourcePage(dialog, instance) { m_model = new FlameResourcePackModel(instance); m_ui->packView->setModel(m_model); addSortings(); // sometimes Qt just ignores virtual slots and doesn't work as intended it seems, // so it's best not to connect them in the parent's contructor... connect(m_ui->sortByBox, SIGNAL(currentIndexChanged(int)), this, SLOT(triggerSearch())); connect(m_ui->packView->selectionModel(), &QItemSelectionModel::currentChanged, this, &FlameResourcePackPage::onSelectionChanged); connect(m_ui->versionSelectionBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &FlameResourcePackPage::onVersionSelectionChanged); connect(m_ui->resourceSelectionButton, &QPushButton::clicked, this, &FlameResourcePackPage::onResourceSelected); m_ui->packDescription->setMetaEntry(metaEntryBase()); } void FlameResourcePackPage::openUrl(const QUrl& url) { if (url.scheme().isEmpty()) { QString query = url.query(QUrl::FullyDecoded); if (query.startsWith("remoteUrl=")) { // attempt to resolve url from warning page query.remove(0, 10); ResourcePackResourcePage::openUrl({ QUrl::fromPercentEncoding(query.toUtf8()) }); // double decoding is necessary return; } } ResourcePackResourcePage::openUrl(url); } FlameTexturePackPage::FlameTexturePackPage(TexturePackDownloadDialog* dialog, BaseInstance& instance) : TexturePackResourcePage(dialog, instance) { m_model = new FlameTexturePackModel(instance); m_ui->packView->setModel(m_model); addSortings(); // sometimes Qt just ignores virtual slots and doesn't work as intended it seems, // so it's best not to connect them in the parent's contructor... connect(m_ui->sortByBox, SIGNAL(currentIndexChanged(int)), this, SLOT(triggerSearch())); connect(m_ui->packView->selectionModel(), &QItemSelectionModel::currentChanged, this, &FlameTexturePackPage::onSelectionChanged); connect(m_ui->versionSelectionBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &FlameTexturePackPage::onVersionSelectionChanged); connect(m_ui->resourceSelectionButton, &QPushButton::clicked, this, &FlameTexturePackPage::onResourceSelected); m_ui->packDescription->setMetaEntry(metaEntryBase()); } void FlameTexturePackPage::openUrl(const QUrl& url) { if (url.scheme().isEmpty()) { QString query = url.query(QUrl::FullyDecoded); if (query.startsWith("remoteUrl=")) { // attempt to resolve url from warning page query.remove(0, 10); ResourcePackResourcePage::openUrl({ QUrl::fromPercentEncoding(query.toUtf8()) }); // double decoding is necessary return; } } TexturePackResourcePage::openUrl(url); } FlameShaderPackPage::FlameShaderPackPage(ShaderPackDownloadDialog* dialog, BaseInstance& instance) : ShaderPackResourcePage(dialog, instance) { m_model = new FlameShaderPackModel(instance); m_ui->packView->setModel(m_model); addSortings(); // sometimes Qt just ignores virtual slots and doesn't work as intended it seems, // so it's best not to connect them in the parent's constructor... connect(m_ui->sortByBox, SIGNAL(currentIndexChanged(int)), this, SLOT(triggerSearch())); connect(m_ui->packView->selectionModel(), &QItemSelectionModel::currentChanged, this, &FlameShaderPackPage::onSelectionChanged); connect(m_ui->versionSelectionBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &FlameShaderPackPage::onVersionSelectionChanged); connect(m_ui->resourceSelectionButton, &QPushButton::clicked, this, &FlameShaderPackPage::onResourceSelected); m_ui->packDescription->setMetaEntry(metaEntryBase()); } void FlameShaderPackPage::openUrl(const QUrl& url) { if (url.scheme().isEmpty()) { QString query = url.query(QUrl::FullyDecoded); if (query.startsWith("remoteUrl=")) { // attempt to resolve url from warning page query.remove(0, 10); ShaderPackResourcePage::openUrl({ QUrl::fromPercentEncoding(query.toUtf8()) }); // double decoding is necessary return; } } ShaderPackResourcePage::openUrl(url); } // I don't know why, but doing this on the parent class makes it so that // other mod providers start loading before being selected, at least with // my Qt, so we need to implement this in every derived class... auto FlameModPage::shouldDisplay() const -> bool { return true; } auto FlameResourcePackPage::shouldDisplay() const -> bool { return true; } auto FlameTexturePackPage::shouldDisplay() const -> bool { return true; } auto FlameShaderPackPage::shouldDisplay() const -> bool { return true; } unique_qobject_ptr<ModFilterWidget> FlameModPage::createFilterWidget() { return ModFilterWidget::create(&static_cast<MinecraftInstance&>(m_baseInstance), false, this); } void FlameModPage::prepareProviderCategories() { auto response = std::make_shared<QByteArray>(); m_categoriesTask = FlameAPI::getModCategories(response); QObject::connect(m_categoriesTask.get(), &Task::succeeded, [this, response]() { auto categories = FlameAPI::loadModCategories(response); m_filter_widget->setCategories(categories); }); m_categoriesTask->start(); }; } // namespace ResourceDownload
8,873
C++
.cpp
191
41.958115
140
0.731152
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,985
FlamePage.cpp
PrismLauncher_PrismLauncher/launcher/ui/pages/modplatform/flame/FlamePage.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 Jamie Mansfield <jmansfield@cadixdev.org> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 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 "FlamePage.h" #include "Version.h" #include "modplatform/flame/FlamePackIndex.h" #include "ui/dialogs/CustomMessageBox.h" #include "ui/widgets/ModFilterWidget.h" #include "ui_FlamePage.h" #include <QKeyEvent> #include <memory> #include "Application.h" #include "FlameModel.h" #include "InstanceImportTask.h" #include "Json.h" #include "StringUtils.h" #include "modplatform/flame/FlameAPI.h" #include "ui/dialogs/NewInstanceDialog.h" #include "ui/widgets/ProjectItem.h" #include "net/ApiDownload.h" static FlameAPI api; FlamePage::FlamePage(NewInstanceDialog* dialog, QWidget* parent) : QWidget(parent), ui(new Ui::FlamePage), dialog(dialog), m_fetch_progress(this, false) { ui->setupUi(this); ui->searchEdit->installEventFilter(this); listModel = new Flame::ListModel(this); ui->packView->setModel(listModel); ui->versionSelectionBox->view()->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); ui->versionSelectionBox->view()->parentWidget()->setMaximumHeight(300); m_search_timer.setTimerType(Qt::TimerType::CoarseTimer); m_search_timer.setSingleShot(true); connect(&m_search_timer, &QTimer::timeout, this, &FlamePage::triggerSearch); m_fetch_progress.hideIfInactive(true); m_fetch_progress.setFixedHeight(24); m_fetch_progress.progressFormat(""); ui->verticalLayout->insertWidget(2, &m_fetch_progress); // index is used to set the sorting with the curseforge api ui->sortByBox->addItem(tr("Sort by Featured")); ui->sortByBox->addItem(tr("Sort by Popularity")); ui->sortByBox->addItem(tr("Sort by Last Updated")); ui->sortByBox->addItem(tr("Sort by Name")); ui->sortByBox->addItem(tr("Sort by Author")); ui->sortByBox->addItem(tr("Sort by Total Downloads")); connect(ui->sortByBox, SIGNAL(currentIndexChanged(int)), this, SLOT(triggerSearch())); connect(ui->packView->selectionModel(), &QItemSelectionModel::currentChanged, this, &FlamePage::onSelectionChanged); connect(ui->versionSelectionBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &FlamePage::onVersionSelectionChanged); ui->packView->setItemDelegate(new ProjectItemDelegate(this)); ui->packDescription->setMetaEntry("FlamePacks"); createFilterWidget(); } FlamePage::~FlamePage() { delete ui; } bool FlamePage::eventFilter(QObject* watched, QEvent* event) { if (watched == ui->searchEdit && event->type() == QEvent::KeyPress) { QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event); if (keyEvent->key() == Qt::Key_Return) { triggerSearch(); keyEvent->accept(); return true; } else { if (m_search_timer.isActive()) m_search_timer.stop(); m_search_timer.start(350); } } return QWidget::eventFilter(watched, event); } bool FlamePage::shouldDisplay() const { return true; } void FlamePage::retranslate() { ui->retranslateUi(this); } void FlamePage::openedImpl() { suggestCurrent(); triggerSearch(); } void FlamePage::triggerSearch() { ui->packView->selectionModel()->setCurrentIndex({}, QItemSelectionModel::SelectionFlag::ClearAndSelect); ui->packView->clearSelection(); ui->packDescription->clear(); ui->versionSelectionBox->clear(); listModel->searchWithTerm(ui->searchEdit->text(), ui->sortByBox->currentIndex(), m_filterWidget->getFilter(), m_filterWidget->changed()); m_fetch_progress.watch(listModel->activeSearchJob().get()); } bool checkVersionFilters(const Flame::IndexedVersion& v, std::shared_ptr<ModFilterWidget::Filter> filter) { if (!filter) return true; return ((!filter->loaders || !v.loaders || filter->loaders & v.loaders) && // loaders (filter->releases.empty() || // releases std::find(filter->releases.cbegin(), filter->releases.cend(), v.version_type) != filter->releases.cend()) && filter->checkMcVersions({ v.mcVersion })); // mcVersions} } void FlamePage::onSelectionChanged(QModelIndex curr, [[maybe_unused]] QModelIndex prev) { ui->versionSelectionBox->clear(); if (!curr.isValid()) { if (isOpened) { dialog->setSuggestedPack(); } return; } current = listModel->data(curr, Qt::UserRole).value<Flame::IndexedPack>(); if (!current.versionsLoaded || m_filterWidget->changed()) { qDebug() << "Loading flame modpack versions"; auto netJob = new NetJob(QString("Flame::PackVersions(%1)").arg(current.name), APPLICATION->network()); auto response = std::make_shared<QByteArray>(); int addonId = current.addonId; netJob->addNetAction( Net::ApiDownload::makeByteArray(QString("https://api.curseforge.com/v1/mods/%1/files").arg(addonId), response)); QObject::connect(netJob, &NetJob::succeeded, this, [this, response, addonId, curr] { if (addonId != current.addonId) { return; // wrong request } QJsonParseError parse_error; QJsonDocument doc = QJsonDocument::fromJson(*response, &parse_error); if (parse_error.error != QJsonParseError::NoError) { qWarning() << "Error while parsing JSON response from CurseForge at " << parse_error.offset << " reason: " << parse_error.errorString(); qWarning() << *response; return; } auto arr = Json::ensureArray(doc.object(), "data"); try { Flame::loadIndexedPackVersions(current, arr); } catch (const JSONValidationError& e) { qDebug() << *response; qWarning() << "Error while reading flame modpack version: " << e.cause(); } auto pred = [this](const Flame::IndexedVersion& v) { return !checkVersionFilters(v, m_filterWidget->getFilter()); }; #if QT_VERSION >= QT_VERSION_CHECK(6, 1, 0) current.versions.removeIf(pred); #else for (auto it = current.versions.begin(); it != current.versions.end();) if (pred(*it)) it = current.versions.erase(it); else ++it; #endif for (auto version : current.versions) { auto release_type = version.version_type.isValid() ? QString(" [%1]").arg(version.version_type.toString()) : ""; auto mcVersion = !version.mcVersion.isEmpty() && !version.version.contains(version.mcVersion) ? QString(" for %1").arg(version.mcVersion) : ""; ui->versionSelectionBox->addItem(QString("%1%2%3").arg(version.version, mcVersion, release_type), QVariant(version.downloadUrl)); } QVariant current_updated; current_updated.setValue(current); if (!listModel->setData(curr, current_updated, Qt::UserRole)) qWarning() << "Failed to cache versions for the current pack!"; // TODO: Check whether it's a connection issue or the project disabled 3rd-party distribution. if (current.versionsLoaded && ui->versionSelectionBox->count() < 1) { ui->versionSelectionBox->addItem(tr("No version is available!"), -1); } suggestCurrent(); }); QObject::connect(netJob, &NetJob::finished, this, [response, netJob] { netJob->deleteLater(); }); connect(netJob, &NetJob::failed, [this](QString reason) { CustomMessageBox::selectable(this, tr("Error"), reason, QMessageBox::Critical)->exec(); }); netJob->start(); } else { for (auto version : current.versions) { ui->versionSelectionBox->addItem(version.version, QVariant(version.downloadUrl)); } suggestCurrent(); } // TODO: Check whether it's a connection issue or the project disabled 3rd-party distribution. if (current.versionsLoaded && ui->versionSelectionBox->count() < 1) { ui->versionSelectionBox->addItem(tr("No version is available!"), -1); } updateUi(); } void FlamePage::suggestCurrent() { if (!isOpened) { return; } if (m_selected_version_index == -1) { dialog->setSuggestedPack(); return; } auto version = current.versions.at(m_selected_version_index); QMap<QString, QString> extra_info; extra_info.insert("pack_id", QString::number(current.addonId)); extra_info.insert("pack_version_id", QString::number(version.fileId)); dialog->setSuggestedPack(current.name, new InstanceImportTask(version.downloadUrl, this, std::move(extra_info))); QString editedLogoName = "curseforge_" + current.logoName; listModel->getLogo(current.logoName, current.logoUrl, [this, editedLogoName](QString logo) { dialog->setSuggestedIconFromFile(logo, editedLogoName); }); } void FlamePage::onVersionSelectionChanged(int index) { bool is_blocked = false; ui->versionSelectionBox->itemData(index).toInt(&is_blocked); if (index == -1 || is_blocked) { m_selected_version_index = -1; return; } m_selected_version_index = index; Q_ASSERT(current.versions.at(m_selected_version_index).downloadUrl == ui->versionSelectionBox->currentData().toString()); suggestCurrent(); } void FlamePage::updateUi() { QString text = ""; QString name = current.name; if (current.extra.websiteUrl.isEmpty()) text = name; else text = "<a href=\"" + current.extra.websiteUrl + "\">" + name + "</a>"; if (!current.authors.empty()) { auto authorToStr = [](Flame::ModpackAuthor& author) { if (author.url.isEmpty()) { return author.name; } return QString("<a href=\"%1\">%2</a>").arg(author.url, author.name); }; QStringList authorStrs; for (auto& author : current.authors) { authorStrs.push_back(authorToStr(author)); } text += "<br>" + tr(" by ") + authorStrs.join(", "); } if (current.extraInfoLoaded) { if (!current.extra.issuesUrl.isEmpty() || !current.extra.sourceUrl.isEmpty() || !current.extra.wikiUrl.isEmpty()) { text += "<br><br>" + tr("External links:") + "<br>"; } if (!current.extra.issuesUrl.isEmpty()) text += "- " + tr("Issues: <a href=%1>%1</a>").arg(current.extra.issuesUrl) + "<br>"; if (!current.extra.wikiUrl.isEmpty()) text += "- " + tr("Wiki: <a href=%1>%1</a>").arg(current.extra.wikiUrl) + "<br>"; if (!current.extra.sourceUrl.isEmpty()) text += "- " + tr("Source code: <a href=%1>%1</a>").arg(current.extra.sourceUrl) + "<br>"; } text += "<hr>"; text += api.getModDescription(current.addonId).toUtf8(); ui->packDescription->setHtml(StringUtils::htmlListPatch(text + current.description)); ui->packDescription->flush(); } QString FlamePage::getSerachTerm() const { return ui->searchEdit->text(); } void FlamePage::setSearchTerm(QString term) { ui->searchEdit->setText(term); } void FlamePage::createFilterWidget() { auto widget = ModFilterWidget::create(nullptr, false, this); m_filterWidget.swap(widget); auto old = ui->splitter->replaceWidget(0, m_filterWidget.get()); // because we replaced the widget we also need to delete it if (old) { delete old; } connect(ui->filterButton, &QPushButton::clicked, this, [this] { m_filterWidget->setHidden(!m_filterWidget->isHidden()); }); connect(m_filterWidget.get(), &ModFilterWidget::filterChanged, this, &FlamePage::triggerSearch); auto response = std::make_shared<QByteArray>(); m_categoriesTask = FlameAPI::getCategories(response, ModPlatform::ResourceType::MODPACK); QObject::connect(m_categoriesTask.get(), &Task::succeeded, [this, response]() { auto categories = FlameAPI::loadModCategories(response); m_filterWidget->setCategories(categories); }); m_categoriesTask->start(); }
13,691
C++
.cpp
308
37.626623
135
0.651137
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,986
FlameModel.cpp
PrismLauncher_PrismLauncher/launcher/ui/pages/modplatform/flame/FlameModel.cpp
#include "FlameModel.h" #include <Json.h> #include "Application.h" #include "modplatform/ModIndex.h" #include "modplatform/ResourceAPI.h" #include "modplatform/flame/FlameAPI.h" #include "ui/widgets/ProjectItem.h" #include "net/ApiDownload.h" #include <Version.h> #include <QtMath> namespace Flame { ListModel::ListModel(QObject* parent) : QAbstractListModel(parent) {} ListModel::~ListModel() {} int ListModel::rowCount(const QModelIndex& parent) const { return parent.isValid() ? 0 : modpacks.size(); } int ListModel::columnCount(const QModelIndex& parent) const { return parent.isValid() ? 0 : 1; } QVariant ListModel::data(const QModelIndex& index, int role) const { int pos = index.row(); if (pos >= modpacks.size() || pos < 0 || !index.isValid()) { return QString("INVALID INDEX %1").arg(pos); } IndexedPack pack = modpacks.at(pos); switch (role) { case Qt::ToolTipRole: { if (pack.description.length() > 100) { // some magic to prevent to long tooltips and replace html linebreaks QString edit = pack.description.left(97); edit = edit.left(edit.lastIndexOf("<br>")).left(edit.lastIndexOf(" ")).append("..."); return edit; } return pack.description; } case Qt::DecorationRole: { if (m_logoMap.contains(pack.logoName)) { return (m_logoMap.value(pack.logoName)); } QIcon icon = APPLICATION->getThemedIcon("screenshot-placeholder"); ((ListModel*)this)->requestLogo(pack.logoName, pack.logoUrl); return icon; } case Qt::UserRole: { QVariant v; v.setValue(pack); return v; } case Qt::SizeHintRole: return QSize(0, 58); case UserDataTypes::TITLE: return pack.name; case UserDataTypes::DESCRIPTION: return pack.description; case UserDataTypes::SELECTED: return false; case UserDataTypes::INSTALLED: return false; default: break; } return QVariant(); } bool ListModel::setData(const QModelIndex& index, const QVariant& value, [[maybe_unused]] int role) { int pos = index.row(); if (pos >= modpacks.size() || pos < 0 || !index.isValid()) return false; modpacks[pos] = value.value<Flame::IndexedPack>(); return true; } void ListModel::logoLoaded(QString logo, QIcon out) { m_loadingLogos.removeAll(logo); m_logoMap.insert(logo, out); for (int i = 0; i < modpacks.size(); i++) { if (modpacks[i].logoName == logo) { emit dataChanged(createIndex(i, 0), createIndex(i, 0), { Qt::DecorationRole }); } } } void ListModel::logoFailed(QString logo) { m_failedLogos.append(logo); m_loadingLogos.removeAll(logo); } void ListModel::requestLogo(QString logo, QString url) { if (m_loadingLogos.contains(logo) || m_failedLogos.contains(logo)) { return; } MetaEntryPtr entry = APPLICATION->metacache()->resolveEntry("FlamePacks", QString("logos/%1").arg(logo)); auto job = new NetJob(QString("Flame Icon Download %1").arg(logo), APPLICATION->network()); job->setAskRetry(false); job->addNetAction(Net::ApiDownload::makeCached(QUrl(url), entry)); auto fullPath = entry->getFullPath(); QObject::connect(job, &NetJob::succeeded, this, [this, logo, fullPath, job] { job->deleteLater(); emit logoLoaded(logo, QIcon(fullPath)); if (waitingCallbacks.contains(logo)) { waitingCallbacks.value(logo)(fullPath); } }); QObject::connect(job, &NetJob::failed, this, [this, logo, job] { job->deleteLater(); emit logoFailed(logo); }); job->start(); m_loadingLogos.append(logo); } void ListModel::getLogo(const QString& logo, const QString& logoUrl, LogoCallback callback) { if (m_logoMap.contains(logo)) { callback(APPLICATION->metacache()->resolveEntry("FlamePacks", QString("logos/%1").arg(logo))->getFullPath()); } else { requestLogo(logo, logoUrl); } } Qt::ItemFlags ListModel::flags(const QModelIndex& index) const { return QAbstractListModel::flags(index); } bool ListModel::canFetchMore([[maybe_unused]] const QModelIndex& parent) const { return searchState == CanPossiblyFetchMore; } void ListModel::fetchMore(const QModelIndex& parent) { if (parent.isValid()) return; if (nextSearchOffset == 0) { qWarning() << "fetchMore with 0 offset is wrong..."; return; } performPaginatedSearch(); } void ListModel::performPaginatedSearch() { if (currentSearchTerm.startsWith("#")) { auto projectId = currentSearchTerm.mid(1); if (!projectId.isEmpty()) { ResourceAPI::ProjectInfoCallbacks callbacks; callbacks.on_fail = [this](QString reason) { searchRequestFailed(reason); }; callbacks.on_succeed = [this](auto& doc, auto& pack) { searchRequestForOneSucceeded(doc); }; callbacks.on_abort = [this] { qCritical() << "Search task aborted by an unknown reason!"; searchRequestFailed("Aborted"); }; static const FlameAPI api; if (auto job = api.getProjectInfo({ projectId }, std::move(callbacks)); job) { jobPtr = job; jobPtr->start(); } return; } } ResourceAPI::SortingMethod sort{}; sort.index = currentSort + 1; auto netJob = makeShared<NetJob>("Flame::Search", APPLICATION->network()); auto searchUrl = FlameAPI().getSearchURL({ ModPlatform::ResourceType::MODPACK, nextSearchOffset, currentSearchTerm, sort, m_filter->loaders, m_filter->versions, "", m_filter->categoryIds, m_filter->openSource }); netJob->addNetAction(Net::ApiDownload::makeByteArray(QUrl(searchUrl.value()), response)); jobPtr = netJob; jobPtr->start(); QObject::connect(netJob.get(), &NetJob::succeeded, this, &ListModel::searchRequestFinished); QObject::connect(netJob.get(), &NetJob::failed, this, &ListModel::searchRequestFailed); } void ListModel::searchWithTerm(const QString& term, int sort, std::shared_ptr<ModFilterWidget::Filter> filter, bool filterChanged) { if (currentSearchTerm == term && currentSearchTerm.isNull() == term.isNull() && currentSort == sort && !filterChanged) { return; } currentSearchTerm = term; currentSort = sort; m_filter = filter; if (hasActiveSearchJob()) { jobPtr->abort(); searchState = ResetRequested; return; } beginResetModel(); modpacks.clear(); endResetModel(); searchState = None; nextSearchOffset = 0; performPaginatedSearch(); } void Flame::ListModel::searchRequestFinished() { if (hasActiveSearchJob()) return; QJsonParseError parse_error; QJsonDocument doc = QJsonDocument::fromJson(*response, &parse_error); if (parse_error.error != QJsonParseError::NoError) { qWarning() << "Error while parsing JSON response from CurseForge at " << parse_error.offset << " reason: " << parse_error.errorString(); qWarning() << *response; return; } QList<Flame::IndexedPack> newList; auto packs = Json::ensureArray(doc.object(), "data"); for (auto packRaw : packs) { auto packObj = packRaw.toObject(); Flame::IndexedPack pack; try { Flame::loadIndexedPack(pack, packObj); newList.append(pack); } catch (const JSONValidationError& e) { qWarning() << "Error while loading pack from CurseForge: " << e.cause(); continue; } } if (packs.size() < 25) { searchState = Finished; } else { nextSearchOffset += 25; searchState = CanPossiblyFetchMore; } // When you have a Qt build with assertions turned on, proceeding here will abort the application if (newList.size() == 0) return; beginInsertRows(QModelIndex(), modpacks.size(), modpacks.size() + newList.size() - 1); modpacks.append(newList); endInsertRows(); } void Flame::ListModel::searchRequestForOneSucceeded(QJsonDocument& doc) { jobPtr.reset(); auto packObj = Json::ensureObject(doc.object(), "data"); Flame::IndexedPack pack; try { Flame::loadIndexedPack(pack, packObj); } catch (const JSONValidationError& e) { qWarning() << "Error while loading pack from CurseForge: " << e.cause(); return; } beginInsertRows(QModelIndex(), modpacks.size(), modpacks.size() + 1); modpacks.append({ pack }); endInsertRows(); } void Flame::ListModel::searchRequestFailed(QString reason) { jobPtr.reset(); if (searchState == ResetRequested) { beginResetModel(); modpacks.clear(); endResetModel(); nextSearchOffset = 0; performPaginatedSearch(); } else { searchState = Finished; } } } // namespace Flame
9,176
C++
.cpp
257
28.964981
137
0.637818
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
28,987
FlameResourceModels.cpp
PrismLauncher_PrismLauncher/launcher/ui/pages/modplatform/flame/FlameResourceModels.cpp
// SPDX-FileCopyrightText: 2023 flowln <flowlnlnln@gmail.com> // // SPDX-License-Identifier: GPL-3.0-only #include "FlameResourceModels.h" #include "Json.h" #include "minecraft/PackProfile.h" #include "modplatform/flame/FlameAPI.h" #include "modplatform/flame/FlameModIndex.h" namespace ResourceDownload { static bool isOptedOut(const ModPlatform::IndexedVersion& ver) { return ver.downloadUrl.isEmpty(); } FlameModModel::FlameModModel(BaseInstance& base) : ModModel(base, new FlameAPI) {} void FlameModModel::loadIndexedPack(ModPlatform::IndexedPack& m, QJsonObject& obj) { FlameMod::loadIndexedPack(m, obj); } // We already deal with the URLs when initializing the pack, due to the API response's structure void FlameModModel::loadExtraPackInfo(ModPlatform::IndexedPack& m, QJsonObject& obj) { FlameMod::loadBody(m, obj); } void FlameModModel::loadIndexedPackVersions(ModPlatform::IndexedPack& m, QJsonArray& arr) { FlameMod::loadIndexedPackVersions(m, arr, APPLICATION->network(), &m_base_instance); } auto FlameModModel::loadDependencyVersions(const ModPlatform::Dependency& m, QJsonArray& arr) -> ModPlatform::IndexedVersion { return FlameMod::loadDependencyVersions(m, arr, &m_base_instance); } bool FlameModModel::optedOut(const ModPlatform::IndexedVersion& ver) const { return isOptedOut(ver); } auto FlameModModel::documentToArray(QJsonDocument& obj) const -> QJsonArray { return Json::ensureArray(obj.object(), "data"); } FlameResourcePackModel::FlameResourcePackModel(const BaseInstance& base) : ResourcePackResourceModel(base, new FlameAPI) {} void FlameResourcePackModel::loadIndexedPack(ModPlatform::IndexedPack& m, QJsonObject& obj) { FlameMod::loadIndexedPack(m, obj); } // We already deal with the URLs when initializing the pack, due to the API response's structure void FlameResourcePackModel::loadExtraPackInfo(ModPlatform::IndexedPack& m, QJsonObject& obj) { FlameMod::loadBody(m, obj); } void FlameResourcePackModel::loadIndexedPackVersions(ModPlatform::IndexedPack& m, QJsonArray& arr) { FlameMod::loadIndexedPackVersions(m, arr, APPLICATION->network(), &m_base_instance); } bool FlameResourcePackModel::optedOut(const ModPlatform::IndexedVersion& ver) const { return isOptedOut(ver); } auto FlameResourcePackModel::documentToArray(QJsonDocument& obj) const -> QJsonArray { return Json::ensureArray(obj.object(), "data"); } FlameTexturePackModel::FlameTexturePackModel(const BaseInstance& base) : TexturePackResourceModel(base, new FlameAPI) {} void FlameTexturePackModel::loadIndexedPack(ModPlatform::IndexedPack& m, QJsonObject& obj) { FlameMod::loadIndexedPack(m, obj); } // We already deal with the URLs when initializing the pack, due to the API response's structure void FlameTexturePackModel::loadExtraPackInfo(ModPlatform::IndexedPack& m, QJsonObject& obj) { FlameMod::loadBody(m, obj); } void FlameTexturePackModel::loadIndexedPackVersions(ModPlatform::IndexedPack& m, QJsonArray& arr) { FlameMod::loadIndexedPackVersions(m, arr, APPLICATION->network(), &m_base_instance); QVector<ModPlatform::IndexedVersion> filtered_versions(m.versions.size()); // FIXME: Client-side version filtering. This won't take into account any user-selected filtering. for (auto const& version : m.versions) { auto const& mc_versions = version.mcVersion; if (std::any_of(mc_versions.constBegin(), mc_versions.constEnd(), [this](auto const& mc_version) { return Version(mc_version) <= maximumTexturePackVersion(); })) filtered_versions.push_back(version); } m.versions = filtered_versions; } ResourceAPI::SearchArgs FlameTexturePackModel::createSearchArguments() { auto args = TexturePackResourceModel::createSearchArguments(); auto profile = static_cast<const MinecraftInstance&>(m_base_instance).getPackProfile(); QString instance_minecraft_version = profile->getComponentVersion("net.minecraft"); // Bypass the texture pack logic, because we can't do multiple versions in the API query args.versions = { instance_minecraft_version }; return args; } ResourceAPI::VersionSearchArgs FlameTexturePackModel::createVersionsArguments(QModelIndex& entry) { auto args = TexturePackResourceModel::createVersionsArguments(entry); // Bypass the texture pack logic, because we can't do multiple versions in the API query args.mcVersions = {}; return args; } bool FlameTexturePackModel::optedOut(const ModPlatform::IndexedVersion& ver) const { return isOptedOut(ver); } auto FlameTexturePackModel::documentToArray(QJsonDocument& obj) const -> QJsonArray { return Json::ensureArray(obj.object(), "data"); } FlameShaderPackModel::FlameShaderPackModel(const BaseInstance& base) : ShaderPackResourceModel(base, new FlameAPI) {} void FlameShaderPackModel::loadIndexedPack(ModPlatform::IndexedPack& m, QJsonObject& obj) { FlameMod::loadIndexedPack(m, obj); } // We already deal with the URLs when initializing the pack, due to the API response's structure void FlameShaderPackModel::loadExtraPackInfo(ModPlatform::IndexedPack& m, QJsonObject& obj) { FlameMod::loadBody(m, obj); } void FlameShaderPackModel::loadIndexedPackVersions(ModPlatform::IndexedPack& m, QJsonArray& arr) { FlameMod::loadIndexedPackVersions(m, arr, APPLICATION->network(), &m_base_instance); } bool FlameShaderPackModel::optedOut(const ModPlatform::IndexedVersion& ver) const { return isOptedOut(ver); } auto FlameShaderPackModel::documentToArray(QJsonDocument& obj) const -> QJsonArray { return Json::ensureArray(obj.object(), "data"); } } // namespace ResourceDownload
5,678
C++
.cpp
131
40.496183
124
0.783833
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,988
ListModel.cpp
PrismLauncher_PrismLauncher/launcher/ui/pages/modplatform/legacy_ftb/ListModel.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 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 "ListModel.h" #include "Application.h" #include "net/ApiDownload.h" #include "net/HttpMetaCache.h" #include "net/NetJob.h" #include <Version.h> #include "StringUtils.h" #include "ui/widgets/ProjectItem.h" #include <QLabel> #include <QtMath> #include <RWStorage.h> #include <BuildConfig.h> namespace LegacyFTB { FilterModel::FilterModel(QObject* parent) : QSortFilterProxyModel(parent) { currentSorting = Sorting::ByGameVersion; sortings.insert(tr("Sort by Name"), Sorting::ByName); sortings.insert(tr("Sort by Game Version"), Sorting::ByGameVersion); } bool FilterModel::lessThan(const QModelIndex& left, const QModelIndex& right) const { Modpack leftPack = sourceModel()->data(left, Qt::UserRole).value<Modpack>(); Modpack rightPack = sourceModel()->data(right, Qt::UserRole).value<Modpack>(); if (currentSorting == Sorting::ByGameVersion) { Version lv(leftPack.mcVersion); Version rv(rightPack.mcVersion); return lv < rv; } else if (currentSorting == Sorting::ByName) { return StringUtils::naturalCompare(leftPack.name, rightPack.name, Qt::CaseSensitive) >= 0; } // UHM, some inavlid value set?! qWarning() << "Invalid sorting set!"; return true; } bool FilterModel::filterAcceptsRow([[maybe_unused]] int sourceRow, [[maybe_unused]] const QModelIndex& sourceParent) const { if (searchTerm.isEmpty()) { return true; } QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent); Modpack pack = sourceModel()->data(index, Qt::UserRole).value<Modpack>(); if (searchTerm.startsWith("#")) return pack.packCode == searchTerm.mid(1); return pack.name.contains(searchTerm, Qt::CaseInsensitive); } void FilterModel::setSearchTerm(const QString term) { searchTerm = term.trimmed(); invalidate(); } const QMap<QString, FilterModel::Sorting> FilterModel::getAvailableSortings() { return sortings; } QString FilterModel::translateCurrentSorting() { return sortings.key(currentSorting); } void FilterModel::setSorting(Sorting s) { currentSorting = s; invalidate(); } FilterModel::Sorting FilterModel::getCurrentSorting() { return currentSorting; } ListModel::ListModel(QObject* parent) : QAbstractListModel(parent) {} ListModel::~ListModel() {} QString ListModel::translatePackType(PackType type) const { switch (type) { case PackType::Public: return tr("Public Modpack"); case PackType::ThirdParty: return tr("Third Party Modpack"); case PackType::Private: return tr("Private Modpack"); } qWarning() << "Unknown FTB modpack type:" << int(type); return QString(); } int ListModel::rowCount(const QModelIndex& parent) const { return parent.isValid() ? 0 : modpacks.size(); } int ListModel::columnCount(const QModelIndex& parent) const { return parent.isValid() ? 0 : 1; } QVariant ListModel::data(const QModelIndex& index, int role) const { int pos = index.row(); if (pos >= modpacks.size() || pos < 0 || !index.isValid()) { return QString("INVALID INDEX %1").arg(pos); } Modpack pack = modpacks.at(pos); switch (role) { case Qt::ToolTipRole: { if (pack.description.length() > 100) { // some magic to prevent to long tooltips and replace html linebreaks QString edit = pack.description.left(97); edit = edit.left(edit.lastIndexOf("<br>")).left(edit.lastIndexOf(" ")).append("..."); return edit; } return pack.description; } case Qt::DecorationRole: { if (m_logoMap.contains(pack.logo)) { return (m_logoMap.value(pack.logo)); } QIcon icon = APPLICATION->getThemedIcon("screenshot-placeholder"); ((ListModel*)this)->requestLogo(pack.logo); return icon; } case Qt::UserRole: { QVariant v; v.setValue(pack); return v; } case Qt::ForegroundRole: { if (pack.broken) { // FIXME: Hardcoded color return QColor(255, 0, 50); } else if (pack.bugged) { // FIXME: Hardcoded color // bugged pack, currently only indicates bugged xml return QColor(244, 229, 66); } } case Qt::DisplayRole: return pack.name; case Qt::SizeHintRole: return QSize(0, 58); // Custom data case UserDataTypes::TITLE: return pack.name; case UserDataTypes::DESCRIPTION: return pack.description; case UserDataTypes::SELECTED: return false; case UserDataTypes::INSTALLED: return false; default: break; } return {}; } void ListModel::fill(ModpackList modpacks_) { beginResetModel(); this->modpacks = modpacks_; endResetModel(); } void ListModel::addPack(Modpack modpack) { beginResetModel(); this->modpacks.append(modpack); endResetModel(); } void ListModel::clear() { beginResetModel(); modpacks.clear(); endResetModel(); } Modpack ListModel::at(int row) { return modpacks.at(row); } void ListModel::remove(int row) { if (row < 0 || row >= modpacks.size()) { qWarning() << "Attempt to remove FTB modpacks with invalid row" << row; return; } beginRemoveRows(QModelIndex(), row, row); modpacks.removeAt(row); endRemoveRows(); } void ListModel::logoLoaded(QString logo, QIcon out) { m_loadingLogos.removeAll(logo); m_logoMap.insert(logo, out); emit dataChanged(createIndex(0, 0), createIndex(1, 0)); } void ListModel::logoFailed(QString logo) { m_failedLogos.append(logo); m_loadingLogos.removeAll(logo); } void ListModel::requestLogo(QString file) { if (m_loadingLogos.contains(file) || m_failedLogos.contains(file)) { return; } MetaEntryPtr entry = APPLICATION->metacache()->resolveEntry("FTBPacks", QString("logos/%1").arg(file)); NetJob* job = new NetJob(QString("FTB Icon Download for %1").arg(file), APPLICATION->network()); job->setAskRetry(false); job->addNetAction(Net::ApiDownload::makeCached(QUrl(QString(BuildConfig.LEGACY_FTB_CDN_BASE_URL + "static/%1").arg(file)), entry)); auto fullPath = entry->getFullPath(); QObject::connect(job, &NetJob::finished, this, [this, file, fullPath, job] { job->deleteLater(); emit logoLoaded(file, QIcon(fullPath)); if (waitingCallbacks.contains(file)) { waitingCallbacks.value(file)(fullPath); } }); QObject::connect(job, &NetJob::failed, this, [this, file, job] { job->deleteLater(); emit logoFailed(file); }); job->start(); m_loadingLogos.append(file); } void ListModel::getLogo(const QString& logo, LogoCallback callback) { if (m_logoMap.contains(logo)) { callback(APPLICATION->metacache()->resolveEntry("FTBPacks", QString("logos/%1").arg(logo))->getFullPath()); } else { requestLogo(logo); } } Qt::ItemFlags ListModel::flags(const QModelIndex& index) const { return QAbstractListModel::flags(index); } } // namespace LegacyFTB
8,826
C++
.cpp
262
28.39313
135
0.666549
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
28,989
Page.cpp
PrismLauncher_PrismLauncher/launcher/ui/pages/modplatform/legacy_ftb/Page.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 Jamie Mansfield <jmansfield@cadixdev.org> * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 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 "Page.h" #include "StringUtils.h" #include "ui/widgets/ProjectItem.h" #include "ui_Page.h" #include <QInputDialog> #include "Application.h" #include "ui/dialogs/CustomMessageBox.h" #include "ui/dialogs/NewInstanceDialog.h" #include "ListModel.h" #include "modplatform/legacy_ftb/PackFetchTask.h" #include "modplatform/legacy_ftb/PackInstallTask.h" #include "modplatform/legacy_ftb/PrivatePackManager.h" namespace LegacyFTB { Page::Page(NewInstanceDialog* dialog, QWidget* parent) : QWidget(parent), dialog(dialog), ui(new Ui::Page) { ftbFetchTask.reset(new PackFetchTask(APPLICATION->network())); ftbPrivatePacks.reset(new PrivatePackManager()); ui->setupUi(this); { publicFilterModel = new FilterModel(this); publicListModel = new ListModel(this); publicFilterModel->setSourceModel(publicListModel); ui->publicPackList->setModel(publicFilterModel); ui->publicPackList->setSortingEnabled(true); ui->publicPackList->header()->hide(); ui->publicPackList->setIndentation(0); ui->publicPackList->setIconSize(QSize(42, 42)); for (int i = 0; i < publicFilterModel->getAvailableSortings().size(); i++) { ui->sortByBox->addItem(publicFilterModel->getAvailableSortings().keys().at(i)); } ui->sortByBox->setCurrentText(publicFilterModel->translateCurrentSorting()); } { thirdPartyFilterModel = new FilterModel(this); thirdPartyModel = new ListModel(this); thirdPartyFilterModel->setSourceModel(thirdPartyModel); ui->thirdPartyPackList->setModel(thirdPartyFilterModel); ui->thirdPartyPackList->setSortingEnabled(true); ui->thirdPartyPackList->header()->hide(); ui->thirdPartyPackList->setIndentation(0); ui->thirdPartyPackList->setIconSize(QSize(42, 42)); thirdPartyFilterModel->setSorting(publicFilterModel->getCurrentSorting()); } { privateFilterModel = new FilterModel(this); privateListModel = new ListModel(this); privateFilterModel->setSourceModel(privateListModel); ui->privatePackList->setModel(privateFilterModel); ui->privatePackList->setSortingEnabled(true); ui->privatePackList->header()->hide(); ui->privatePackList->setIndentation(0); ui->privatePackList->setIconSize(QSize(42, 42)); privateFilterModel->setSorting(publicFilterModel->getCurrentSorting()); } ui->versionSelectionBox->view()->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); ui->versionSelectionBox->view()->parentWidget()->setMaximumHeight(300); connect(ui->sortByBox, &QComboBox::currentTextChanged, this, &Page::onSortingSelectionChanged); connect(ui->versionSelectionBox, &QComboBox::currentTextChanged, this, &Page::onVersionSelectionItemChanged); connect(ui->searchEdit, &QLineEdit::textChanged, this, &Page::triggerSearch); connect(ui->publicPackList->selectionModel(), &QItemSelectionModel::currentChanged, this, &Page::onPublicPackSelectionChanged); connect(ui->thirdPartyPackList->selectionModel(), &QItemSelectionModel::currentChanged, this, &Page::onThirdPartyPackSelectionChanged); connect(ui->privatePackList->selectionModel(), &QItemSelectionModel::currentChanged, this, &Page::onPrivatePackSelectionChanged); connect(ui->addPackBtn, &QPushButton::clicked, this, &Page::onAddPackClicked); connect(ui->removePackBtn, &QPushButton::clicked, this, &Page::onRemovePackClicked); connect(ui->tabWidget, &QTabWidget::currentChanged, this, &Page::onTabChanged); // ui->modpackInfo->setOpenExternalLinks(true); ui->publicPackList->selectionModel()->reset(); ui->thirdPartyPackList->selectionModel()->reset(); ui->privatePackList->selectionModel()->reset(); ui->publicPackList->setItemDelegate(new ProjectItemDelegate(this)); ui->thirdPartyPackList->setItemDelegate(new ProjectItemDelegate(this)); ui->privatePackList->setItemDelegate(new ProjectItemDelegate(this)); onTabChanged(ui->tabWidget->currentIndex()); } Page::~Page() { delete ui; } bool Page::shouldDisplay() const { return true; } void Page::openedImpl() { if (!initialized) { connect(ftbFetchTask.get(), &PackFetchTask::finished, this, &Page::ftbPackDataDownloadSuccessfully); connect(ftbFetchTask.get(), &PackFetchTask::failed, this, &Page::ftbPackDataDownloadFailed); connect(ftbFetchTask.get(), &PackFetchTask::aborted, this, &Page::ftbPackDataDownloadAborted); connect(ftbFetchTask.get(), &PackFetchTask::privateFileDownloadFinished, this, &Page::ftbPrivatePackDataDownloadSuccessfully); connect(ftbFetchTask.get(), &PackFetchTask::privateFileDownloadFailed, this, &Page::ftbPrivatePackDataDownloadFailed); ftbFetchTask->fetch(); ftbPrivatePacks->load(); ftbFetchTask->fetchPrivate(ftbPrivatePacks->getCurrentPackCodes().values()); initialized = true; } suggestCurrent(); } void Page::retranslate() { ui->retranslateUi(this); } void Page::suggestCurrent() { if (!isOpened) { return; } if (selected.broken || selectedVersion.isEmpty()) { dialog->setSuggestedPack(); return; } dialog->setSuggestedPack(selected.name, selectedVersion, new PackInstallTask(APPLICATION->network(), selected, selectedVersion)); QString editedLogoName = selected.logo; if (!selected.logo.toLower().startsWith("ftb")) { editedLogoName = "ftb_" + editedLogoName; } if (selected.type == PackType::Public) { publicListModel->getLogo(selected.logo, [this, editedLogoName](QString logo) { dialog->setSuggestedIconFromFile(logo, editedLogoName); }); } else if (selected.type == PackType::ThirdParty) { thirdPartyModel->getLogo(selected.logo, [this, editedLogoName](QString logo) { dialog->setSuggestedIconFromFile(logo, editedLogoName); }); } else if (selected.type == PackType::Private) { privateListModel->getLogo(selected.logo, [this, editedLogoName](QString logo) { dialog->setSuggestedIconFromFile(logo, editedLogoName); }); } } void Page::ftbPackDataDownloadSuccessfully(ModpackList publicPacks, ModpackList thirdPartyPacks) { publicListModel->fill(publicPacks); thirdPartyModel->fill(thirdPartyPacks); } void Page::ftbPackDataDownloadFailed(QString reason) { CustomMessageBox::selectable(this, tr("Error"), reason, QMessageBox::Critical)->show(); } void Page::ftbPackDataDownloadAborted() { CustomMessageBox::selectable(this, tr("Task aborted"), tr("The task has been aborted by the user."), QMessageBox::Information)->show(); } void Page::ftbPrivatePackDataDownloadSuccessfully(Modpack pack) { privateListModel->addPack(pack); } void Page::ftbPrivatePackDataDownloadFailed([[maybe_unused]] QString reason, QString packCode) { auto reply = QMessageBox::question(this, tr("FTB private packs"), tr("Failed to download pack information for code %1.\nShould it be removed now?").arg(packCode)); if (reply == QMessageBox::Yes) { ftbPrivatePacks->remove(packCode); } } void Page::onPublicPackSelectionChanged(QModelIndex now, [[maybe_unused]] QModelIndex prev) { if (!now.isValid()) { onPackSelectionChanged(); return; } Modpack selectedPack = publicFilterModel->data(now, Qt::UserRole).value<Modpack>(); onPackSelectionChanged(&selectedPack); } void Page::onThirdPartyPackSelectionChanged(QModelIndex now, [[maybe_unused]] QModelIndex prev) { if (!now.isValid()) { onPackSelectionChanged(); return; } Modpack selectedPack = thirdPartyFilterModel->data(now, Qt::UserRole).value<Modpack>(); onPackSelectionChanged(&selectedPack); } void Page::onPrivatePackSelectionChanged(QModelIndex now, [[maybe_unused]] QModelIndex prev) { if (!now.isValid()) { onPackSelectionChanged(); return; } Modpack selectedPack = privateFilterModel->data(now, Qt::UserRole).value<Modpack>(); onPackSelectionChanged(&selectedPack); } void Page::onPackSelectionChanged(Modpack* pack) { ui->versionSelectionBox->clear(); if (pack) { currentModpackInfo->setHtml(StringUtils::htmlListPatch("Pack by <b>" + pack->author + "</b>" + "<br>Minecraft " + pack->mcVersion + "<br>" + "<br>" + pack->description + "<ul><li>" + pack->mods.replace(";", "</li><li>") + "</li></ul>")); bool currentAdded = false; for (int i = 0; i < pack->oldVersions.size(); i++) { if (pack->currentVersion == pack->oldVersions.at(i)) { currentAdded = true; } ui->versionSelectionBox->addItem(pack->oldVersions.at(i)); } if (!currentAdded) { ui->versionSelectionBox->addItem(pack->currentVersion); } selected = *pack; } else { currentModpackInfo->setHtml(""); ui->versionSelectionBox->clear(); if (isOpened) { dialog->setSuggestedPack(); } return; } suggestCurrent(); } void Page::onVersionSelectionItemChanged(QString version) { if (version.isNull() || version.isEmpty()) { selectedVersion = ""; return; } selectedVersion = version; suggestCurrent(); } void Page::onSortingSelectionChanged(QString sort) { FilterModel::Sorting toSet = publicFilterModel->getAvailableSortings().value(sort); publicFilterModel->setSorting(toSet); thirdPartyFilterModel->setSorting(toSet); privateFilterModel->setSorting(toSet); } void Page::onTabChanged(int tab) { if (tab == 1) { currentModel = thirdPartyFilterModel; currentList = ui->thirdPartyPackList; currentModpackInfo = ui->thirdPartyPackDescription; } else if (tab == 2) { currentModel = privateFilterModel; currentList = ui->privatePackList; currentModpackInfo = ui->privatePackDescription; } else { currentModel = publicFilterModel; currentList = ui->publicPackList; currentModpackInfo = ui->publicPackDescription; } triggerSearch(); currentList->selectionModel()->reset(); QModelIndex idx = currentList->currentIndex(); if (idx.isValid()) { auto pack = currentModel->data(idx, Qt::UserRole).value<Modpack>(); onPackSelectionChanged(&pack); } else { onPackSelectionChanged(); } } void Page::onAddPackClicked() { bool ok; QString text = QInputDialog::getText(this, tr("Add FTB pack"), tr("Enter pack code:"), QLineEdit::Normal, QString(), &ok); if (ok && !text.isEmpty()) { ftbPrivatePacks->add(text); ftbFetchTask->fetchPrivate({ text }); } } void Page::onRemovePackClicked() { auto index = ui->privatePackList->currentIndex(); if (!index.isValid()) { return; } auto row = index.row(); Modpack pack = privateListModel->at(row); auto answer = QMessageBox::question(this, tr("Remove pack"), tr("Are you sure you want to remove pack %1?").arg(pack.name), QMessageBox::Yes | QMessageBox::No); if (answer != QMessageBox::Yes) { return; } ftbPrivatePacks->remove(pack.packCode); privateListModel->remove(row); onPackSelectionChanged(); } void Page::triggerSearch() { currentModel->setSearchTerm(ui->searchEdit->text()); } void Page::setSearchTerm(QString term) { ui->searchEdit->setText(term); } QString Page::getSerachTerm() const { return ui->searchEdit->text(); } } // namespace LegacyFTB
13,389
C++
.cpp
321
35.819315
139
0.695649
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
28,990
ListModel.cpp
PrismLauncher_PrismLauncher/launcher/ui/pages/modplatform/import_ftb/ListModel.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2023 Trial97 <alexandru.tripon97@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "ListModel.h" #include <qfileinfo.h> #include <QDir> #include <QDirIterator> #include <QFileInfo> #include <QIcon> #include <QProcessEnvironment> #include "Application.h" #include "Exception.h" #include "FileSystem.h" #include "Json.h" #include "StringUtils.h" #include "modplatform/import_ftb/PackHelpers.h" #include "ui/widgets/ProjectItem.h" namespace FTBImportAPP { QString getFTBRoot() { QString partialPath = QDir::homePath(); #if defined(Q_OS_OSX) partialPath = FS::PathCombine(partialPath, "Library/Application Support"); #endif return FS::PathCombine(partialPath, ".ftba"); } QString getDynamicPath() { auto settingsPath = FS::PathCombine(getFTBRoot(), "storage", "settings.json"); if (!QFileInfo::exists(settingsPath)) settingsPath = FS::PathCombine(getFTBRoot(), "bin", "settings.json"); if (!QFileInfo::exists(settingsPath)) { qWarning() << "The ftb app setings doesn't exist."; return {}; } try { auto doc = Json::requireDocument(FS::read(settingsPath)); return Json::requireString(Json::requireObject(doc), "instanceLocation"); } catch (const Exception& e) { qCritical() << "Could not read ftb settings file: " << e.cause(); } return {}; } ListModel::ListModel(QObject* parent) : QAbstractListModel(parent), m_instances_path(getDynamicPath()) {} void ListModel::update() { beginResetModel(); m_modpacks.clear(); auto wasPathAdded = [this](QString path) { for (auto pack : m_modpacks) { if (pack.path == path) return true; } return false; }; auto scanPath = [this, wasPathAdded](QString path) { if (path.isEmpty()) return; if (auto instancesInfo = QFileInfo(path); !instancesInfo.exists() || !instancesInfo.isDir()) return; QDirIterator directoryIterator(path, QDir::Dirs | QDir::NoDotAndDotDot | QDir::Readable | QDir::Hidden, QDirIterator::FollowSymlinks); while (directoryIterator.hasNext()) { auto currentPath = directoryIterator.next(); if (!wasPathAdded(currentPath)) { auto modpack = parseDirectory(currentPath); if (!modpack.path.isEmpty()) m_modpacks.append(modpack); } } }; scanPath(APPLICATION->settings()->get("FTBAppInstancesPath").toString()); scanPath(m_instances_path); endResetModel(); } QVariant ListModel::data(const QModelIndex& index, int role) const { int pos = index.row(); if (pos >= m_modpacks.size() || pos < 0 || !index.isValid()) { return QVariant(); } auto pack = m_modpacks.at(pos); if (role == Qt::ToolTipRole) { } switch (role) { case Qt::ToolTipRole: return tr("Minecraft %1").arg(pack.mcVersion); case Qt::DecorationRole: return pack.icon; case Qt::UserRole: { QVariant v; v.setValue(pack); return v; } case Qt::DisplayRole: return pack.name; case Qt::SizeHintRole: return QSize(0, 58); // Custom data case UserDataTypes::TITLE: return pack.name; case UserDataTypes::DESCRIPTION: return tr("Minecraft %1").arg(pack.mcVersion); case UserDataTypes::SELECTED: return false; case UserDataTypes::INSTALLED: return false; default: break; } return {}; } FilterModel::FilterModel(QObject* parent) : QSortFilterProxyModel(parent) { m_currentSorting = Sorting::ByGameVersion; m_sortings.insert(tr("Sort by Name"), Sorting::ByName); m_sortings.insert(tr("Sort by Game Version"), Sorting::ByGameVersion); } bool FilterModel::lessThan(const QModelIndex& left, const QModelIndex& right) const { Modpack leftPack = sourceModel()->data(left, Qt::UserRole).value<Modpack>(); Modpack rightPack = sourceModel()->data(right, Qt::UserRole).value<Modpack>(); if (m_currentSorting == Sorting::ByGameVersion) { Version lv(leftPack.mcVersion); Version rv(rightPack.mcVersion); return lv < rv; } else if (m_currentSorting == Sorting::ByName) { return StringUtils::naturalCompare(leftPack.name, rightPack.name, Qt::CaseSensitive) >= 0; } // UHM, some inavlid value set?! qWarning() << "Invalid sorting set!"; return true; } bool FilterModel::filterAcceptsRow([[maybe_unused]] int sourceRow, [[maybe_unused]] const QModelIndex& sourceParent) const { if (m_searchTerm.isEmpty()) { return true; } QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent); Modpack pack = sourceModel()->data(index, Qt::UserRole).value<Modpack>(); return pack.name.contains(m_searchTerm, Qt::CaseInsensitive); } void FilterModel::setSearchTerm(const QString term) { m_searchTerm = term.trimmed(); invalidate(); } const QMap<QString, FilterModel::Sorting> FilterModel::getAvailableSortings() { return m_sortings; } QString FilterModel::translateCurrentSorting() { return m_sortings.key(m_currentSorting); } void FilterModel::setSorting(Sorting s) { m_currentSorting = s; invalidate(); } FilterModel::Sorting FilterModel::getCurrentSorting() { return m_currentSorting; } void ListModel::setPath(QString path) { APPLICATION->settings()->set("FTBAppInstancesPath", path); update(); } QString ListModel::getUserPath() { auto path = APPLICATION->settings()->get("FTBAppInstancesPath").toString(); if (path.isEmpty()) path = m_instances_path; return path; } } // namespace FTBImportAPP
6,484
C++
.cpp
191
28.471204
122
0.666879
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,991
ImportFTBPage.cpp
PrismLauncher_PrismLauncher/launcher/ui/pages/modplatform/import_ftb/ImportFTBPage.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2023 Trial97 <alexandru.tripon97@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "ImportFTBPage.h" #include "ui/widgets/ProjectItem.h" #include "ui_ImportFTBPage.h" #include <QFileDialog> #include <QFileInfo> #include <QWidget> #include "FileSystem.h" #include "ListModel.h" #include "modplatform/import_ftb/PackInstallTask.h" #include "ui/dialogs/NewInstanceDialog.h" namespace FTBImportAPP { ImportFTBPage::ImportFTBPage(NewInstanceDialog* dialog, QWidget* parent) : QWidget(parent), dialog(dialog), ui(new Ui::ImportFTBPage) { ui->setupUi(this); { currentModel = new FilterModel(this); listModel = new ListModel(this); currentModel->setSourceModel(listModel); ui->modpackList->setModel(currentModel); ui->modpackList->setSortingEnabled(true); ui->modpackList->header()->hide(); ui->modpackList->setIndentation(0); ui->modpackList->setIconSize(QSize(42, 42)); for (int i = 0; i < currentModel->getAvailableSortings().size(); i++) { ui->sortByBox->addItem(currentModel->getAvailableSortings().keys().at(i)); } ui->sortByBox->setCurrentText(currentModel->translateCurrentSorting()); } connect(ui->modpackList->selectionModel(), &QItemSelectionModel::currentChanged, this, &ImportFTBPage::onPublicPackSelectionChanged); connect(ui->sortByBox, &QComboBox::currentTextChanged, this, &ImportFTBPage::onSortingSelectionChanged); connect(ui->searchEdit, &QLineEdit::textChanged, this, &ImportFTBPage::triggerSearch); connect(ui->browseButton, &QPushButton::clicked, this, [this] { QString dir = QFileDialog::getExistingDirectory(this, tr("Select FTBApp instances directory"), listModel->getUserPath(), QFileDialog::ShowDirsOnly); if (!dir.isEmpty()) listModel->setPath(dir); }); ui->modpackList->setItemDelegate(new ProjectItemDelegate(this)); ui->modpackList->selectionModel()->reset(); } ImportFTBPage::~ImportFTBPage() { delete ui; } void ImportFTBPage::openedImpl() { if (!initialized) { listModel->update(); initialized = true; } suggestCurrent(); } void ImportFTBPage::retranslate() { ui->retranslateUi(this); } void ImportFTBPage::suggestCurrent() { if (!isOpened) return; if (selected.path.isEmpty()) { dialog->setSuggestedPack(); return; } dialog->setSuggestedPack(selected.name, new PackInstallTask(selected)); QString editedLogoName = QString("ftb_%1_%2.jpg").arg(selected.name, QString::number(selected.id)); dialog->setSuggestedIconFromFile(FS::PathCombine(selected.path, "folder.jpg"), editedLogoName); } void ImportFTBPage::onPublicPackSelectionChanged(QModelIndex now, QModelIndex prev) { if (!now.isValid()) { onPackSelectionChanged(); return; } Modpack selectedPack = currentModel->data(now, Qt::UserRole).value<Modpack>(); onPackSelectionChanged(&selectedPack); } void ImportFTBPage::onPackSelectionChanged(Modpack* pack) { if (pack) { selected = *pack; suggestCurrent(); return; } if (isOpened) dialog->setSuggestedPack(); } void ImportFTBPage::onSortingSelectionChanged(QString sort) { FilterModel::Sorting toSet = currentModel->getAvailableSortings().value(sort); currentModel->setSorting(toSet); } void ImportFTBPage::triggerSearch() { currentModel->setSearchTerm(ui->searchEdit->text()); } void ImportFTBPage::setSearchTerm(QString term) { ui->searchEdit->setText(term); } QString ImportFTBPage::getSerachTerm() const { return ui->searchEdit->text(); } } // namespace FTBImportAPP
4,402
C++
.cpp
122
31.442623
137
0.713514
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,992
TechnicModel.cpp
PrismLauncher_PrismLauncher/launcher/ui/pages/modplatform/technic/TechnicModel.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2021 Jamie Mansfield <jmansfield@cadixdev.org> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2020-2021 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 "TechnicModel.h" #include "Application.h" #include "BuildConfig.h" #include "Json.h" #include "net/ApiDownload.h" #include "ui/widgets/ProjectItem.h" #include <QFileInfo> #include <QIcon> #include <QUrl> Technic::ListModel::ListModel(QObject* parent) : QAbstractListModel(parent) {} Technic::ListModel::~ListModel() {} QVariant Technic::ListModel::data(const QModelIndex& index, int role) const { int pos = index.row(); if (pos >= modpacks.size() || pos < 0 || !index.isValid()) { return QString("INVALID INDEX %1").arg(pos); } Modpack pack = modpacks.at(pos); switch (role) { case Qt::ToolTipRole: { if (pack.description.length() > 100) { // some magic to prevent to long tooltips and replace html linebreaks QString edit = pack.description.left(97); edit = edit.left(edit.lastIndexOf("<br>")).left(edit.lastIndexOf(" ")).append("..."); return edit; } return pack.description; } case Qt::DecorationRole: { if (m_logoMap.contains(pack.logoName)) { return (m_logoMap.value(pack.logoName)); } QIcon icon = APPLICATION->getThemedIcon("screenshot-placeholder"); ((ListModel*)this)->requestLogo(pack.logoName, pack.logoUrl); return icon; } case Qt::UserRole: { QVariant v; v.setValue(pack); return v; } case Qt::DisplayRole: return pack.name; case Qt::SizeHintRole: return QSize(0, 58); // Custom data case UserDataTypes::TITLE: return pack.name; case UserDataTypes::DESCRIPTION: return pack.description; case UserDataTypes::SELECTED: return false; case UserDataTypes::INSTALLED: return false; default: break; } return {}; } int Technic::ListModel::columnCount(const QModelIndex& parent) const { return parent.isValid() ? 0 : 1; } int Technic::ListModel::rowCount(const QModelIndex& parent) const { return parent.isValid() ? 0 : modpacks.size(); } void Technic::ListModel::searchWithTerm(const QString& term) { if (currentSearchTerm == term && currentSearchTerm.isNull() == term.isNull()) { return; } currentSearchTerm = term; if (hasActiveSearchJob()) { jobPtr->abort(); searchState = ResetRequested; return; } beginResetModel(); modpacks.clear(); endResetModel(); searchState = None; performSearch(); } void Technic::ListModel::performSearch() { if (hasActiveSearchJob()) return; auto netJob = makeShared<NetJob>("Technic::Search", APPLICATION->network()); QString searchUrl = ""; if (currentSearchTerm.isEmpty()) { searchUrl = QString("%1trending?build=%2").arg(BuildConfig.TECHNIC_API_BASE_URL, BuildConfig.TECHNIC_API_BUILD); searchMode = List; } else if (currentSearchTerm.startsWith("http://api.technicpack.net/modpack/")) { searchUrl = QString("https://%1?build=%2").arg(currentSearchTerm.mid(7), BuildConfig.TECHNIC_API_BUILD); searchMode = Single; } else if (currentSearchTerm.startsWith("https://api.technicpack.net/modpack/")) { searchUrl = QString("%1?build=%2").arg(currentSearchTerm, BuildConfig.TECHNIC_API_BUILD); searchMode = Single; } else if (currentSearchTerm.startsWith("#")) { searchUrl = QString("https://api.technicpack.net/modpack/%1?build=%2").arg(currentSearchTerm.mid(1), BuildConfig.TECHNIC_API_BUILD); searchMode = Single; } else { searchUrl = QString("%1search?build=%2&q=%3").arg(BuildConfig.TECHNIC_API_BASE_URL, BuildConfig.TECHNIC_API_BUILD, currentSearchTerm); searchMode = List; } auto clientId = APPLICATION->settings()->get("TechnicClientID").toString(); if (!clientId.isEmpty()) { searchUrl += "?cid=" + clientId; } netJob->addNetAction(Net::ApiDownload::makeByteArray(QUrl(searchUrl), response)); jobPtr = netJob; jobPtr->start(); QObject::connect(netJob.get(), &NetJob::succeeded, this, &ListModel::searchRequestFinished); QObject::connect(netJob.get(), &NetJob::failed, this, &ListModel::searchRequestFailed); } void Technic::ListModel::searchRequestFinished() { jobPtr.reset(); QJsonParseError parse_error; QJsonDocument doc = QJsonDocument::fromJson(*response, &parse_error); if (parse_error.error != QJsonParseError::NoError) { qWarning() << "Error while parsing JSON response from Technic at " << parse_error.offset << " reason: " << parse_error.errorString(); qWarning() << *response; return; } QList<Modpack> newList; try { auto root = Json::requireObject(doc); switch (searchMode) { case List: { auto objs = Json::requireArray(root, "modpacks"); for (auto technicPack : objs) { Modpack pack; auto technicPackObject = Json::requireObject(technicPack); pack.name = Json::requireString(technicPackObject, "name"); pack.slug = Json::requireString(technicPackObject, "slug"); if (pack.slug == "vanilla") continue; auto rawURL = Json::ensureString(technicPackObject, "iconUrl", "null"); if (rawURL == "null") { pack.logoUrl = "null"; pack.logoName = "null"; } else { pack.logoUrl = rawURL; pack.logoName = pack.slug + "." + QFileInfo(QUrl(rawURL).fileName()).suffix(); } pack.broken = false; newList.append(pack); } break; } case Single: { if (root.contains("error")) { // Invalid API url break; } Modpack pack; pack.name = Json::requireString(root, "displayName"); pack.slug = Json::requireString(root, "name"); if (root.contains("icon")) { auto iconObj = Json::requireObject(root, "icon"); auto iconUrl = Json::requireString(iconObj, "url"); pack.logoUrl = iconUrl; pack.logoName = pack.slug + "." + QFileInfo(QUrl(iconUrl).fileName()).suffix(); } else { pack.logoUrl = "null"; pack.logoName = "null"; } pack.broken = false; newList.append(pack); break; } } } catch (const JSONValidationError& err) { qCritical() << "Couldn't parse technic search results:" << err.cause(); return; } searchState = Finished; // When you have a Qt build with assertions turned on, proceeding here will abort the application if (newList.size() == 0) return; beginInsertRows(QModelIndex(), modpacks.size(), modpacks.size() + newList.size() - 1); modpacks.append(newList); endInsertRows(); } void Technic::ListModel::getLogo(const QString& logo, const QString& logoUrl, Technic::LogoCallback callback) { if (m_logoMap.contains(logo)) { callback(APPLICATION->metacache()->resolveEntry("TechnicPacks", QString("logos/%1").arg(logo))->getFullPath()); } else { requestLogo(logo, logoUrl); } } void Technic::ListModel::searchRequestFailed() { jobPtr.reset(); if (searchState == ResetRequested) { beginResetModel(); modpacks.clear(); endResetModel(); performSearch(); } else { searchState = Finished; } } void Technic::ListModel::logoLoaded(QString logo, QString out) { m_loadingLogos.removeAll(logo); m_logoMap.insert(logo, QIcon(out)); for (int i = 0; i < modpacks.size(); i++) { if (modpacks[i].logoName == logo) { emit dataChanged(createIndex(i, 0), createIndex(i, 0), { Qt::DecorationRole }); } } } void Technic::ListModel::logoFailed(QString logo) { m_failedLogos.append(logo); m_loadingLogos.removeAll(logo); } void Technic::ListModel::requestLogo(QString logo, QString url) { if (m_loadingLogos.contains(logo) || m_failedLogos.contains(logo) || logo == "null") { return; } MetaEntryPtr entry = APPLICATION->metacache()->resolveEntry("TechnicPacks", QString("logos/%1").arg(logo)); auto job = new NetJob(QString("Technic Icon Download %1").arg(logo), APPLICATION->network()); job->setAskRetry(false); job->addNetAction(Net::ApiDownload::makeCached(QUrl(url), entry)); auto fullPath = entry->getFullPath(); QObject::connect(job, &NetJob::succeeded, this, [this, logo, fullPath, job] { job->deleteLater(); logoLoaded(logo, fullPath); }); QObject::connect(job, &NetJob::failed, this, [this, logo, job] { job->deleteLater(); logoFailed(logo); }); job->start(); m_loadingLogos.append(logo); }
10,822
C++
.cpp
278
30.956835
140
0.616468
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false