diff options
| author | SulfurNitride <SulfurNitride@users.noreply.github.com> | 2026-02-11 02:37:39 -0600 |
|---|---|---|
| committer | SulfurNitride <SulfurNitride@users.noreply.github.com> | 2026-02-11 02:37:39 -0600 |
| commit | 7ee008e150bc5bcf76082d726f719ee0fdfda982 (patch) | |
| tree | 27fb39be241fdb5ac2734c574de678977d1856d0 /libs/installer_fomod_csharp | |
Fluorine Manager: full Linux port of Mod Organizer 2
Complete native Linux port with FUSE-based virtual filesystem,
Proton/umu-run integration, and Flatpak packaging.
Key features:
- FUSE VFS replacing Windows USVFS (in-process + standalone helper for Flatpak)
- Proton/GE-Proton/umu-run launcher with env var forwarding
- Flatpak support (sandbox-aware VFS, NXM handler, umu-run)
- Wine prefix management UI
- Case-insensitive path resolution for Linux filesystems
- QSettings-safe INI handling (avoids Bethesda INI corruption)
- Portable instance support with auto-generated launcher scripts
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Diffstat (limited to 'libs/installer_fomod_csharp')
27 files changed, 3370 insertions, 0 deletions
diff --git a/libs/installer_fomod_csharp/.clang-format b/libs/installer_fomod_csharp/.clang-format new file mode 100644 index 0000000..6098e1f --- /dev/null +++ b/libs/installer_fomod_csharp/.clang-format @@ -0,0 +1,41 @@ +--- +# We'll use defaults from the LLVM style, but with 4 columns indentation. +BasedOnStyle: LLVM +IndentWidth: 2 +--- +Language: Cpp +DeriveLineEnding: false +UseCRLF: true +DerivePointerAlignment: false +PointerAlignment: Left +AlignConsecutiveAssignments: true +AllowShortFunctionsOnASingleLine: Inline +AllowShortIfStatementsOnASingleLine: Never +AllowShortLambdasOnASingleLine: Empty +AlwaysBreakTemplateDeclarations: Yes +AccessModifierOffset: -2 +AlignTrailingComments: true +SpacesBeforeTrailingComments: 2 +NamespaceIndentation: Inner +MaxEmptyLinesToKeep: 1 +BreakBeforeBraces: Custom +BraceWrapping: + AfterCaseLabel: false + AfterClass: true + AfterControlStatement: false + AfterEnum: true + AfterFunction: true + AfterNamespace: true + AfterStruct: true + AfterUnion: true + AfterExternBlock: true + BeforeCatch: false + BeforeElse: false + BeforeLambdaBody: false + BeforeWhile: false + IndentBraces: false + SplitEmptyFunction: false + SplitEmptyRecord: false + SplitEmptyNamespace: true +ColumnLimit: 88 +ForEachMacros: ['Q_FOREACH', 'foreach'] diff --git a/libs/installer_fomod_csharp/.git-blame-ignore-revs b/libs/installer_fomod_csharp/.git-blame-ignore-revs new file mode 100644 index 0000000..a26d6d2 --- /dev/null +++ b/libs/installer_fomod_csharp/.git-blame-ignore-revs @@ -0,0 +1 @@ +f45b25a7b347ae5a42ca86ae60a47b177e9caf6e diff --git a/libs/installer_fomod_csharp/.gitattributes b/libs/installer_fomod_csharp/.gitattributes new file mode 100644 index 0000000..f869712 --- /dev/null +++ b/libs/installer_fomod_csharp/.gitattributes @@ -0,0 +1,7 @@ +# Set the default behavior, in case people don't have core.autocrlf set. +* text=auto + +# Explicitly declare text files you want to always be normalized and converted +# to native line endings on checkout. +*.cpp text eol=crlf +*.h text eol=crlf diff --git a/libs/installer_fomod_csharp/.github/workflows/build.yml b/libs/installer_fomod_csharp/.github/workflows/build.yml new file mode 100644 index 0000000..b9d11e3 --- /dev/null +++ b/libs/installer_fomod_csharp/.github/workflows/build.yml @@ -0,0 +1,20 @@ +name: Build Installer FOMOD C# + +on: + push: + branches: [master] + pull_request: + types: [opened, synchronize, reopened] + +env: + VCPKG_BINARY_SOURCES: clear;x-azblob,${{ vars.AZ_BLOB_VCPKG_URL }},${{ secrets.AZ_BLOB_SAS }},readwrite + +jobs: + build: + runs-on: windows-2022 + steps: + - name: Build Installer FOMOD C# + id: build-installer-fomod-csharp + uses: ModOrganizer2/build-with-mob-action@master + with: + mo2-dependencies: uibase diff --git a/libs/installer_fomod_csharp/.github/workflows/linting.yml b/libs/installer_fomod_csharp/.github/workflows/linting.yml new file mode 100644 index 0000000..80d5fd4 --- /dev/null +++ b/libs/installer_fomod_csharp/.github/workflows/linting.yml @@ -0,0 +1,16 @@ +name: Lint Installer FOMOD C# Plugin + +on: + push: + pull_request: + types: [opened, synchronize, reopened] + +jobs: + lint: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - name: Check format + uses: ModOrganizer2/check-formatting-action@master + with: + check-path: "." diff --git a/libs/installer_fomod_csharp/.gitignore b/libs/installer_fomod_csharp/.gitignore new file mode 100644 index 0000000..58b3448 --- /dev/null +++ b/libs/installer_fomod_csharp/.gitignore @@ -0,0 +1 @@ +vsbuild diff --git a/libs/installer_fomod_csharp/.pre-commit-config.yaml b/libs/installer_fomod_csharp/.pre-commit-config.yaml new file mode 100644 index 0000000..3103a1f --- /dev/null +++ b/libs/installer_fomod_csharp/.pre-commit-config.yaml @@ -0,0 +1,20 @@ +repos: + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v5.0.0 + hooks: + - id: trailing-whitespace + - id: end-of-file-fixer + - id: check-merge-conflict + - id: check-case-conflict + - repo: https://github.com/pre-commit/mirrors-clang-format + rev: v19.1.5 + hooks: + - id: clang-format + 'types_or': [c++, c] + +ci: + autofix_commit_msg: "[pre-commit.ci] Auto fixes from pre-commit.com hooks." + autofix_prs: true + autoupdate_commit_msg: "[pre-commit.ci] Pre-commit autoupdate." + autoupdate_schedule: quarterly + submodules: false diff --git a/libs/installer_fomod_csharp/CMakeLists.txt b/libs/installer_fomod_csharp/CMakeLists.txt new file mode 100644 index 0000000..3170ab3 --- /dev/null +++ b/libs/installer_fomod_csharp/CMakeLists.txt @@ -0,0 +1,5 @@ +cmake_minimum_required(VERSION 3.16) + +project(installer_fomod_csharp) + +add_subdirectory(src) diff --git a/libs/installer_fomod_csharp/CMakePresets.json b/libs/installer_fomod_csharp/CMakePresets.json new file mode 100644 index 0000000..5a63c77 --- /dev/null +++ b/libs/installer_fomod_csharp/CMakePresets.json @@ -0,0 +1,67 @@ +{ + "configurePresets": [ + { + "errors": { + "deprecated": true + }, + "hidden": true, + "name": "cmake-dev", + "warnings": { + "deprecated": true, + "dev": true + } + }, + { + "cacheVariables": { + "VCPKG_MANIFEST_NO_DEFAULT_FEATURES": { + "type": "BOOL", + "value": "ON" + } + }, + "toolchainFile": "$env{VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake", + "hidden": true, + "name": "vcpkg" + }, + { + "hidden": true, + "inherits": ["vcpkg"], + "name": "vcpkg-dev" + }, + { + "binaryDir": "${sourceDir}/vsbuild", + "architecture": { + "strategy": "set", + "value": "x64" + }, + "cacheVariables": { + "CMAKE_CXX_FLAGS": "/EHsc /MP /W4", + "VCPKG_TARGET_TRIPLET": { + "type": "STRING", + "value": "x64-windows-static-md" + } + }, + "generator": "Visual Studio 17 2022", + "inherits": ["cmake-dev", "vcpkg-dev"], + "name": "vs2022-windows", + "toolset": "v143" + }, + { + "cacheVariables": { + "VCPKG_MANIFEST_FEATURES": { + "type": "STRING", + "value": "standalone" + } + }, + "inherits": "vs2022-windows", + "name": "vs2022-windows-standalone" + } + ], + "buildPresets": [ + { + "name": "vs2022-windows", + "resolvePackageReferences": "on", + "configurePreset": "vs2022-windows" + } + ], + "version": 4 +} diff --git a/libs/installer_fomod_csharp/LICENSE b/libs/installer_fomod_csharp/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/libs/installer_fomod_csharp/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + <program> Copyright (C) <year> <name of author> + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +<https://www.gnu.org/licenses/>. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +<https://www.gnu.org/licenses/why-not-lgpl.html>. diff --git a/libs/installer_fomod_csharp/README.md b/libs/installer_fomod_csharp/README.md new file mode 100644 index 0000000..6b4e4d1 --- /dev/null +++ b/libs/installer_fomod_csharp/README.md @@ -0,0 +1,20 @@ +# [MO2](https://github.com/ModOrganizer2/modorganizer) plugin for FOMOD installers using C# scripts + +This is simple installer plugin for Mod Organizer 2 to handle FOMOD installers containing C# script. + +Without this plugin, Mod Organizer 2 will use NCC to install such plugins, but NCC has a few limitations when +used within MO2: + +- Mod detection will not work, so the installer will not be able to check for active mods or even existing files. +- Modifying settings (`FalloutNV.ini`, etc.) does not work properly with the NCC installer (it may work if you + do not use per-profile settings, but that is not recommended). + +This installer is better integrated with Mod Organizer 2 and should handle any kind of FOMOD installer containing +a C# script. Feel free to [open an issue](https://github.com/ModOrganizer2/modorganizer/issues/new?assignees=&labels=issue+report&template=issue-report.md) +if you find a bug. + +The installer will never modify settings silently. If during installation, the script tries to modify settings, +they will be stored in memory and presented to you at the end of the installation. You will then be able to either +apply the settings, save them inside the mod folder or discard them. + +**Warning:** This plugin currently only works with Mod Organizer 2 development build 2.3.0 alpha 10! diff --git a/libs/installer_fomod_csharp/src/CMakeLists.txt b/libs/installer_fomod_csharp/src/CMakeLists.txt new file mode 100644 index 0000000..09b3015 --- /dev/null +++ b/libs/installer_fomod_csharp/src/CMakeLists.txt @@ -0,0 +1,11 @@ +cmake_minimum_required(VERSION 3.16) + +find_package(mo2-cmake CONFIG REQUIRED) +find_package(mo2-uibase CONFIG REQUIRED) + +add_library(installer_fomod_csharp SHARED) +mo2_configure_plugin(installer_fomod_csharp WARNINGS OFF CLI ON) +target_link_libraries(installer_fomod_csharp PRIVATE mo2::uibase) +mo2_install_plugin(installer_fomod_csharp) + +set_target_properties(installer_fomod_csharp PROPERTIES CXX_STANDARD 20) diff --git a/libs/installer_fomod_csharp/src/base_script.cpp b/libs/installer_fomod_csharp/src/base_script.cpp new file mode 100644 index 0000000..e3aa4a7 --- /dev/null +++ b/libs/installer_fomod_csharp/src/base_script.cpp @@ -0,0 +1,685 @@ +/* +Copyright (C) 2020 Holt59. All rights reserved. + +Mod Organizer is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Mod Organizer 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 Mod Organizer. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include "base_script.h" + +#include <filesystem> +#include <map> + +#include <QCheckBox> +#include <QDialogButtonBox> +#include <QInputDialog> +#include <QLabel> +#include <QMessageBox> +#include <QPushButton> +#include <QRadioButton> +#include <QSettings> +#include <QVBoxLayout> +#include <QVersionNumber> + +#include <uibase/game_features/igamefeatures.h> +#include <uibase/game_features/scriptextender.h> +#include <uibase/iinstallationmanager.h> +#include <uibase/imoinfo.h> +#include <uibase/iplugingame.h> +#include <uibase/ipluginlist.h> +#include <uibase/log.h> + +#include "csharp_interface.h" +#include "csharp_utils.h" +#include "installer_fomod_postdialog.h" +#include "psettings.h" + +using namespace MOBase; + +// clang-format off + +namespace CSharp { + + // Pointer to object: + static MOBase::IOrganizer* g_Organizer = nullptr; + + // Per-install globals: + struct Globals { + IInstallationManager* InstallManager; + QWidget* ParentWidget; + std::shared_ptr<const IFileTree> SourceTree; + std::shared_ptr<IFileTree> DestinationTree; + + // Map from path in destination entry to the original entry: + std::map<std::shared_ptr<const FileTreeEntry>, + std::shared_ptr<const FileTreeEntry>> InstalledEntries; + + // Map extracted entries (in the original tree) to (temporary) paths: + std::map<std::shared_ptr<const FileTreeEntry>, QString> ExtractedEntries; + + // Map creted entries (in the destination tree) to (temporary) paths: + std::map<std::shared_ptr<const FileTreeEntry>, QString> CreatedEntries; + + // List of modified settings values: + std::map<QString, PSettings> Settings; + + Globals() { } + Globals( + IPlugin const* plugin, MOBase::IInstallationManager* manager, QWidget* parentWidget, + std::shared_ptr<MOBase::IFileTree> tree, std::map<std::shared_ptr<const FileTreeEntry>, QString> entries) : + m_Plugin(plugin), InstallManager(manager), ParentWidget(parentWidget), SourceTree(tree), DestinationTree(tree->createOrphanTree()), ExtractedEntries(std::move(entries)) { + + } + + Globals(Globals const&) = delete; + Globals(Globals&&) = default; + + Globals& operator=(Globals const&) = delete; + Globals& operator=(Globals&&) = default; + + private: + IPlugin const* m_Plugin; + }; + static Globals g; + + + + void init(MOBase::IOrganizer* moInfo) { + + // Do this only once: + if (g_Organizer == nullptr) { + Application::EnableVisualStyles(); + Application::SetCompatibleTextRenderingDefault(false); + } + + g_Organizer = moInfo; + } + + void beforeInstall(IPlugin const* plugin, MOBase::IInstallationManager* manager, QWidget* parentWidget, + std::shared_ptr<MOBase::IFileTree> tree, std::map<std::shared_ptr<const FileTreeEntry>, QString> entries) { + g = { plugin, manager, parentWidget, tree, std::move(entries) }; + } + + IPluginInstaller::EInstallResult postInstall(std::shared_ptr<MOBase::IFileTree>& tree) { + + if (!g.Settings.empty()) { + + InstallerFomodPostDialog* dialog = new InstallerFomodPostDialog(g.ParentWidget); + + dialog->setIniSettings(g.Settings); + + // Installation cancelled: + if (dialog->exec() == QDialog::Rejected) { + return IPluginInstaller::EInstallResult::RESULT_CANCELED; + } + + switch (dialog->result()) { + + // Discard, nothing do to: + case InstallerFomodPostDialog::Result::DISCARD: break; + + // Apply, must fetch the profile INI settings and apply the settings: + case InstallerFomodPostDialog::Result::APPLY: { + for (auto& p : g.Settings) { + QDir path(g_Organizer->profilePath()); + if (!g_Organizer->profile()->localSettingsEnabled()) { + path = QDir(g_Organizer->managedGame()->documentsDirectory()); + } + + QSettings settings(path.filePath(p.first), QSettings::IniFormat); + + if (settings.status() != QSettings::NoError) { + return IPluginInstaller::EInstallResult::RESULT_FAILED; + } + + p.second.update(settings); + } + } break; + + // Move, must create the INI files and apply the settings: + case InstallerFomodPostDialog::Result::MOVE: { + for (auto& p : g.Settings) { + auto e = g.DestinationTree->addFile("INI Tweaks/" + p.first, false); + if (e == nullptr) { + return IPluginInstaller::EInstallResult::RESULT_FAILED; + } + QString path = g.InstallManager->createFile(e); + if (path.isEmpty()) { + return IPluginInstaller::EInstallResult::RESULT_FAILED; + } + QSettings settings(path, QSettings::IniFormat); + if (settings.status() != QSettings::NoError) { + return IPluginInstaller::EInstallResult::RESULT_FAILED; + } + p.second.update(settings); + } + } break; + } + + } + + tree = g.DestinationTree; + + // Clear up: + g = Globals(); + + + return IPluginInstaller::EInstallResult::RESULT_SUCCESS; + } + +} + +namespace CSharp { + + using namespace System::IO; + + bool isFomodEntry(std::shared_ptr<const FileTreeEntry> entry) { + return entry->pathFrom(g.SourceTree).compare("fomod", Qt::CaseInsensitive) == 0; + } + + bool BaseScriptImpl::PerformBasicInstall() { + for (auto e : *g.SourceTree) { + if (!isFomodEntry(e)) { + auto ce = g.DestinationTree->copy(e, "", IFileTree::InsertPolicy::MERGE); + g.InstalledEntries[ce] = e; + } + } + return true; + } + + bool BaseScriptImpl::InstallFileFromMod(String^ p_strFrom, String^ p_strTo) { + auto sourceEntry = g.SourceTree->find(to_qstring(p_strFrom)); + + if (!sourceEntry) { + log::warn("File '{}' not found in the archive.", to_wstring(p_strFrom)); + return false; + } + + if (auto ce = g.DestinationTree->copy(sourceEntry, to_qstring(p_strTo)); ce != nullptr) { + g.InstalledEntries[ce] = sourceEntry; + return true; + } + + return false; + } + + array<String^>^ BaseScriptImpl::GetModFileList() { + // Cannot directly fill a, e.g., List<String^>^ because I cannot capture it: + std::vector<QString> paths; + g.SourceTree->walk([&](QString const& path, std::shared_ptr<const FileTreeEntry> entry) { + // Discard fomod folder: + if (isFomodEntry(entry)) { + return IFileTree::WalkReturn::SKIP; + } + if (entry->isFile()) { + paths.push_back(path + entry->name()); + } + return IFileTree::WalkReturn::CONTINUE; + }, "/"); + + // Convert to C#: + const auto size = static_cast<int>(paths.size()); + array<String^>^ result = gcnew array<String^>(size); + for (int i = 0; i < size; ++i) { + result[i] = from_string(paths[i].toStdWString()); + } + + return result; + } + + + /** + * @brief Extract the given entry. + * + * If the entry has already been extracted, the existing paths is returned. + * + * @param entry The entry to extract. + * + * @return path to the temporary file corresponding to the entry. + */ + QString extractFile(std::shared_ptr<const FileTreeEntry> entry) { + + QString qPath; + if (auto it = g.ExtractedEntries.find(entry); it != g.ExtractedEntries.end()) { + qPath = it->second; + } + else { + qPath = g.InstallManager->extractFile(entry, true); + + if (qPath.isEmpty()) { + return QString(); + } + + g.ExtractedEntries[entry] = qPath; + } + + return qPath; + } + + array<Byte>^ BaseScriptImpl::GetFileFromMod(String^ p_strFile) { + auto entry = g.SourceTree->find(to_qstring(p_strFile)); + + if (!entry) { + return gcnew array<Byte>(0); + } + + QString qPath = extractFile(entry); + if (qPath.isEmpty()) { + return gcnew array<Byte>(0); + } + + String^ path = from_string(qPath.toStdWString()); + return File::ReadAllBytes(path); + } + + QStringList getDataFiles(QString folder, QString pattern, bool allFolders) { + QStringList files = g_Organizer->findFiles(folder, [pattern](QString const& filepath) { + return QDir::match(pattern, QFileInfo(filepath).fileName()); + }); + if (allFolders) { + QStringList directories = g_Organizer->listDirectories(folder); + for (QString directory : directories) { + // MO2 does not like path with . or / (I think), so creating the path manually: + files.append(getDataFiles((folder.isEmpty() ? "" : folder + QDir::separator()) + directory, pattern, allFolders)); + } + } + return files; + } + + array<String^>^ BaseScriptImpl::GetExistingDataFileList(String^ p_strPath, String^ p_strPattern, bool p_booAllFolders) { + QStringList files = getDataFiles(to_qstring(p_strPath), to_qstring(p_strPattern), p_booAllFolders); + array<String^>^ result = gcnew array<String^>(files.size()); + + QDir modsDir(g_Organizer->modsPath()); + for (int i = 0; i < files.size(); ++i) { + // We need to trim the path to the actual folder containing the mod (did not find a better way): + QString rpath = modsDir.relativeFilePath(files[i]).replace("/", QDir::separator()); + result[i] = from_string(rpath.mid(rpath.indexOf(QDir::separator()) + 1).toStdWString()); + } + return result; + } + + /** + * @brief Find the data-file path corresponding to the given path. + * + * This methods first lookup the file in the destination tree of the mod (for files + * that have been extracted / created by the mod), and if it does not find it there + * lookup files from other mods. + * + * @param p_strPath Path to the file to lookup, relative to the data folder. + * + * @return a path to an actual corresponding file, or a null pointer if the + * file was not found. + */ + String^ getDataFilePath(String^ p_strPath) { + + // Check if the file is in the output tree: + QString qPath = to_qstring(p_strPath); + if (auto e = g.DestinationTree->find(qPath); e != nullptr) { + + // Check if it's a created entry: + if (auto it = g.CreatedEntries.find(e); it != g.CreatedEntries.end()) { + return from_string(g.CreatedEntries[e]); + } + + // Find the source entry - We need to check for parent: + std::shared_ptr<const FileTreeEntry> originalEntry; + if (auto it = g.InstalledEntries.find(e); it != g.InstalledEntries.end()) { + originalEntry = it->second; + } + else { + std::shared_ptr<const IFileTree> tree = e->parent(); + decltype(tree) oTree = nullptr; + while (oTree == nullptr && tree != nullptr) { + auto it = g.InstalledEntries.find(tree); + if (it != g.InstalledEntries.end()) { + oTree = it->second->astree(); + } + else { + tree = tree->parent(); + } + } + originalEntry = oTree->find(e->pathFrom(tree)); + } + QString path = extractFile(originalEntry); + if (path.isEmpty()) { + return nullptr; + } + return from_string(path); + } + + // Convert to path and normalize separator: + auto path = std::filesystem::path(qPath.toStdWString()).make_preferred(); + QStringList paths = g_Organizer->findFiles(ToQString(path.parent_path().native()), [name = ToQString(path.filename())](QString const& filepath) { + return QFileInfo(filepath).fileName().compare(name, Qt::CaseInsensitive) == 0; + }); + + if (paths.isEmpty()) { + return nullptr; + } + + return from_string(paths[0]); + } + + bool BaseScriptImpl::DataFileExists(String^ p_strPath) { + return getDataFilePath(p_strPath) != nullptr; + } + + array<Byte>^ BaseScriptImpl::GetExistingDataFile(String^ p_strPath) { + + // Convert to path and normalize separator: + String^ datapath = getDataFilePath(p_strPath); + + if (datapath == nullptr) { + return nullptr; + } + + // Read the first file (should be only one): + return File::ReadAllBytes(datapath); + } + + bool BaseScriptImpl::GenerateDataFile(String^ p_strPath, array<Byte>^ p_bteData) { + + // Check if we already have created an entry for this: + QString qPath = to_qstring(p_strPath); + auto entry = g.DestinationTree->find(qPath); + + QString qAbsPath; + // If the entry is in the list of created files (note: if the entry does not exist, + // find return a nullptr, which is never in g.CreatedEntries). + if (auto it = g.CreatedEntries.find(entry); it != g.CreatedEntries.end()) { + qAbsPath = g.CreatedEntries.at(entry); + } + // Otherwize: Create the entry and the temporary file: + else { + entry = g.DestinationTree->addFile(qPath, true); + qAbsPath = g.InstallManager->createFile(entry); + if (qAbsPath.isEmpty()) { + // Remove the entry from the tree: + entry->detach(); + return false; + } + + // Store the created entry: + g.CreatedEntries[entry] = qAbsPath; + } + + String^ absPath = from_string(qAbsPath); + File::WriteAllBytes(absPath, p_bteData); + return true; + } + + // UI methods: + + DialogResult BaseScriptImpl::ExtendedMessageBox(String^ p_strMessage, String^ p_strTitle, String^ p_strDetails, MessageBoxButtons p_mbbButtons, MessageBoxIcon p_mdiIcon) { + QMessageBox messageBox(g.ParentWidget); + if (!String::IsNullOrEmpty(p_strTitle)) { + messageBox.setWindowTitle(to_qstring(p_strTitle)); + } + messageBox.setText(to_qstring(p_strMessage)); + + if (!String::IsNullOrEmpty(p_strDetails)) { + messageBox.setDetailedText(to_qstring(p_strDetails)); + } + + // For whatever reason MessageBoxIcon has duplicated entries... + switch (p_mdiIcon) { + case MessageBoxIcon::Error: + // case MessageBoxIcon::Stop: + messageBox.setIcon(QMessageBox::Icon::Critical); + break; + case MessageBoxIcon::Asterisk: + // case MessageBoxIcon::Information: + messageBox.setIcon(QMessageBox::Icon::Information); + break; + case MessageBoxIcon::Question: + messageBox.setIcon(QMessageBox::Icon::Question); + break; + case MessageBoxIcon::Exclamation: + // case MessageBoxIcon::Hand: + // case MessageBoxIcon::Warning: + // case MessageBoxIcon::None: + messageBox.setIcon(QMessageBox::Icon::Warning); + case MessageBoxIcon::None: + messageBox.setIcon(QMessageBox::Icon::NoIcon); + break; + } + + QMessageBox::StandardButtons buttons; + + switch (p_mbbButtons) { + case MessageBoxButtons::AbortRetryIgnore: + buttons = QMessageBox::StandardButton::Abort | QMessageBox::StandardButton::Retry | QMessageBox::StandardButton::Ignore; + break; + case MessageBoxButtons::OK: + buttons = QMessageBox::StandardButton::Ok; + break; + case MessageBoxButtons::OKCancel: + buttons = QMessageBox::StandardButton::Ok | QMessageBox::Cancel; + break; + case MessageBoxButtons::RetryCancel: + buttons = QMessageBox::StandardButton::Cancel | QMessageBox::StandardButton::Retry; + break; + case MessageBoxButtons::YesNoCancel: + buttons = QMessageBox::StandardButton::Yes | QMessageBox::No | QMessageBox::Cancel; + break; + case MessageBoxButtons::YesNo: + buttons = QMessageBox::StandardButton::Yes | QMessageBox::No; + break; + } + + messageBox.setStandardButtons(buttons); + + // Only some case are possible here: + switch (messageBox.exec()) { + case QMessageBox::Button::Abort: + return DialogResult::Abort; + case QMessageBox::Button::Cancel: + return DialogResult::Cancel; + case QMessageBox::Button::Ignore: + return DialogResult::Ignore; + case QMessageBox::Button::No: + return DialogResult::No; + case QMessageBox::Button::Ok: + return DialogResult::OK; + case QMessageBox::Button::Retry: + return DialogResult::Retry; + case QMessageBox::Button::Yes: + return DialogResult::Yes; + } + + return DialogResult::None; + } + + + array<int>^ BaseScriptImpl::Select(array<SelectOption^>^ p_sopOptions, String^ p_strTitle, bool p_booSelectMany) { + using namespace System::Collections::Generic; + + QDialog* inputDialog = new QDialog(); + QVBoxLayout* layout = new QVBoxLayout(inputDialog); + inputDialog->setWindowTitle(to_qstring(p_strTitle)); + inputDialog->setLayout(layout); + + layout->setSizeConstraint(QLayout::SetFixedSize); + + if (p_booSelectMany) { + layout->addWidget(new QLabel(QObject::tr("Choose any:"), inputDialog)); + } + else { + layout->addWidget(new QLabel(QObject::tr("Choose one:"), inputDialog)); + } + + QList<QAbstractButton*> items; + for each (SelectOption ^ opt in p_sopOptions) { + QAbstractButton* btn; + if (p_booSelectMany) { + btn = new QCheckBox(to_qstring(opt->Item), inputDialog); + } + else { + btn = new QRadioButton(to_qstring(opt->Item), inputDialog); + } + + if (!String::IsNullOrEmpty(opt->Desc)) { + btn->setToolTip(to_qstring(opt->Desc)); + } + + layout->addWidget(btn); + items.append(btn); + } + + if (!p_booSelectMany && items.size() > 0) { + items[0]->setChecked(true); + } + + QDialogButtonBox* buttonBox = new QDialogButtonBox( + QDialogButtonBox::Cancel | QDialogButtonBox::Ok, inputDialog); + layout->addWidget(buttonBox); + + // Using old signal/slot syntax since the new one does not work here (probably + // due to the C++/CLR nature): + QObject::connect(buttonBox, SIGNAL(accepted()), inputDialog, SLOT(accept())); + QObject::connect(buttonBox, SIGNAL(rejected()), inputDialog, SLOT(reject())); + + inputDialog->setModal(true); + if (inputDialog->exec() != QDialog::Accepted) { + return gcnew array<int>(0); + } + + List<int>^ selected = gcnew List<int>(items.size()); + for (int i = 0; i < items.size(); ++i) { + if (items[i]->isChecked()) { + selected->Add(i); + } + } + + return selected->ToArray(); + } + + // Versioning / INIs: + + // Convert to Version^ from a MO2 version: + inline System::Version^ make_version(VersionInfo version) { + auto qversion = version.asQVersionNumber(); + return gcnew System::Version(qversion.majorVersion(), qversion.minorVersion(), qversion.microVersion()); + + } + + System::Version^ BaseScriptImpl::GetModManagerVersion() { + const auto version = g_Organizer->version(); + return gcnew System::Version(version.major(), version.minor(), version.patch()); + } + + System::Version^ BaseScriptImpl::GetGameVersion() { + return make_version(g_Organizer->managedGame()->gameVersion()); + } + + System::Version^ BaseScriptImpl::GetScriptExtenderVersion() { + auto scriptExtender = g_Organizer->gameFeatures()->gameFeature<ScriptExtender>(); + + if (!scriptExtender || !scriptExtender->isInstalled()) { + return nullptr; + } + + return gcnew System::Version(msclr::interop::marshal_as<String^>(scriptExtender->getExtenderVersion().toStdString())); + } + + bool BaseScriptImpl::ScriptExtenderPresent() { + auto scriptExtender = g_Organizer->gameFeatures()->gameFeature<ScriptExtender>(); + return scriptExtender && scriptExtender->isInstalled(); + } + + // Plugins: + array<String^>^ BaseScriptImpl::GetAllPlugins() { + QStringList names = g_Organizer->pluginList()->pluginNames(); + array<String^>^ result = gcnew array<String^>(names.size()); + for (int i = 0; i < names.size(); ++i) { + result[i] = from_string(names[i].toStdString()); + } + return result; + } + + array<String^>^ BaseScriptImpl::GetActivePlugins() { + auto pluginList = g_Organizer->pluginList(); + QStringList names = pluginList->pluginNames(); + QStringList activeNames; + for (auto& name : names) { + if (pluginList->state(name) == IPluginList::STATE_ACTIVE) { + activeNames.append(name); + } + } + array<String^>^ result = gcnew array<String^>(activeNames.size()); + for (int i = 0; i < activeNames.size(); ++i) { + result[i] = from_string(activeNames[i].toStdString()); + } + return result; + } + + // INIs: + String^ BaseScriptImpl::GetIniString(String^ settingsFileName, String^ section, String^ key) { + + // Check if we have already set this within this installation: + auto fIt = g.Settings.find(to_qstring(settingsFileName)); + if (fIt != g.Settings.end()) { + QString value = fIt->second.value(to_qstring(section), to_qstring(key)); + if (!value.isEmpty()) { + return from_string(value); + } + } + + // Otherwize, look-up the file: + QDir path(g_Organizer->profilePath()); + if (!g_Organizer->profile()->localSettingsEnabled()) { + path = QDir(g_Organizer->managedGame()->documentsDirectory()); + } + + QSettings settings(path.filePath(to_qstring(settingsFileName)), QSettings::IniFormat); + + if (settings.status() != QSettings::NoError) { + return nullptr; + } + + QString name = to_qstring(section + "/" + key); + if (section->Equals("General", System::StringComparison::CurrentCultureIgnoreCase)) { + name = to_qstring(key); + } + + QVariant value = settings.value(name); + if (!value.isValid()) { + return nullptr; + } + + return from_string(value.toString().toStdString()); + } + + int BaseScriptImpl::GetIniInt(String^ settingsFileName, String^ section, String^ key) { + return Convert::ToInt32(GetIniString(settingsFileName, section, key)); + } + + bool BaseScriptImpl::EditIni(String^ p_strSettingsFileName, String^ p_strSection, String^ p_strKey, String^ p_strValue) { + // Check that the file is supported: + bool iniFound = false; + for (auto ini : g_Organizer->managedGame()->iniFiles()) { + if (ini.compare(to_qstring(p_strSettingsFileName), Qt::CaseInsensitive) == 0) { + iniFound = true; + } + } + + if (!iniFound) { + return false; + } + + g.Settings[to_qstring(p_strSettingsFileName)].setValue(to_qstring(p_strSection), to_qstring(p_strKey), to_qstring(p_strValue)); + return true; + } + +} diff --git a/libs/installer_fomod_csharp/src/base_script.h b/libs/installer_fomod_csharp/src/base_script.h new file mode 100644 index 0000000..abfa152 --- /dev/null +++ b/libs/installer_fomod_csharp/src/base_script.h @@ -0,0 +1,552 @@ +/* +Copyright (C) 2020 Holt59. All rights reserved. + +Mod Organizer is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Mod Organizer 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 Mod Organizer. If not, see <http://www.gnu.org/licenses/>. +*/ + +// clang-format off + +#ifndef BASE_SCRIPT_H +#define BASE_SCRIPT_H + +#using <System.dll> +#using <System.Drawing.dll> +#using <System.Windows.Forms.dll> + +#include <uibase/iplugininstaller.h> + +/** + * Note: The specification of BaseScript where taken from the Nexus-Mods installer_fomod extension + * for Vortex: https://github.com/Nexus-Mods/fomod-installer + */ +namespace CSharp { + + using namespace System; + using namespace System::Drawing; + using namespace System::Windows::Forms; + + /// <summary> + /// Describes the options to display in a select form. + /// </summary> + public ref struct SelectOption { + public: + /// <summary> + /// The name of the selection item. + /// </summary> + String^ Item; + + /// <summary> + /// The path to the preview image of the item. + /// </summary> + String^ Preview; + + /// <summary> + /// The description of the selection item. + /// </summary> + String^ Desc; + + /// <summary> + /// A simple constructor that initializes the struct with the given values. + /// </summary> + /// <param name="item">The name of the selection item.</param> + /// <param name="preview">The path to the preview image of the item.</param> + /// <param name="desc">The description of the selection item.</param> + SelectOption(String^ item, String^ preview, String^ desc) { + Item = item; + Preview = preview; + Desc = desc; + } + }; + + /// <summary> + /// The base class for C# scripts. + /// </summary> + public ref class BaseScriptImpl { + public: + + static String^ LastError; + + /// <summary> + /// Returns the last error that occurred. + /// </summary> + /// <returns>The last error that occurred.</returns> + static String^ GetLastError() { + return LastError; + } + + /// <summary> + /// Performs a basic install of the mod. + /// </summary> + /// <remarks> + /// A basic install installs all of the file in the mod to the Data directory + /// or activates all esp and esm files. + /// </remarks> + /// <returns><c>true</c> if the installation succeed; + /// <c>false</c> otherwise.</returns> + static bool PerformBasicInstall(); + + /// <summary> + /// Installs the specified file from the mod to the specified location on the file system. + /// </summary> + /// <remarks> + /// This is the legacy form of <see cref="InstallFileFromMod(string, string)"/>. It now just calls + /// <see cref="InstallFileFromMod(string, string)"/>. + /// </remarks> + /// <param name="p_strFrom">The path of the file in the mod to install.</param> + /// <param name="p_strTo">The path on the file system where the file is to be created.</param> + /// <returns><c>true</c> if the file was written; <c>false</c> otherwise.</returns> + /// <seealso cref="InstallFileFromMod(string, string)"/> + static bool CopyDataFile(String^ p_strFrom, String^ p_strTo) { + return InstallFileFromMod(p_strFrom, p_strTo); + } + + /// <summary> + /// Installs the specified file from the mod to the specified location on the file system. + /// </summary> + /// <param name="p_strFrom">The path of the file in the mod to install.</param> + /// <param name="p_strTo">The path on the file system where the file is to be created.</param> + /// <returns><c>true</c> if the file was written; <c>false</c> otherwise.</returns> + static bool InstallFileFromMod(String^ p_strFrom, String^ p_strTo); + + /// <summary> + /// Installs the speified file from the mod to the file system. + /// </summary> + /// <param name="p_strFile">The path of the file to install.</param> + /// <returns><c>true</c> if the file was written; <c>false</c> otherwise.</returns> + static bool InstallFileFromMod(String^ p_strFile) { + return InstallFileFromMod(p_strFile, p_strFile); + } + + /// <summary> + /// Installs the specified file from the mod to the specified location on the file system. + /// </summary> + /// <param name="p_strFrom">The path of the file in the mod to install.</param> + /// <param name="p_strTo">The path on the file system where the file is to be created.</param> + /// <returns><c>true</c> if the file was written; <c>false</c> otherwise.</returns> + static bool InstallFileFromFomod(String^ p_strFrom, String^ p_strTo) { + return InstallFileFromMod(p_strFrom, p_strTo); + } + + /// <summary> + /// Installs the speified file from the mod to the file system. + /// </summary> + /// <param name="p_strFile">The path of the file to install.</param> + /// <returns><c>true</c> if the file was written; <c>false</c> otherwise.</returns> + static bool InstallFileFromFomod(String^ p_strFile) { + return InstallFileFromMod(p_strFile, p_strFile); + } + + /// <summary> + /// Retrieves the list of files in the mod. + /// </summary> + /// <returns>The list of files in the mod.</returns> + static array<String^>^ GetModFileList(); + + /// <summary> + /// Retrieves the list of files in the mod. + /// </summary> + /// <returns>The list of files in the mod.</returns> + static array<String^>^ GetFomodFileList() { + return GetModFileList(); + } + + /// <summary> + /// Retrieves the specified file from the mod. + /// </summary> + /// <param name="p_strFile">The file to retrieve.</param> + /// <returns>The requested file data.</returns> + static array<Byte>^ GetFileFromMod(String^ p_strFile); + + /// <summary> + /// Retrieves the specified file from the mod. + /// </summary> + /// <param name="p_strFile">The file to retrieve.</param> + /// <returns>The requested file data.</returns> + static array<Byte>^ GetFileFromFomod(String^ p_strFile) { + return GetFileFromMod(p_strFile); + } + + /// <summary> + /// Gets a filtered list of all files in a user's Data directory. + /// </summary> + /// <param name="p_strPath">The subdirectory of the Data directory from which to get the listing.</param> + /// <param name="p_strPattern">The pattern against which to filter the file paths.</param> + /// <param name="p_booAllFolders">Whether or not to search through subdirectories.</param> + /// <returns>A filtered list of all files in a user's Data directory.</returns> + static array<String^>^ GetExistingDataFileList(String^ p_strPath, String^ p_strPattern, bool p_booAllFolders); + + /// <summary> + /// Determines if the specified file exists in the user's Data directory. + /// </summary> + /// <param name="p_strPath">The path of the file whose existence is to be verified.</param> + /// <returns><c>true</c> if the specified file exists; <c>false</c> + /// otherwise.</returns> + static bool DataFileExists(String^ p_strPath); + + /// <summary> + /// Gets the speified file from the user's Data directory. + /// </summary> + /// <param name="p_strPath">The path of the file to retrieve.</param> + /// <returns>The specified file, or <c>null</c> if the file does not exist.</returns> + static array<Byte>^ GetExistingDataFile(String^ p_strPath); + + /// <summary> + /// Writes the file represented by the given byte array to the given path. + /// </summary> + /// <remarks> + /// This method writes the given data as a file at the given path. If the file + /// already exists the user is prompted to overwrite the file. + /// </remarks> + /// <param name="p_strPath">The path where the file is to be created.</param> + /// <param name="p_bteData">The data that is to make up the file.</param> + /// <returns><c>true</c> if the file was written; <c>false</c> otherwise.</returns> + static bool GenerateDataFile(String^ p_strPath, array<Byte>^ p_bteData); + + /// <summary> + /// Shows a message box with the given message. + /// </summary> + /// <param name="p_strMessage">The message to display in the message box.</param> + static void MessageBox(String^ p_strMessage) { + MessageBox(p_strMessage, nullptr); + } + + /// <summary> + /// Shows a message box with the given message and title. + /// </summary> + /// <param name="p_strMessage">The message to display in the message box.</param> + /// <param name="p_strTitle">The message box's title, display in the title bar.</param> + static void MessageBox(String^ p_strMessage, String^ p_strTitle) { + MessageBox(p_strMessage, p_strTitle, MessageBoxButtons::OK); + } + + /// <summary> + /// Shows a message box with the given message, title, and buttons. + /// </summary> + /// <param name="p_strMessage">The message to display in the message box.</param> + /// <param name="p_strTitle">The message box's title, display in the title bar.</param> + /// <param name="p_mbbButtons">The buttons to show in the message box.</param> + static DialogResult MessageBox(String^ p_strMessage, String^ p_strTitle, MessageBoxButtons p_mbbButtons) { + return MessageBox(p_strMessage, p_strTitle, p_mbbButtons, MessageBoxIcon::Information); + } + + static DialogResult MessageBox(String^ p_strMessage, String^ p_strTitle, MessageBoxButtons p_mbbButtons, MessageBoxIcon p_mdiIcon) { + return ExtendedMessageBox(p_strMessage, p_strTitle, nullptr, p_mbbButtons, p_mdiIcon); + } + + /// <summary> + /// Shows an extended message box with the given message, title, details, buttons, and icon. + /// </summary> + /// <param name="p_strMessage">The message to display in the message box.</param> + /// <param name="p_strTitle">The message box's title, displayed in the title bar.</param> + /// <param name="p_strDetails">The message box's details, displayed in the details area.</param> + /// <param name="p_mbbButtons">The buttons to show in the message box.</param> + /// <param name="p_mdiIcon">The icon to display in the message box.</param> + static DialogResult ExtendedMessageBox(String^ p_strMessage, String^ p_strTitle, String^ p_strDetails, MessageBoxButtons p_mbbButtons, MessageBoxIcon p_mdiIcon); + + /// <summary> + /// Displays a selection form to the user. + /// </summary> + /// <param name="p_sopOptions">The options from which to select.</param> + /// <param name="p_strTitle">The title of the selection form.</param> + /// <param name="p_booSelectMany">Whether more than one item can be selected.</param> + /// <returns>The indices of the selected items.</returns> + static array<int>^ Select(array<SelectOption^>^ p_sopOptions, String^ p_strTitle, bool p_booSelectMany); + + /// <summary> + /// Displays a selection form to the user. + /// </summary> + /// <remarks> + /// The items, previews, and descriptions are repectively ordered. In other words, + /// the i-th item in <paramref name="p_strItems"/> uses the i-th preview in + /// <paramref name="p_strPreviewPaths"/> and the i-th description in <paramref name="p_strDescriptions"/>. + /// + /// Similarly, the idices return as results correspond to the indices of the items in + /// <paramref name="p_strItems"/>. + /// </remarks> + /// <param name="p_strItems">The items from which to select.</param> + /// <param name="p_strPreviewPaths">The preview image file names for the items.</param> + /// <param name="p_strDescriptions">The descriptions of the items.</param> + /// <param name="p_strTitle">The title of the selection form.</param> + /// <param name="p_booSelectMany">Whether more than one item can be selected.</param> + /// <returns>The indices of the selected items.</returns> + static array<int>^ Select(array<String^>^ p_strItems, array<String^>^ p_strPreviewPaths, array<String^>^ p_strDescriptions, String^ p_strTitle, bool p_booSelectMany) { + const int size = p_strItems->GetLength(0); + array<SelectOption^>^ options = gcnew array<SelectOption^>(size); + for (int i = 0; i < size; ++i) { + options[i] = gcnew SelectOption(p_strItems[i], p_strPreviewPaths[i], p_strDescriptions[i]); + } + return Select(options, p_strTitle, p_booSelectMany); + } + + /// <summary> + /// Displays a selection form to the user. + /// </summary> + /// <remarks> + /// The items, previews, and descriptions are repectively ordered. In other words, + /// the i-th item in <paramref name="p_strItems"/> uses the i-th preview in + /// <paramref name="p_imgPreviews"/> and the i-th description in <paramref name="p_strDescriptions"/>. + /// + /// Similarly, the idices return as results correspond to the indices of the items in + /// <paramref name="p_strItems"/>. + /// </remarks> + /// <param name="p_strItems">The items from which to select.</param> + /// <param name="p_imgPreviews">The preview images for the items.</param> + /// <param name="p_strDescriptions">The descriptions of the items.</param> + /// <param name="p_strTitle">The title of the selection form.</param> + /// <param name="p_booSelectMany">Whether more than one item can be selected.</param> + /// <returns>The indices of the selected items.</returns> + static array<int>^ ImageSelect(array<String^>^ p_strItems, array<Image^>^ /* p_imgPreviews */, array<String^>^ p_strDescriptions, String^ p_strTitle, bool p_booSelectMany) { + return Select(p_strItems, gcnew array<String^>(p_strItems->Length), p_strDescriptions, p_strTitle, p_booSelectMany); + } + + /// <summary> + /// Creates a form that can be used in custom mod scripts. + /// </summary> + /// <returns>A form that can be used in custom mod scripts.</returns> + static Form^ CreateCustomForm() { + Form^ form = gcnew Form; + return form; + } + + /// <summary> + /// Gets the version of the mod manager. + /// </summary> + /// <returns>The version of the mod manager.</returns> + static System::Version^ GetModManagerVersion(); + + /// <summary> + /// Gets the version of the game that is installed. + /// </summary> + /// <returns>The version of the game, or <c>null</c> if Fallout + /// is not installed.</returns> + static System::Version^ GetGameVersion(); + + // This is not in the spec., but I do not see a point in checking each + // script extender in a different way. + static System::Version^ GetScriptExtenderVersion(); + + /// <summary> + /// Gets the script extender version or null if it's not installed + /// </summary> + /// <returns></returns> + static System::Version^ GetSkseVersion() { + return GetScriptExtenderVersion(); + } + + /// <summary> + /// Gets the script extender version or null if it's not installed + /// </summary> + /// <returns></returns> + static System::Version^ GetFoseVersion() { + return GetScriptExtenderVersion(); + } + + /// <summary> + /// Gets the script extender version or null if it's not installed + /// </summary> + /// <returns></returns> + static System::Version^ GetNvseVersion() { + return GetScriptExtenderVersion(); + } + + /// <summary> + /// Gets the version of the mod manager. + /// </summary> + /// <returns>The version of the mod manager.</returns> + static System::Version^ GetFommVersion() { + return GetModManagerVersion(); + } + + /// <summary> + /// Gets the version of the game that is installed. + /// </summary> + /// <returns>The version of the game, or <c>null</c> if Fallout + /// is not installed.</returns> + static System::Version^ GetFalloutVersion() { + // I think this is an old function... What Fallout anyway? So just going + // to return the game version, whatever current game. + return GetGameVersion(); + } + + /// <summary> + /// Determins if the script extender for the game is installed + /// (this checks for the script extender of the game for which the + /// mod is being installed) + /// </summary> + /// <returns></returns> + static bool ScriptExtenderPresent(); + + /// <summary> + /// Gets a list of all install plugins. + /// </summary> + /// <returns>A list of all install plugins.</returns> + static array<String^>^ GetAllPlugins(); + + /// <summary> + /// Retrieves a list of currently active plugins. + /// </summary> + /// <returns>A list of currently active plugins.</returns> + static array<String^>^ GetActivePlugins(); + + /// <summary> + /// Sets the activated status of a plugin (i.e., and esp or esm file). + /// </summary> + /// <param name="p_strPluginPath">The path to the plugin to activate or deactivate.</param> + /// <param name="p_booActivate">Whether to activate the plugin.</param> + static void SetPluginActivation(String^ /* p_strPluginPath */, bool /* p_booActivate */) { + // throw gcnew NotImplementedException("SetPluginActivation"); + } + + /// <summary> + /// Sets the load order of the specifid plugin. + /// </summary> + /// <param name="p_strPlugin">The path to the plugin file whose load order is to be set.</param> + /// <param name="p_intNewIndex">The new load order index of the plugin.</param> + static void SetPluginOrderIndex(String^ /* p_strPlugin */, int /* p_intNewIndex */) { + // throw gcnew NotImplementedException("SetPluginOrderIndex"); + } + + /// <summary> + /// Sets the load order of the plugins. + /// </summary> + /// <remarks> + /// Each plugin will be moved from its current index to its indices' position + /// in <paramref name="p_intPlugins"/>. + /// </remarks> + /// <param name="p_intPlugins">The new load order of the plugins. Each entry in this array + /// contains the current index of a plugin. This array must contain all current indices.</param> + static void SetLoadOrder(array<int>^ /* p_intPlugins */) { + // throw gcnew NotImplementedException("SetLoadOrder"); + } + + /// <summary> + /// Moves the specified plugins to the given position in the load order. + /// </summary> + /// <remarks> + /// Note that the order of the given list of plugins is not maintained. They are re-ordered + /// to be in the same order as they are in the before-operation load order. This, I think, + /// is somewhat counter-intuitive and may change, though likely not so as to not break + /// backwards compatibility. + /// </remarks> + /// <param name="p_intPlugins">The list of plugins to move to the given position in the + /// load order. Each entry in this array contains the current index of a plugin.</param> + /// <param name="p_intPosition">The position in the load order to which to move the specified + /// plugins.</param> + static void SetLoadOrder(array<int>^ /* p_intPlugins */, int /* p_intPosition */) { + // throw gcnew NotImplementedException("SetLoadOrder"); + } + + /// <summary> + /// Retrieves the specified settings value as a string. + /// </summary> + /// <param name="settingsFileName">The name of the settings file from which to retrieve the value.</param> + /// <param name="section">The section containing the value to retrieve.</param> + /// <param name="key">The key of the value to retrieve.</param> + /// <returns>The specified value as a string.</returns> + static String^ GetIniString(String^ settingsFileName, String^ section, String^ key); + + /// <summary> + /// Retrieves the specified settings value as an integer. + /// </summary> + /// <param name="settingsFileName">The name of the settings file from which to retrieve the value.</param> + /// <param name="section">The section containing the value to retrieve.</param> + /// <param name="key">The key of the value to retrieve.</param> + /// <returns>The specified value as an integer.</returns> + static int GetIniInt(String^ settingsFileName, String^ section, String^ key); + + /// <summary> + /// Retrieves the specified Fallout.ini value as a string. + /// </summary> + /// <param name="section">The section containing the value to retrieve.</param> + /// <param name="key">The key of the value to retrieve.</param> + /// <returns>The specified value as a string.</returns> + /// <seealso cref="GetFalloutIniInt(string, string)"/> + static String^ GetFalloutIniString(String^ section, String^ key) { + return GetIniString("Fallout.ini", section, key); + } + + /// <summary> + /// Retrieves the specified Fallout.ini value as an integer. + /// </summary> + /// <param name="section">The section containing the value to retrieve.</param> + /// <param name="key">The key of the value to retrieve.</param> + /// <seealso cref="GetFalloutIniString(string, string)"/> + static int GetFalloutIniInt(String^ section, String^ key) { + return GetIniInt("Fallout.ini", section, key); + } + + /// <summary> + /// Retrieves the specified FalloutPrefs.ini value as a string. + /// </summary> + /// <param name="p_strSection">The section containing the value to retrieve.</param> + /// <param name="p_strKey">The key of the value to retrieve.</param> + /// <returns>The specified value as a string.</returns> + /// <seealso cref="GetPrefsIniInt(string, string)"/> + static String^ GetPrefsIniString(String^ p_strSection, String^ p_strKey) { + // This looks wrong? Yes! But that's what used in other mod managers... + return GetIniString("FalloutPrefs.ini", p_strSection, p_strKey); + } + + /// <summary> + /// Retrieves the specified FalloutPrefs.ini value as an integer. + /// </summary> + /// <param name="p_strSection">The section containing the value to retrieve.</param> + /// <param name="p_strKey">The key of the value to retrieve.</param> + /// <returns>The specified value as an integer.</returns> + /// <seealso cref="GetPrefsIniString(string, string)"/> + static int GetPrefsIniInt(String^ p_strSection, String^ p_strKey) { + // This looks wrong? Yes! But that's what used in other mod managers... + return GetIniInt("FalloutPrefs.ini", p_strSection, p_strKey); + } + + /// <summary> + /// Sets the specified value in the specified Ini file to the given value. + /// </summary> + /// <param name="p_strSettingsFileName">The name of the settings file to edit.</param> + /// <param name="p_strSection">The section in the Ini file to edit.</param> + /// <param name="p_strKey">The key in the Ini file to edit.</param> + /// <param name="p_strValue">The value to which to set the key.</param> + /// <returns><c>true</c> if the value was set; <c>false</c> + /// if the user chose not to overwrite the existing value.</returns> + static bool EditIni(String^ p_strSettingsFileName, String^ p_strSection, String^ p_strKey, String^ p_strValue); + + /// <summary> + /// Sets the specified value in the Fallout.ini file to the given value. + /// </summary> + /// <param name="p_strSection">The section in the Ini file to edit.</param> + /// <param name="p_strKey">The key in the Ini file to edit.</param> + /// <param name="p_strValue">The value to which to set the key.</param> + /// <param name="p_booSaveOld">Not used.</param> + /// <returns><c>true</c> if the value was set; <c>false</c> + /// if the user chose not to overwrite the existing value.</returns> + static bool EditFalloutINI(String^ p_strSection, String^ p_strKey, String^ p_strValue, bool /* p_booSaveOld */) { + return EditIni("Fallout.ini", p_strSection, p_strKey, p_strValue); + } + + }; + + /** + * @brief Post-install script. + */ + MOBase::IPluginInstaller::EInstallResult postInstall(std::shared_ptr<MOBase::IFileTree>& tree); +} + +// BaseScript cannot be in a namespace: +public ref struct SelectOption: public CSharp::SelectOption { + SelectOption(System::String^ item, System::String^ preview, System::String^ desc) : + CSharp::SelectOption(item, preview, desc) { } +}; +public ref class BaseScript: public CSharp::BaseScriptImpl { }; + +#endif diff --git a/libs/installer_fomod_csharp/src/csharp_interface.cpp b/libs/installer_fomod_csharp/src/csharp_interface.cpp new file mode 100644 index 0000000..91a4a0d --- /dev/null +++ b/libs/installer_fomod_csharp/src/csharp_interface.cpp @@ -0,0 +1,157 @@ +#include "csharp_interface.h" + +#include <fstream> +#include <regex> +#include <sstream> + +#include <uibase/log.h> + +#include "base_script.h" +#include "csharp_utils.h" + +// clang-format off + +#using <System.dll> + +using namespace MOBase; + +/** + * This is a assembly resolve handler that does only one thing: returns the assembly + * containing BaseScript (usually the DLL) when requested. + * + * I don't know why this must be done manually... But I did not find any better solution. + */ +System::Reflection::Assembly^ currentDomain_AssemblyResolve(System::Object^, System::ResolveEventArgs^ args) +{ + using namespace System::Reflection; + + try { + Assembly^ baseScriptAssembly = System::Reflection::Assembly::GetAssembly(BaseScript::typeid); + if (args->Name->Equals(baseScriptAssembly->FullName)) { + return baseScriptAssembly; + } + } + catch (...) + { + } + + return nullptr; +} + +IPluginInstaller::EInstallResult executeScript(System::String^ script) { + + using namespace System; + using namespace System::CodeDom; + using namespace System::CodeDom::Compiler; + using namespace System::Collections::Generic; + + AppDomain^ currentDomain = AppDomain::CurrentDomain; + currentDomain->AssemblyResolve += gcnew ResolveEventHandler(currentDomain_AssemblyResolve); + + // From Nexus-Mods/fomod-installer: + Dictionary<String^, String^>^ dicOptions = gcnew Dictionary<String^, String^>(10); + dicOptions->Add("CompilerVersion", "v4.0"); + + // List of assemblies (including BaseScript) - From Nexus-Mods/fomod-installer: + array<String^>^ referenceAssemblies = { + "System.dll", + "System.Runtime.dll", + "System.Drawing.dll", + "System.Windows.Forms.dll", + "System.Xml.dll", + System::Reflection::Assembly::GetAssembly(BaseScript::typeid)->Location + }; + + CompilerParameters^ cp = gcnew CompilerParameters(referenceAssemblies); + cp->GenerateExecutable = false; + cp->IncludeDebugInformation = false; + cp->GenerateInMemory = true; + cp->TreatWarningsAsErrors = false; + CodeDomProvider^ provider = CodeDomProvider::CreateProvider("CSharp", dicOptions); + + // Compile the script + auto result = provider->CompileAssemblyFromSource(cp, script); + + int errorCount = 0; + for each (CompilerError ^ error in result->Errors) { + if (error->IsWarning) { + log::warn("C# [{}]: {}", error->Line, CSharp::to_string(error->ErrorText)); + } + else { + log::error("C# [{}]: {}", error->Line, CSharp::to_string(error->ErrorText)); + ++errorCount; + } + } + + if (errorCount > 0) { + return IPluginInstaller::EInstallResult::RESULT_FAILED; + } + + // Execute the script: + try { + auto scriptClass = result->CompiledAssembly->GetType("Script"); + BaseScript^ scriptObject = (BaseScript^)System::Activator::CreateInstance(scriptClass); + auto onActivateMethod = scriptObject->GetType()->GetMethod("OnActivate"); + + auto success = (bool)(onActivateMethod->IsStatic ? onActivateMethod->Invoke(nullptr, nullptr) : onActivateMethod->Invoke(scriptObject, nullptr)); + return success ? IPluginInstaller::EInstallResult::RESULT_SUCCESS : IPluginInstaller::EInstallResult::RESULT_CANCELED; + } + catch (System::Exception^ ex) { + log::error("C# ({}): {}\n{}", CSharp::to_string(ex->GetType()->FullName), CSharp::to_string(ex->Message), CSharp::to_string(ex->StackTrace)); + System::Exception^ innerEx = ex->InnerException; + if (innerEx) { + log::error("C# ({}): {}\n{}", CSharp::to_string(innerEx->GetType()->FullName), CSharp::to_string(innerEx->Message), CSharp::to_string(innerEx->StackTrace)); + } + return IPluginInstaller::EInstallResult::RESULT_FAILED; + } + +} + +namespace CSharp { + + IPluginInstaller::EInstallResult executeCSharpScript(QString scriptPath, std::shared_ptr<IFileTree>& tree) { + + using namespace System; + using namespace System::IO; + using namespace System::Text::RegularExpressions; + + // Note: Using C# stuff here to mimicate NMM since there are some encoding issues, and + // some regex do not work in C++: + array<Byte>^ scriptBytes = File::ReadAllBytes(from_string(scriptPath.toStdWString())); + + // Read the script (using C# to "auto-detect" encoding in a C# way): + String^ script; + { + auto memoryStream = gcnew MemoryStream(scriptBytes); + auto reader = gcnew StreamReader(memoryStream, true); + + script = reader->ReadToEnd(); + + reader->Close(); + memoryStream->Close(); + + delete reader; + delete memoryStream; + } + + + Regex^ regScriptClass = gcnew Regex(R"re((class\s+Script\s*:.*?)(\S*BaseScript))re"); + Regex^ regFommUsing = gcnew Regex(R"re(\s*using\s*fomm.Scripting\s*;)re"); + + String^ strBaseScriptClassName = regScriptClass->Match(script)->Groups[2]->ToString(); + Regex^ regOtherScriptClasses = gcnew Regex(String::Format(R"re((class\s+\S+\s*:.*?)(?<!\w){0})re", strBaseScriptClassName)); + String^ strCode = script; + strCode = regScriptClass->Replace(strCode, "$1BaseScript"); + strCode = regOtherScriptClasses->Replace(strCode, "$1BaseScript"); + strCode = regFommUsing->Replace(strCode, ""); + + auto result = executeScript(strCode); + + if (result != IPluginInstaller::EInstallResult::RESULT_SUCCESS) { + return result; + } + + return postInstall(tree); + } + +} diff --git a/libs/installer_fomod_csharp/src/csharp_interface.h b/libs/installer_fomod_csharp/src/csharp_interface.h new file mode 100644 index 0000000..4f22c20 --- /dev/null +++ b/libs/installer_fomod_csharp/src/csharp_interface.h @@ -0,0 +1,40 @@ +#ifndef CSHARP_INTERFACE_H +#define CSHARP_INTERFACE_H + +#include <map> + +#include <uibase/ifiletree.h> +#include <uibase/iplugininstaller.h> + +namespace CSharp +{ + +void init(MOBase::IOrganizer* moInfo); + +/** + * @brief Initialize the C# interface before starting an installation. + * + * @param installer The FOMOD C# installer. + * @param manager The installation manager from the installer. + * @param parentWidget The parent widget from the installer. + * @param tree The archive tree. + * @param extractedEntries A map from extracted entries to their extracted path. + */ +void beforeInstall( + MOBase::IPlugin const* installer, MOBase::IInstallationManager* manager, + QWidget* parentWidget, std::shared_ptr<MOBase::IFileTree> tree, + std::map<std::shared_ptr<const MOBase::FileTreeEntry>, QString> extractedEntries); + +/** + * @brief Clear the C# interface after an installation. + * + * @param scriptPath Path to the script to execute. + * @param tree Reference where the final tree will be stored (in case of success. + * + * @return the installation result after performing post-installation. + */ +MOBase::IPluginInstaller::EInstallResult +executeCSharpScript(QString scriptPath, std::shared_ptr<MOBase::IFileTree>& tree); + +} // namespace CSharp +#endif diff --git a/libs/installer_fomod_csharp/src/csharp_utils.h b/libs/installer_fomod_csharp/src/csharp_utils.h new file mode 100644 index 0000000..5ede874 --- /dev/null +++ b/libs/installer_fomod_csharp/src/csharp_utils.h @@ -0,0 +1,41 @@ +// clang-format off + +#ifndef CSHARP_UTILS_H +#define CSHARP_UTILS_H + +#include <type_traits> +#include <string> + +#include <QString> + +#include <msclr\marshal_cppstd.h> + +#using <System.dll> + +namespace CSharp { + + /** + * Handy functions. + */ + inline std::string to_string(System::String^ value) { + return msclr::interop::marshal_as<std::string>(value); + } + inline std::wstring to_wstring(System::String^ value) { + return msclr::interop::marshal_as<std::wstring>(value); + } + inline QString to_qstring(System::String^ value) { + msclr::interop::marshal_context ctx; + return QString::fromWCharArray(ctx.marshal_as<const wchar_t*>(value)); + } + + template <class Str> + inline System::String^ from_string(Str const& string) { + return msclr::interop::marshal_as<System::String^>(string); + } + inline System::String^ from_string(QString const& string) { + return msclr::interop::marshal_as<System::String^>(string.toStdWString().c_str()); + } + +} + +#endif diff --git a/libs/installer_fomod_csharp/src/installer_fomod_csharp.cpp b/libs/installer_fomod_csharp/src/installer_fomod_csharp.cpp new file mode 100644 index 0000000..02d3a3e --- /dev/null +++ b/libs/installer_fomod_csharp/src/installer_fomod_csharp.cpp @@ -0,0 +1,193 @@ +/* +Copyright (C) 2020 Holt59. All rights reserved. + +Mod Organizer is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Mod Organizer 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 Mod Organizer. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include <uibase/iinstallationmanager.h> + +#include "csharp_interface.h" +#include "installer_fomod_csharp.h" +#include "installer_fomod_predialog.h" +#include "xml_info_reader.h" + +using namespace MOBase; + +bool InstallerFomodCSharp::init(IOrganizer* moInfo) +{ + m_MOInfo = moInfo; + CSharp::init(moInfo); + return true; +} + +std::shared_ptr<const IFileTree> +InstallerFomodCSharp::findFomodDirectory(std::shared_ptr<const IFileTree> tree) const +{ + auto entry = tree->find("fomod", FileTreeEntry::DIRECTORY); + + if (entry != nullptr) { + return entry->astree(); + } + + if (tree->empty()) { + return nullptr; + } + + // We need at least a directory: + if (!tree->at(0)->isDir()) { + return nullptr; + } + + // But not two: + if (tree->size() > 1 && tree->at(1)->isDir()) { + return nullptr; + } + + return findFomodDirectory(tree->at(0)->astree()); +} + +std::shared_ptr<const FileTreeEntry> +InstallerFomodCSharp::findScriptFile(std::shared_ptr<const IFileTree> tree) const +{ + auto fomodDirectory = findFomodDirectory(tree); + + if (fomodDirectory == nullptr) { + return nullptr; + } + + for (auto e : *fomodDirectory) { + if (e->isFile() && e->suffix().compare("cs", Qt::CaseInsensitive) == 0) { + return e; + } + } + + return nullptr; +} + +std::shared_ptr<const FileTreeEntry> +InstallerFomodCSharp::findInfoFile(std::shared_ptr<const IFileTree> tree) const +{ + auto fomodDirectory = findFomodDirectory(tree); + + if (fomodDirectory == nullptr) { + return nullptr; + } + + for (auto e : *fomodDirectory) { + if (e->isFile() && e->compare("info.xml") == 0) { + return e; + } + } + + return nullptr; +} + +bool InstallerFomodCSharp::isArchiveSupported( + std::shared_ptr<const MOBase::IFileTree> tree) const +{ + return findScriptFile(tree) != nullptr; +} + +InstallerFomodCSharp::EInstallResult +InstallerFomodCSharp::install(MOBase::GuessedValue<QString>& modName, + std::shared_ptr<MOBase::IFileTree>& tree, + QString& version, int& modID) +{ + static std::set<QString, FileNameComparator> imageSuffixes{"png", "jpg", "jpeg", + "gif", "bmp"}; + + // Extract the script file: + auto scriptFile = findScriptFile(tree); + if (scriptFile == nullptr) { + return EInstallResult::RESULT_NOTATTEMPTED; + } + + // Check if there is a info.xml: + auto infoFile = findInfoFile(tree); + + // Set containing everything to extract except the script and the info file: + std::set<std::shared_ptr<const FileTreeEntry>> toExtractSet{scriptFile}; + + if (infoFile != nullptr) { + toExtractSet.insert(infoFile); + } + + // Extract all the images: + tree->walk([&](const QString&, auto entry) { + if (entry->isFile() && imageSuffixes.count(entry->suffix()) > 0) { + toExtractSet.insert(entry); + } + return IFileTree::WalkReturn::CONTINUE; + }); + + // Extract everything from the fomod/ folder: + auto fomodFolder = findFomodDirectory(tree); + fomodFolder->walk([&](const QString&, auto entry) { + if (entry->isFile()) { + toExtractSet.insert(entry); + } + return IFileTree::WalkReturn::CONTINUE; + }); + + // Convert to vector: + std::vector toExtract(std::begin(toExtractSet), std::end(toExtractSet)); + QStringList paths(manager()->extractFiles(toExtract)); + + // If user cancelled: + if (toExtract.size() != static_cast<std::size_t>(paths.size())) { + return EInstallResult::RESULT_CANCELED; + } + + // Create a map from entry to file path: + std::map<std::shared_ptr<const FileTreeEntry>, QString> entryToPath; + for (std::size_t i = 0; i < toExtract.size(); ++i) { + entryToPath[toExtract[i]] = paths[i]; + } + + if (infoFile != nullptr) { + QFile file(entryToPath[infoFile]); + if (file.open(QIODevice::ReadOnly)) { + auto info = FomodInfoReader::readXml(file, &FomodInfoReader::parseInfo); + if (!std::get<0>(info).isEmpty()) { + modName.update(std::get<0>(info), GUESS_META); + } + if (std::get<1>(info) != -1) { + modID = std::get<1>(info); + } + if (!std::get<2>(info).isEmpty()) { + version = std::get<2>(info); + } + } + } + + // Show the dialog: + InstallerFomodPredialog dialog(modName, parentWidget()); + if (dialog.exec() != QDialog::Accepted) { + if (dialog.manualRequested()) { + modName.update(dialog.getName(), GUESS_USER); + return EInstallResult::RESULT_MANUALREQUESTED; + } else { + return EInstallResult::RESULT_CANCELED; + } + } + modName.update(dialog.getName(), GUESS_USER); + + // Run the C# script: + const QString scriptPath = entryToPath[scriptFile]; + CSharp::beforeInstall( + this, manager(), parentWidget(), + std::const_pointer_cast<IFileTree>(scriptFile->parent()->parent()), + std::move(entryToPath)); + return CSharp::executeCSharpScript(scriptPath, tree); +} diff --git a/libs/installer_fomod_csharp/src/installer_fomod_csharp.h b/libs/installer_fomod_csharp/src/installer_fomod_csharp.h new file mode 100644 index 0000000..530db37 --- /dev/null +++ b/libs/installer_fomod_csharp/src/installer_fomod_csharp.h @@ -0,0 +1,84 @@ +/* +Copyright (C) 2020 Holt59. All rights reserved. + +Mod Organizer is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Mod Organizer 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 Mod Organizer. If not, see <http://www.gnu.org/licenses/>. +*/ + +#ifndef INSTALLER_FOMOD_CSHARP_H +#define INSTALLER_FOMOD_CSHARP_H + +#include <uibase/iplugininstallersimple.h> + +class InstallerFomodCSharp : public MOBase::IPluginInstallerSimple +{ + Q_OBJECT + Q_INTERFACES(MOBase::IPlugin MOBase::IPluginInstaller MOBase::IPluginInstallerSimple) + Q_PLUGIN_METADATA(IID "org.holt59.InstallerFomodCSharp") + +public: + InstallerFomodCSharp() {} + + virtual bool init(MOBase::IOrganizer* moInfo) override; + + virtual QString name() const override { return "Fomod Installer C#"; } + + virtual QString localizedName() const override { return tr("Fomod Installer C#"); } + + virtual QString author() const override { return "Holt59"; } + + virtual QString description() const override + { + return tr("Installer for C# based FOMOD archives."); + } + + virtual MOBase::VersionInfo version() const override + { + return MOBase::VersionInfo(1, 0, 0, MOBase::VersionInfo::RELEASE_BETA); + } + + virtual QList<MOBase::PluginSetting> settings() const override + { + return { + MOBase::PluginSetting("enabled", "check to enable this plugin", QVariant(true)), + MOBase::PluginSetting("prefer", "prefer this over the NCC based plugin", + QVariant(true))}; + } + + virtual unsigned int priority() const override + { + // It's the same priority as the FOMOD installer but those should never conflict: + return m_MOInfo->pluginSetting(name(), "prefer").toBool() ? 110 : 90; + } + + virtual bool isManualInstaller() const override { return false; } + + virtual bool + isArchiveSupported(std::shared_ptr<const MOBase::IFileTree> tree) const override; + + virtual EInstallResult install(MOBase::GuessedValue<QString>& modName, + std::shared_ptr<MOBase::IFileTree>& tree, + QString& version, int& modID) override; + +private: + MOBase::IOrganizer* m_MOInfo; + + std::shared_ptr<const MOBase::IFileTree> + findFomodDirectory(std::shared_ptr<const MOBase::IFileTree> tree) const; + std::shared_ptr<const MOBase::FileTreeEntry> + findScriptFile(std::shared_ptr<const MOBase::IFileTree> tree) const; + std::shared_ptr<const MOBase::FileTreeEntry> + findInfoFile(std::shared_ptr<const MOBase::IFileTree> tree) const; +}; + +#endif diff --git a/libs/installer_fomod_csharp/src/installer_fomod_csharp_en.ts b/libs/installer_fomod_csharp/src/installer_fomod_csharp_en.ts new file mode 100644 index 0000000..7c13b6c --- /dev/null +++ b/libs/installer_fomod_csharp/src/installer_fomod_csharp_en.ts @@ -0,0 +1,125 @@ +<?xml version="1.0" encoding="utf-8"?> +<!DOCTYPE TS> +<TS version="2.1" language="en_US"> +<context> + <name>FomodCSharpPostDialog</name> + <message> + <location filename="installer_fomod_csharp_postdialog.ui" line="14"/> + <source>Settings modification required</source> + <translation type="unfinished"></translation> + </message> + <message> + <location filename="installer_fomod_csharp_postdialog.ui" line="20"/> + <source>The installer needs to edit the following settings. You can either apply them, discard them or move them to the mod installation folder (under INI Tweaks).</source> + <translation type="unfinished"></translation> + </message> + <message> + <location filename="installer_fomod_csharp_postdialog.ui" line="56"/> + <source>Apply the settings to the INI files corresponding to the current profile.</source> + <translation type="unfinished"></translation> + </message> + <message> + <location filename="installer_fomod_csharp_postdialog.ui" line="59"/> + <source>Apply</source> + <translation type="unfinished"></translation> + </message> + <message> + <location filename="installer_fomod_csharp_postdialog.ui" line="66"/> + <source>Discard the settings.</source> + <translation type="unfinished"></translation> + </message> + <message> + <location filename="installer_fomod_csharp_postdialog.ui" line="69"/> + <source>Discard</source> + <translation type="unfinished"></translation> + </message> + <message> + <location filename="installer_fomod_csharp_postdialog.ui" line="76"/> + <source>Create files under "INI Tweaks" in the mod folder with these settings.</source> + <translation type="unfinished"></translation> + </message> + <message> + <location filename="installer_fomod_csharp_postdialog.ui" line="79"/> + <source>INI Tweaks</source> + <translation type="unfinished"></translation> + </message> + <message> + <location filename="installer_fomod_csharp_postdialog.ui" line="86"/> + <source>Cancel the installation.</source> + <translation type="unfinished"></translation> + </message> + <message> + <location filename="installer_fomod_csharp_postdialog.ui" line="89"/> + <source>Cancel</source> + <translation type="unfinished"></translation> + </message> +</context> +<context> + <name>FomodCSharpPredialog</name> + <message> + <location filename="installer_fomod_csharp_predialog.ui" line="14"/> + <source>FOMOD C# Installer</source> + <translation type="unfinished"></translation> + </message> + <message> + <location filename="installer_fomod_csharp_predialog.ui" line="22"/> + <source>Name</source> + <translation type="unfinished"></translation> + </message> + <message> + <location filename="installer_fomod_csharp_predialog.ui" line="40"/> + <location filename="installer_fomod_csharp_predialog.ui" line="43"/> + <source>Opens a Dialog that allows custom modifications.</source> + <translation type="unfinished"></translation> + </message> + <message> + <location filename="installer_fomod_csharp_predialog.ui" line="46"/> + <source>Manual</source> + <translation type="unfinished"></translation> + </message> + <message> + <location filename="installer_fomod_csharp_predialog.ui" line="69"/> + <source>Start</source> + <translation type="unfinished"></translation> + </message> + <message> + <location filename="installer_fomod_csharp_predialog.ui" line="79"/> + <source>Cancel</source> + <translation type="unfinished"></translation> + </message> +</context> +<context> + <name>FomodInfoReader</name> + <message> + <location filename="xml_info_reader.h" line="109"/> + <source>Failed to parse %1. See console for details.</source> + <translation type="unfinished"></translation> + </message> +</context> +<context> + <name>InstallerFomodCSharp</name> + <message> + <location filename="installer_fomod_csharp.h" line="36"/> + <source>Fomod Installer C#</source> + <translation type="unfinished"></translation> + </message> + <message> + <location filename="installer_fomod_csharp.h" line="42"/> + <source>Installer for C# based FOMOD archives.</source> + <translation type="unfinished"></translation> + </message> +</context> +<context> + <name>QObject</name> + <message> + <location filename="base_script.cpp" line="516"/> + <source>Choose any:</source> + <translation type="unfinished"></translation> + </message> + <message> + <location filename="base_script.cpp" line="519"/> + <source>Choose one:</source> + <translation type="unfinished"></translation> + </message> +</context> +</TS> diff --git a/libs/installer_fomod_csharp/src/installer_fomod_csharp_postdialog.ui b/libs/installer_fomod_csharp/src/installer_fomod_csharp_postdialog.ui new file mode 100644 index 0000000..89a6106 --- /dev/null +++ b/libs/installer_fomod_csharp/src/installer_fomod_csharp_postdialog.ui @@ -0,0 +1,99 @@ +<?xml version="1.0" encoding="UTF-8"?> +<ui version="4.0"> + <class>FomodCSharpPostDialog</class> + <widget class="QDialog" name="FomodCSharpPostDialog"> + <property name="geometry"> + <rect> + <x>0</x> + <y>0</y> + <width>589</width> + <height>399</height> + </rect> + </property> + <property name="windowTitle"> + <string>Settings modification required</string> + </property> + <layout class="QVBoxLayout" name="verticalLayout"> + <item> + <widget class="QLabel" name="label"> + <property name="text"> + <string>The installer needs to edit the following settings. You can either apply them, discard them or move them to the mod installation folder (under INI Tweaks).</string> + </property> + <property name="wordWrap"> + <bool>true</bool> + </property> + </widget> + </item> + <item> + <layout class="QHBoxLayout" name="horizontalLayout"> + <item> + <widget class="QTabWidget" name="tabWidget"> + <property name="currentIndex"> + <number>-1</number> + </property> + </widget> + </item> + </layout> + </item> + <item> + <layout class="QHBoxLayout" name="horizontalLayout_2" stretch="0,0,0,0,0"> + <item> + <spacer name="horizontalSpacer"> + <property name="orientation"> + <enum>Qt::Horizontal</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>40</width> + <height>20</height> + </size> + </property> + </spacer> + </item> + <item> + <widget class="QPushButton" name="applyBtn"> + <property name="toolTip"> + <string>Apply the settings to the INI files corresponding to the current profile.</string> + </property> + <property name="text"> + <string>Apply</string> + </property> + </widget> + </item> + <item> + <widget class="QPushButton" name="discardBtn"> + <property name="toolTip"> + <string>Discard the settings.</string> + </property> + <property name="text"> + <string>Discard</string> + </property> + </widget> + </item> + <item> + <widget class="QPushButton" name="moveBtn"> + <property name="toolTip"> + <string>Create files under "INI Tweaks" in the mod folder with these settings.</string> + </property> + <property name="text"> + <string>INI Tweaks</string> + </property> + </widget> + </item> + <item> + <widget class="QPushButton" name="cancelBtn"> + <property name="toolTip"> + <string>Cancel the installation.</string> + </property> + <property name="text"> + <string>Cancel</string> + </property> + </widget> + </item> + </layout> + </item> + </layout> + </widget> + <resources/> + <connections/> +</ui> diff --git a/libs/installer_fomod_csharp/src/installer_fomod_csharp_predialog.ui b/libs/installer_fomod_csharp/src/installer_fomod_csharp_predialog.ui new file mode 100644 index 0000000..0aa08c3 --- /dev/null +++ b/libs/installer_fomod_csharp/src/installer_fomod_csharp_predialog.ui @@ -0,0 +1,89 @@ +<?xml version="1.0" encoding="UTF-8"?> +<ui version="4.0"> + <class>FomodCSharpPredialog</class> + <widget class="QDialog" name="FomodCSharpPredialog"> + <property name="geometry"> + <rect> + <x>0</x> + <y>0</y> + <width>400</width> + <height>83</height> + </rect> + </property> + <property name="windowTitle"> + <string>FOMOD C# Installer</string> + </property> + <layout class="QVBoxLayout" name="verticalLayout"> + <item> + <layout class="QHBoxLayout" name="horizontalLayout" stretch="0,1"> + <item> + <widget class="QLabel" name="label"> + <property name="text"> + <string>Name</string> + </property> + </widget> + </item> + <item> + <widget class="QComboBox" name="nameCombo"> + <property name="editable"> + <bool>true</bool> + </property> + </widget> + </item> + </layout> + </item> + <item> + <layout class="QHBoxLayout" name="horizontalLayout_2"> + <item> + <widget class="QPushButton" name="manualBtn"> + <property name="toolTip"> + <string>Opens a Dialog that allows custom modifications.</string> + </property> + <property name="whatsThis"> + <string>Opens a Dialog that allows custom modifications.</string> + </property> + <property name="text"> + <string>Manual</string> + </property> + </widget> + </item> + <item> + <spacer name="horizontalSpacer"> + <property name="orientation"> + <enum>Qt::Horizontal</enum> + </property> + <property name="sizeType"> + <enum>QSizePolicy::MinimumExpanding</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>20</width> + <height>20</height> + </size> + </property> + </spacer> + </item> + <item> + <widget class="QPushButton" name="okBtn"> + <property name="text"> + <string>Start</string> + </property> + <property name="default"> + <bool>true</bool> + </property> + </widget> + </item> + <item> + <widget class="QPushButton" name="cancelBtn"> + <property name="text"> + <string>Cancel</string> + </property> + </widget> + </item> + </layout> + </item> + </layout> + </widget> + <resources/> + <connections/> +</ui> diff --git a/libs/installer_fomod_csharp/src/installer_fomod_postdialog.h b/libs/installer_fomod_csharp/src/installer_fomod_postdialog.h new file mode 100644 index 0000000..9804610 --- /dev/null +++ b/libs/installer_fomod_csharp/src/installer_fomod_postdialog.h @@ -0,0 +1,87 @@ +#ifndef INSTALLER_FOMOD_POSTDIALOG_H +#define INSTALLER_FOMOD_POSTDIALOG_H + +#include "ui_installer_fomod_csharp_postdialog.h" + +#include <QTextEdit> + +#include "psettings.h" + +/** + * @brief Dialog for the installation of a simple archive + * a simple archive is one that doesn't require any manual changes to work correctly + **/ +class InstallerFomodPostDialog : public QDialog +{ + Q_OBJECT + +public: + enum class Result + { + APPLY, + DISCARD, + MOVE, + }; + + /** + * @brief constructor + * + * @param preset suggested name for the mod + * @param parent parent widget + **/ + explicit InstallerFomodPostDialog(QWidget* parent = 0) + : QDialog(parent), ui(new Ui::FomodCSharpPostDialog) + { + ui->setupUi(this); + setWindowFlags(windowFlags() & (~Qt::WindowContextHelpButtonHint)); + } + + ~InstallerFomodPostDialog() {} + + /** + * @return the result of this dialog if the user did not cancel. + */ + Result result() const { return m_Result; } + + /** + * + */ + void setIniSettings(std::map<QString, PSettings> const& settings) + { + for (auto p : settings) { + QTextEdit* widget = new QTextEdit(this); + widget->append(p.second.toString()); + widget->setReadOnly(true); + ui->tabWidget->addTab(widget, p.first); + } + } + +private slots: + + void on_discardBtn_clicked() + { + m_Result = Result::DISCARD; + this->accept(); + } + + void on_applyBtn_clicked() + { + m_Result = Result::APPLY; + this->accept(); + } + + void on_moveBtn_clicked() + { + m_Result = Result::MOVE; + this->accept(); + } + + void on_cancelBtn_clicked() { this->reject(); } + +private: + std::unique_ptr<Ui::FomodCSharpPostDialog> ui; + + Result m_Result{Result::APPLY}; +}; + +#endif diff --git a/libs/installer_fomod_csharp/src/installer_fomod_predialog.h b/libs/installer_fomod_csharp/src/installer_fomod_predialog.h new file mode 100644 index 0000000..5c57fdf --- /dev/null +++ b/libs/installer_fomod_csharp/src/installer_fomod_predialog.h @@ -0,0 +1,72 @@ +#ifndef INSTALLER_FOMOD_PREDIALOG_H +#define INSTALLER_FOMOD_PREDIALOG_H + +#include "ui_installer_fomod_csharp_predialog.h" + +#include <uibase/guessedvalue.h> + +#include <QCompleter> + +/** + * @brief Dialog for the installation of a simple archive + * a simple archive is one that doesn't require any manual changes to work correctly + **/ +class InstallerFomodPredialog : public QDialog +{ + Q_OBJECT + +public: + /** + * @brief constructor + * + * @param preset suggested name for the mod + * @param parent parent widget + **/ + explicit InstallerFomodPredialog(const MOBase::GuessedValue<QString>& preset, + QWidget* parent = 0) + : QDialog(parent), ui(new Ui::FomodCSharpPredialog), m_Manual(false) + { + + ui->setupUi(this); + setWindowTitle(preset + " - " + windowTitle()); + + for (auto iter = preset.variants().begin(); iter != preset.variants().end(); + ++iter) { + ui->nameCombo->addItem(*iter); + } + + ui->nameCombo->setCurrentIndex(ui->nameCombo->findText(preset)); + setWindowFlags(windowFlags() & (~Qt::WindowContextHelpButtonHint)); + ui->nameCombo->completer()->setCaseSensitivity(Qt::CaseSensitive); + } + + ~InstallerFomodPredialog() {} + + /** + * @return true if the user requested a manual installation. + **/ + bool manualRequested() const { return m_Manual; } + + /** + * @return the (user-modified) mod name + **/ + QString getName() const { return ui->nameCombo->currentText(); } + +private slots: + + void on_okBtn_clicked() { this->accept(); } + + void on_cancelBtn_clicked() { this->reject(); } + + void on_manualBtn_clicked() + { + m_Manual = true; + this->reject(); + } + +private: + std::unique_ptr<Ui::FomodCSharpPredialog> ui; + bool m_Manual; +}; + +#endif diff --git a/libs/installer_fomod_csharp/src/psettings.h b/libs/installer_fomod_csharp/src/psettings.h new file mode 100644 index 0000000..649c7da --- /dev/null +++ b/libs/installer_fomod_csharp/src/psettings.h @@ -0,0 +1,108 @@ +#ifndef PSETTINGS_H +#define PSETTINGS_H + +#include <QSettings> +#include <QString> +#include <map> + +/** + * This is a small class that can be used to store INI settings in memory since + * QSettings is a pain to use without an actual file. + * + * It is a much simpler structure since it stores everything as string. + */ +struct PSettings +{ + + /** + * + */ + PSettings() = default; + +public: // Value read/write. + /** + * @brief Set the value of the given section/key. + * + * @param section The section of the value. + * @param key The key of the value. + * @param value The value to set. + */ + void setValue(QString section, QString key, QString value) + { + m_Values[std::make_pair(section, key)] = value; + } + + /** + * @brief Return the value at the given section/key. + * + * @param section The section of the value. + * @param key The key of the value. + * + * @return the corresponding value, or an empty string if the section/key does not + * exist. + */ + QString value(QString section, QString key) const + { + auto it = m_Values.find(std::make_pair(section, key)); + return it == m_Values.end() ? QString() : it->second; + } + + /** + * @brief Check if the given section/key exists in these settings. + * + * @param section The section of the value. + * @param key The key of the value. + * + * @return true if the section/key exist. + */ + bool hasValue(QString section, QString key) const + { + return m_Values.find(std::make_pair(section, key)) != m_Values.end(); + } + +public: // Output: + /** + * @brief Convert this PSettings to a string. + * + * @return a string representing the content of a valid INI file corresponding + * to this PSettings. + */ + QString toString() const + { + QString result = ""; + QString cSection; + for (auto& p : m_Values) { + if (cSection != p.first.first) { + if (!cSection.isEmpty()) { + result += '\n'; + } + cSection = p.first.first; + result += "[" + cSection + "]\n"; + } + result += p.first.second + "=" + p.second + "\n"; + } + return result; + } + + /** + * @brief Update the given QSettings with all the value in this. + * + * @param settings The settings to update. + */ + void update(QSettings& settings) const + { + for (auto& p : m_Values) { + if (p.first.first == "General") { + settings.setValue(p.first.second, p.second); + } else { + settings.setValue(p.first.first + "/" + p.first.second, p.second); + } + } + } + +private: + // Map from <section, key> to value: + std::map<std::pair<QString, QString>, QString> m_Values; +}; + +#endif // !PSETTINGS_H diff --git a/libs/installer_fomod_csharp/src/xml_info_reader.h b/libs/installer_fomod_csharp/src/xml_info_reader.h new file mode 100644 index 0000000..91d6d9a --- /dev/null +++ b/libs/installer_fomod_csharp/src/xml_info_reader.h @@ -0,0 +1,140 @@ +#ifndef XML_INFO_READER_H +#define XML_INFO_READER_H + +#include <QFile> +#include <QIODevice> +#include <QString> +#include <QStringEncoder> +#include <QTextStream> +#include <QXmlStreamReader> + +#include <uibase/log.h> +#include <uibase/utility.h> + +// This is from installer_fomod, but should probably not be duplicated here. + +struct FomodInfoReader : QObject +{ + + Q_OBJECT + +public: + struct XmlParseError : MOBase::Exception + { + XmlParseError(const QString& message) : MOBase::Exception(message) {} + }; + + static QByteArray skipXmlHeader(QIODevice& file) + { + static const unsigned char UTF16LE_BOM[] = {0xFF, 0xFE}; + static const unsigned char UTF16BE_BOM[] = {0xFE, 0xFF}; + static const unsigned char UTF8_BOM[] = {0xEF, 0xBB, 0xBF}; + static const unsigned char UTF16LE[] = {0x3C, 0x00, 0x3F, 0x00}; + static const unsigned char UTF16BE[] = {0x00, 0x3C, 0x00, 0x3F}; + static const unsigned char UTF8[] = {0x3C, 0x3F, 0x78, 0x6D}; + + file.seek(0); + QByteArray rawBytes = file.read(4); + QTextStream stream(&file); + int bom = 0; + if (rawBytes.startsWith((const char*)UTF16LE_BOM)) { + stream.setEncoding(QStringEncoder::Encoding::Utf16LE); + bom = 2; + } else if (rawBytes.startsWith((const char*)UTF16BE_BOM)) { + stream.setEncoding(QStringEncoder::Encoding::Utf16BE); + bom = 2; + } else if (rawBytes.startsWith((const char*)UTF8_BOM)) { + stream.setEncoding(QStringEncoder::Encoding::Utf8); + bom = 3; + } else if (rawBytes.startsWith(QByteArray((const char*)UTF16LE, 4))) { + stream.setEncoding(QStringEncoder::Encoding::Utf16LE); + } else if (rawBytes.startsWith(QByteArray((const char*)UTF16BE, 4))) { + stream.setEncoding(QStringEncoder::Encoding::Utf16BE); + } else if (rawBytes.startsWith(QByteArray((const char*)UTF8, 4))) { + stream.setEncoding(QStringEncoder::Encoding::Utf8); + } // otherwise maybe the textstream knows the encoding? + + stream.seek(bom); + QString header = stream.readLine(); + if (!header.startsWith("<?")) { + // it was all for nothing, there is no header here... + stream.seek(bom); + } + // this seems to be necessary due to buffering in QTextStream + file.seek(stream.pos()); + return file.readAll(); + } + + template <class Fn> + static auto readXml(QFile& file, Fn&& fn) + { + // List of encodings to try: + static const std::vector<QStringConverter::Encoding> encodings{ + QStringConverter::Utf16, QStringConverter::Utf8, QStringConverter::Latin1}; + + std::string errorMessage; + try { + QXmlStreamReader reader(&file); + return fn(reader); + } catch (const XmlParseError& e) { + MOBase::log::warn( + "The {} in this file is incorrectly encoded ({}). Applying heuristics...", + file.fileName(), e.what()); + } + + // nmm's xml parser is less strict than the one from qt and allows files with + // wrong encoding in the header. Being strict here would be bad user experience + // this works around bad headers. + QByteArray headerlessData = skipXmlHeader(file); + + // try parsing the file with several encodings to support broken files + for (auto encoding : encodings) { + MOBase::log::debug("Trying encoding {} for {}... ", + QStringConverter::nameForEncoding(encoding), file.fileName()); + try { + QStringEncoder encoder(encoding); + QXmlStreamReader reader( + encoder.encode(QString("<?xml version=\"1.0\" encoding=\"%1\" ?>") + .arg(encoder.name())) + + headerlessData); + MOBase::log::debug("Interpreting {} as {}.", file.fileName(), encoder.name()); + return fn(reader); + } catch (const XmlParseError& e) { + MOBase::log::debug("Not {}: {}.", QStringConverter::nameForEncoding(encoding), + e.what()); + } + } + + throw XmlParseError( + tr("Failed to parse %1. See console for details.").arg(file.fileName())); + } + + static std::tuple<QString, int, QString> parseInfo(QXmlStreamReader& reader) + { + std::tuple<QString, int, QString> info{"", -1, ""}; + while (!reader.atEnd()) { + switch (reader.readNext()) { + case QXmlStreamReader::StartElement: { + if (reader.name().toString() == "Name") { + std::get<0>(info) = reader.readElementText(); + } else if (reader.name().toString() == "Author") { + } else if (reader.name().toString() == "Version") { + std::get<2>(info) = reader.readElementText(); + } else if (reader.name().toString() == "Id") { + std::get<1>(info) = reader.readElementText().toInt(); + } else if (reader.name().toString() == "Website") { + } + } break; + default: { + } break; + } + } + if (reader.hasError()) { + throw XmlParseError( + QString("%1 in line %2").arg(reader.errorString()).arg(reader.lineNumber())); + } + return info; + } +}; + +#endif diff --git a/libs/installer_fomod_csharp/vcpkg.json b/libs/installer_fomod_csharp/vcpkg.json new file mode 100644 index 0000000..28051ad --- /dev/null +++ b/libs/installer_fomod_csharp/vcpkg.json @@ -0,0 +1,15 @@ +{ + "features": { + "standalone": { + "description": "Build Standalone.", + "dependencies": ["mo2-cmake", "mo2-uibase"] + } + }, + "vcpkg-configuration": { + "default-registry": { + "kind": "git", + "repository": "https://github.com/ModOrganizer2/vcpkg-registry", + "baseline": "8beb2e0efa9c17dd6d17bb05288dd1e40727f673" + } + } +} |
