diff --git a/.github/workflows/linux-appimage.yml b/.github/workflows/linux-appimage.yml new file mode 100644 index 00000000..3d389afb --- /dev/null +++ b/.github/workflows/linux-appimage.yml @@ -0,0 +1,52 @@ +# Builds the Linux AppImage of the launcher in the pinned Ubuntu 22.04 container (glibc 2.35, the oldest system the AppImage +# supports) with a test payload: the build proves the launcher's shared code still compiles and links on Linux and that the +# AppImage still bundles what it needs. A release AppImage is built by the maintainer with the release payload +# (clean/installer/README-linux.md); this job's file is a smoke build and never ships. +# It runs only when started by hand (workflow_dispatch). Its own workflow, so ci.yml and its required check stay as they are. +name: Linux AppImage + +# Only when the maintainer starts it by hand: Actions tab, Linux AppImage, Run workflow. +on: + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: linux-appimage-${{ github.ref }} + cancel-in-progress: false + +jobs: + appimage: + name: "AppImage (Ubuntu 22.04, glibc 2.35)" + runs-on: ubuntu-24.04 + timeout-minutes: 60 + # The same digest as CONTAINER_IMAGE in clean/installer/build-appimage.sh (the step below fails if they differ). + container: docker.io/library/ubuntu:22.04@sha256:74b12b11ffa550fba1929ad4d8d16533c34f6612728469671afba1b03b66881c + steps: + # checkout wants git, and the portability check wants python3; the build script installs the rest itself + - name: Packages for checkout and the check + run: | + apt-get update -qq + apt-get install -y -qq --no-install-recommends ca-certificates git python3 + - uses: actions/checkout@v4.2.2 + - name: Container digest matches the build script + run: | + # the whole image reference, digest included, must match: a container line without a digest fails here + workflow="$(sed -n 's/^ container: *//p' .github/workflows/linux-appimage.yml)" + script="$(sed -n 's/^CONTAINER_IMAGE="\(.*\)"$/\1/p' clean/installer/build-appimage.sh)" + case "$workflow" in *@sha256:????????????????????????????????????????????????????????????????) ;; *) echo "workflow container has no sha256 digest: '$workflow'" >&2; exit 1 ;; esac + [ -n "$script" ] && [ "$workflow" = "$script" ] || { echo "workflow '$workflow' differs from build-appimage.sh '$script'" >&2; exit 1; } + - name: Portability check + run: python3 tools/ci/check_portable.py --root clean/installer + - name: Build the AppImage (test payload) + run: bash clean/installer/build-appimage.sh --test-payload --out out + # The smoke build, so the maintainer can run it. It carries the test payload and never ships; it expires after 3 days. + # Pinned to the full commit SHA of the v4.6.2 tag, not the tag, which can be moved. + - name: Keep the AppImage for review + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: WrongGPU-appimage-testpayload + path: out/*.AppImage + if-no-files-found: error + retention-days: 3 diff --git a/LICENSES/OFL-1.1.txt b/LICENSES/OFL-1.1.txt new file mode 100644 index 00000000..6fe84ee2 --- /dev/null +++ b/LICENSES/OFL-1.1.txt @@ -0,0 +1,43 @@ +SIL OPEN FONT LICENSE + +Version 1.1 - 26 February 2007 + +PREAMBLE + +The goals of the Open Font License (OFL) are to stimulate worldwide development of collaborative font projects, to support the font creation efforts of academic and linguistic communities, and to provide a free and open framework in which fonts may be shared and improved in partnership with others. + +The OFL allows the licensed fonts to be used, studied, modified and redistributed freely as long as they are not sold by themselves. The fonts, including any derivative works, can be bundled, embedded, redistributed and/or sold with any software provided that any reserved names are not used by derivative works. The fonts and derivatives, however, cannot be released under any other type of license. The requirement for fonts to remain under this license does not apply to any document created using the fonts or their derivatives. + +DEFINITIONS + +"Font Software" refers to the set of files released by the Copyright Holder(s) under this license and clearly marked as such. This may include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the copyright statement(s). + +"Original Version" refers to the collection of Font Software components as distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, or substituting — in part or in whole — any of the components of the Original Version, by changing formats or by porting the Font Software to a new environment. + +"Author" refers to any designer, engineer, programmer, technical writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS + +Permission is hereby granted, free of charge, to any person obtaining a copy of the Font Software, to use, study, copy, merge, embed, modify, redistribute, and sell modified and unmodified copies of the Font Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, redistributed and/or sold with any software, provided that each copy contains the above copyright notice and this license. These can be included either as stand-alone text files, human-readable headers or in the appropriate machine-readable metadata fields within text or binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font Name(s) unless explicit written permission is granted by the corresponding Copyright Holder. This restriction only applies to the primary font name as presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font Software shall not be used to promote, endorse or advertise any Modified Version, except to acknowledge the contribution(s) of the Copyright Holder(s) and the Author(s) or with their explicit written permission. + +5) The Font Software, modified or unmodified, in part or in whole, must be distributed entirely under this license, and must not be distributed under any other license. The requirement for fonts to remain under this license does not apply to any document created using the Font Software. + +TERMINATION + +This license becomes null and void if any of the above conditions are not met. + +DISCLAIMER + +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/REUSE.toml b/REUSE.toml index 536697a8..9405f0eb 100644 --- a/REUSE.toml +++ b/REUSE.toml @@ -62,6 +62,27 @@ precedence = "override" SPDX-FileCopyrightText = "2023 Advanced Micro Devices, Inc." SPDX-License-Identifier = "MIT" +# Selawik 1.01 (Microsoft; SIL Open Font License 1.1): the launcher's text font on Linux (the OFL's text is beside the fonts) +[[annotations]] +path = "clean/installer/assets/fonts/selawik/**" +precedence = "override" +SPDX-FileCopyrightText = "2015 Microsoft Corporation" +SPDX-License-Identifier = "OFL-1.1" + +# Noto Sans Math v3.000 (The Noto Project Authors; SIL Open Font License 1.1): the launcher's fallback for symbols Selawik lacks +[[annotations]] +path = "clean/installer/assets/fonts/notosansmath/**" +precedence = "override" +SPDX-FileCopyrightText = "2022 The Noto Project Authors (https://github.com/notofonts/math)" +SPDX-License-Identifier = "OFL-1.1" + +# Fluent System Icons (Microsoft; MIT): the launcher's icon font on Linux +[[annotations]] +path = "clean/installer/assets/fonts/fluent/**" +precedence = "override" +SPDX-FileCopyrightText = "2020 Microsoft Corporation" +SPDX-License-Identifier = "MIT" + # WrongGPU's own notes about the vendored headers (written by the clean team, not AMD's) [[annotations]] path = ["clean/third_party/fidelityfx-sdk-1.1.4/README.md", "clean/third_party/fidelityfx-sdk-fsr3-v3.0.4/README.md"] diff --git a/THIRD-PARTY-NOTICES b/THIRD-PARTY-NOTICES index d4e7c85f..b00a6d94 100644 --- a/THIRD-PARTY-NOTICES +++ b/THIRD-PARTY-NOTICES @@ -28,6 +28,35 @@ repository. The model weights are read on the player's own PC from that upscaler Licence: MIT (text below; clean/third_party/fidelityfx-sdk-fsr3-v3.0.4/LICENSE.txt) Used by: clean/fsr/src/fsr30_layout_check.cpp only (a compile-time layout check of WrongGPU's own mirror types) +1.3 Selawik 1.01: text font of the Linux launcher + Files: clean/installer/assets/fonts/selawik/ (selawk.ttf, selawkl.ttf, selawksl.ttf, selawksb.ttf, selawkb.ttf), + unmodified; OFL.txt beside them + Source: https://github.com/microsoft/Selawik, release 1.01 (Selawik_Release.zip) + Licence: SIL Open Font License 1.1, (c) 2015 Microsoft Corporation, Reserved Font Name "Selawik" + (clean/installer/assets/fonts/selawik/OFL.txt) + Used by: the Linux launcher's Cairo/Pango drawing (clean/installer/src/app/ui_gfx_cairo.cpp) in place of + Segoe UI Variable; registered with fontconfig at start-up, never renamed or sold on its own + +1.4 Noto Sans Math v3.000: symbol fallback font of the Linux launcher + Files: clean/installer/assets/fonts/notosansmath/NotoSansMath-Regular.ttf (the release's unhinted TTF, whole and + unmodified, 657 KB, sha256 b127e84699212b6b2ef50aff58e0ebebeec04ffe6db1b9eb9e209c8c3d97b4aa); OFL.txt beside it + Source: https://github.com/notofonts/math, release NotoSansMath-v3.000 (tag commit + 480fb49a4a43189ad0f8f27415e76fd1317ecab9; NotoSansMath-v3.000.zip, sha256 + ac351837b41f8a897f020b97fb0f075ad574c1e9669fb5839ada1f92fd748356) + Licence: SIL Open Font License 1.1, Copyright 2022 The Noto Project Authors (https://github.com/notofonts/math), no + Reserved Font Name (clean/installer/assets/fonts/notosansmath/OFL.txt) + Used by: the Linux launcher's Cairo/Pango drawing (clean/installer/src/app/ui_gfx_cairo.cpp), listed after Selawik so + it draws the symbols Selawik lacks (the arrow in "0.4.5 → 0.6.0", the no-break and en spaces); never + renamed or sold on its own + +1.5 Fluent System Icons: icon font of the Linux launcher + Files: clean/installer/assets/fonts/fluent/FluentSystemIcons-Regular.ttf, unmodified; LICENSE beside it + Source: https://github.com/microsoft/fluentui-system-icons, + commit 67e6dec1ee956af3ab4c746a2b3bb6a2e5520a44 + Licence: MIT, (c) 2020 Microsoft Corporation (clean/installer/assets/fonts/fluent/LICENSE) + Used by: the Linux launcher's Cairo/Pango drawing in place of Segoe Fluent Icons (the codepoint table is in + ui_gfx_cairo.cpp) + 2. Not included; used at build or test time (installed by the developer) ------------------------------------------------------------------------- @@ -56,6 +85,21 @@ repository. The model weights are read on the player's own PC from that upscaler this repository or of WrongGPU's packages). +4. Not included; bundled into the Linux AppImage when it is built +------------------------------------------------------------------ + +4.1 libjpeg-turbo 2.1.2 (Ubuntu 22.04's libjpeg-turbo8): JPEG decoding in the Linux launcher + Files: none in this repository; build-appimage.sh installs libjpeg-turbo8-dev from the Ubuntu 22.04 archive and + linuxdeploy copies libjpeg.so.8 into the AppImage, unmodified. The AppImage carries this file in + share/doc/wronggpu/THIRD-PARTY-NOTICES. + Source: https://github.com/libjpeg-turbo/libjpeg-turbo, tag 2.1.2 (the source of Ubuntu's package) + Licence: the IJG (Independent JPEG Group) licence for the libjpeg API library, which the launcher uses, and the + Modified (3-clause) BSD licence (D. R. Commander and others) for the rest of the project; texts below + Notice: This software is based in part on the work of the Independent JPEG Group. + Used by: clean/installer/src/app/jpeg_decode_linux.cpp, which reads Steam's JPEG art (hero, header, capsule); the + Windows launcher decodes art with WIC and does not carry it + + Licence texts ------------- @@ -105,3 +149,73 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +libjpeg-turbo 2.1.2, the IJG licence (README.ijg of the libjpeg-turbo source, its LEGAL ISSUES section): + +This software is based in part on the work of the Independent JPEG Group. + +The authors make NO WARRANTY or representation, either express or implied, +with respect to this software, its quality, accuracy, merchantability, or +fitness for a particular purpose. This software is provided "AS IS", and you, +its user, assume the entire risk as to its quality and accuracy. + +This software is copyright (C) 1991-2020, Thomas G. Lane, Guido Vollbeding. +All Rights Reserved except as specified below. + +Permission is hereby granted to use, copy, modify, and distribute this +software (or portions thereof) for any purpose, without fee, subject to these +conditions: +(1) If any part of the source code for this software is distributed, then this +README file must be included, with this copyright and no-warranty notice +unaltered; and any additions, deletions, or changes to the original files +must be clearly indicated in accompanying documentation. +(2) If only executable code is distributed, then the accompanying +documentation must state that "this software is based in part on the work of +the Independent JPEG Group". +(3) Permission for use of this software is granted only if the user accepts +full responsibility for any undesirable consequences; the authors accept +NO LIABILITY for damages of any kind. + +These conditions apply to any software derived from or based on the IJG code, +not just to the unmodified library. If you use our work, you ought to +acknowledge us. + +Permission is NOT granted for the use of any IJG author's name or company name +in advertising or publicity relating to this software or products derived from +it. This software may be referred to only as "the Independent JPEG Group's +software". + +We specifically permit and encourage the use of this software as the basis of +commercial products, provided that all warranty or liability claims are +assumed by the product vendor. + + +libjpeg-turbo 2.1.2, the Modified (3-clause) BSD licence (LICENSE.md of the libjpeg-turbo source): + +Copyright (C)2009-2021 D. R. Commander. All Rights Reserved. +Copyright (C)2015 Viktor Szathmáry. All Rights Reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +- Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. +- Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. +- Neither the name of the libjpeg-turbo Project nor the names of its + contributors may be used to endorse or promote products derived from this + software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS", +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. diff --git a/clean/fsr/src/model_choice_record.h b/clean/fsr/src/model_choice_record.h index a3ad5ed4..36340eb8 100644 --- a/clean/fsr/src/model_choice_record.h +++ b/clean/fsr/src/model_choice_record.h @@ -156,7 +156,7 @@ enum class ReadResult { Missing, Ok, Corrupt, Unreadable }; // Reads the record (call it under the record's Lock). inline ReadResult ReadRecordFile(const std::filesystem::path& path, Record* out, std::string* why) { std::string text; - HANDLE h = CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, + HANDLE h = CreateFileW(path.wstring().c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); if (h == INVALID_HANDLE_VALUE) { const DWORD e = GetLastError(); diff --git a/clean/installer/CMakeLists.txt b/clean/installer/CMakeLists.txt index 85930212..bc25c646 100644 --- a/clean/installer/CMakeLists.txt +++ b/clean/installer/CMakeLists.txt @@ -1,5 +1,6 @@ # SPDX-License-Identifier: MIT -# WrongGPU installer (spec 30). Windows only: MSVC or MinGW-w64. +# WrongGPU installer (spec 30). Windows: MSVC or MinGW-w64. Linux: the core (wg_core) and its tests, on a POSIX +# implementation of the Windows calls the core makes (src/platform/posix, README-linux.md). # cmake -S . -B build -DWRONGGPU_PAYLOAD_DIR= [-DWRONGGPU_MAP=] [-DWRONGGPU_VERSION=x.y.z] # cmake --build build --config Release # -DWRONGGPU_PRESET_K=OFF builds an installer for a release that ships Model M only: no Preset K choice or wording, @@ -10,7 +11,12 @@ # (exit 2), an earlier direct install is removed before the hosted one is made, the FSR 3.0 component DLLs of the # payload folder are not built in (src/setup_route.h). cmake_minimum_required(VERSION 3.16) -project(wronggpu_installer LANGUAGES CXX RC) +project(wronggpu_installer LANGUAGES CXX) +if(WIN32) + enable_language(RC) +else() + enable_language(ASM) # resources.S: the embedded payload (tools/make_payload.py) +endif() # MinGW's headers set _WIN32_WINNT to Windows 7 as soon as a standard header comes first (context.h includes # before base.h), which hides the Windows 8+ declarations the core uses (FILE_ID_INFO in convert_ignore.cpp): # the whole build gets base.h's Windows 10 instead. MSVC's headers leave it unset. @@ -88,9 +94,6 @@ else() set(DIRECT_ROUTE_PAYLOAD_ARGS --hosted-only) set(DIRECT_ROUTE_DEFINITION WRONGGPU_DIRECT_ROUTE=0) endif() -if(NOT WRONGGPU_PAYLOAD_DIR) - message(FATAL_ERROR "Set WRONGGPU_PAYLOAD_DIR to the release payload folder (see README.md).") -endif() add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/../converter converter) @@ -104,6 +107,21 @@ if(NOT SOURCE_SIZE_RESULT EQUAL 0) message(FATAL_ERROR "A source file is at or over 256 KB (tools/check_source_size.py): split it.") endif() option(WRONGGPU_TESTING "Isolate registry and enable mock-only HIP candidate selection (never ship)" OFF) +if(NOT WRONGGPU_PAYLOAD_DIR AND WRONGGPU_TESTING AND NOT WIN32) + # a Linux test build makes the stand-in payload and test map the Windows test build is given by hand: the harness's own + # (tests/run_installer_tests.py --prepare-only), the model case tests/run_launcher_tests.py expects + set(MOCK_PAYLOAD_WORK ${CMAKE_CURRENT_BINARY_DIR}/mock-payload) + execute_process(COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tests/run_installer_tests.py --work ${MOCK_PAYLOAD_WORK} --prepare-only + RESULT_VARIABLE MOCK_PAYLOAD_RESULT OUTPUT_QUIET) + if(NOT MOCK_PAYLOAD_RESULT EQUAL 0) + message(FATAL_ERROR "tests/run_installer_tests.py --prepare-only failed") + endif() + set(WRONGGPU_PAYLOAD_DIR ${MOCK_PAYLOAD_WORK}/prepared/payload) + set(WRONGGPU_MAP ${MOCK_PAYLOAD_WORK}/prepared/test-map.json) +endif() +if(NOT WRONGGPU_PAYLOAD_DIR) + message(FATAL_ERROR "Set WRONGGPU_PAYLOAD_DIR to the release payload folder (see README.md).") +endif() set(RR_PAYLOAD_DIR "${WRONGGPU_RR_DIR}") if(NOT RR_PAYLOAD_DIR AND WRONGGPU_TESTING) set(RR_PAYLOAD_DIR ${CMAKE_CURRENT_BINARY_DIR}/mock-rr) @@ -134,6 +152,44 @@ else() set(MAP_F_FILE) endif() +file(GLOB_RECURSE WRONGGPU_PAYLOAD_FILES CONFIGURE_DEPENDS "${WRONGGPU_PAYLOAD_DIR}/*") +set(GEN ${CMAKE_CURRENT_BINARY_DIR}/gen) +set(MANIFEST ${CMAKE_CURRENT_SOURCE_DIR}/src/setup.manifest) +# The application manifest is embedded once: by the MSVC linker (CMake merges .manifest sources into the manifest the +# linker generates), or through the resource script with MinGW, whose linker embeds none. +if(MSVC) + set(MANIFEST_ARGS) + set(MANIFEST_SOURCE ${MANIFEST}) +else() + set(MANIFEST_ARGS --manifest ${MANIFEST}) + set(MANIFEST_SOURCE) +endif() +# A WRONGGPU_TESTING build may embed the test suite's stand-in runtime (tests/run_installer_tests.py --prepare-only: the +# marker and a build manifest that says stand_in); any other build refuses it at this step (make_payload.py --testing). +if(WRONGGPU_TESTING) + set(TESTING_PAYLOAD_ARGS --testing) +else() + set(TESTING_PAYLOAD_ARGS) +endif() +add_custom_command( + OUTPUT ${GEN}/payload_table.h ${GEN}/resources.rc ${GEN}/resources.S ${GEN}/app.ico + COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tools/make_payload.py + --payload ${WRONGGPU_PAYLOAD_DIR} --map ${WRONGGPU_MAP} ${PRESET_K_MAP_ARGS} --version ${WRONGGPU_VERSION} + --build-id=${WRONGGPU_BUILD_ID} --payload-name=${WRONGGPU_PAYLOAD_NAME} + ${DIRECT_ROUTE_PAYLOAD_ARGS} ${RR_PAYLOAD_ARGS} ${MAP_F_ARGS} ${MAP_L_ARGS} ${MANIFEST_ARGS} ${TESTING_PAYLOAD_ARGS} --out ${GEN} + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/tools/make_payload.py ${MANIFEST} ${WRONGGPU_MAP} ${PRESET_K_MAP_FILE} ${MAP_F_FILE} ${MAP_L_FILE} ${WRONGGPU_PAYLOAD_FILES} ${WRONGGPU_RR_FILES} + COMMENT "Embedding the payload and the converter map") + +# The launcher's sources, for both targets: a new shared file goes in WRONGGPU_APP_SOURCES only, never in the two lists below it. +set(WRONGGPU_APP_SOURCES src/app/main.cpp src/app/cli.cpp src/app/launcher_ui.cpp src/app/ui_art.cpp src/app/ui_widgets.cpp + src/app/ui_library.cpp src/app/ui_game.cpp src/app/ui_settings.cpp src/app/ui_uia.cpp src/app/ui_render.cpp src/app/ui_words.cpp + src/app/ui_dump.cpp src/app/ui_frame.cpp src/app/ui_play.cpp src/app/ui_rrprep.cpp src/app/ui_rrconfig.cpp src/app/ui_activate.cpp + src/app/ui_checks.cpp src/app/ui_appimage.cpp src/app/payload_embed.cpp) +# Windows only: the GDI+ wizard and the Direct2D/DirectWrite drawing (Linux draws through ui_gfx_cairo.cpp, in wg_gfx_cairo). +set(WRONGGPU_APP_SOURCES_WINDOWS src/app/wizard.cpp src/app/ui_gfx.cpp) +# Linux only: the live-frame hook for the SDL window layer, and the JPEG decoder (libjpeg-turbo; Windows decodes art with WIC). +set(WRONGGPU_APP_SOURCES_LINUX src/app/ui_live_hook_linux.cpp src/app/jpeg_decode_linux.cpp) + # wg_core: the installer's engine, split into modules (src/wg_core; build/launcher-design.md section 2). No globals: # a wg::Context is passed in. The wizard (and later the launcher) is built on top of it. add_library(wg_core STATIC @@ -142,24 +198,31 @@ add_library(wg_core STATIC src/wg_core/model.cpp src/wg_core/checks.cpp src/wg_core/install.cpp src/wg_core/logs.cpp src/wg_core/profile.cpp src/wg_core/logtail.cpp src/wg_core/launcher.cpp src/wg_core/fingerprint.cpp src/wg_core/optikeys.cpp src/wg_core/leftovers.cpp src/wg_core/rr.cpp src/wg_core/rrprep.cpp src/wg_core/gamerules.cpp - src/wg_core/rrconfig.cpp src/wg_core/convert_ignore.cpp) + src/wg_core/rrconfig.cpp src/wg_core/convert_ignore.cpp src/wg_core/appimage.cpp) target_include_directories(wg_core PUBLIC src) target_compile_definitions(wg_core PUBLIC ${PRESET_K_DEFINITION} ${DIRECT_ROUTE_DEFINITION}) # (private: model-choice-tests compiles profile.cpp with the Model L choice on, against this library) target_compile_definitions(wg_core PRIVATE ${MODEL_L_DEFINITION} ${MODEL_K_DEFINITION}) if(WRONGGPU_TESTING) target_compile_definitions(wg_core PUBLIC WRONGGPU_TESTING) - if(NOT MSVC) - # record.cpp's #pragma comment(lib, "rstrtmgr.lib") is MSVC-only; clang and gcc for MinGW need the library named - target_link_libraries(wg_core PUBLIC rstrtmgr) - endif() endif() -target_link_libraries(wg_core PUBLIC wgc_core advapi32 user32 shell32 ole32 uuid winhttp) +if(WIN32) + # rstrtmgr: record.cpp's Restart Manager check; its #pragma comment(lib) is read by MSVC only, MinGW needs it named here + target_link_libraries(wg_core PUBLIC wgc_core advapi32 user32 shell32 ole32 uuid winhttp rstrtmgr) +else() + # Linux: and the other Windows headers the core includes resolve to src/platform/posix, which implements + # the calls the core makes on POSIX. A Windows call it lacks fails the Linux build at that line. + target_include_directories(wg_core BEFORE PUBLIC src/platform/posix) + target_sources(wg_core PRIVATE src/platform/posix/win32_posix.cpp src/platform/posix/win32_posix_process.cpp + src/platform/posix/win32_posix_registry.cpp src/platform/posix/win32_posix_sync.cpp src/platform/posix/win32_posix_rm.cpp) + target_link_libraries(wg_core PUBLIC wgc_core) +endif() if(MSVC) target_compile_options(wg_core PRIVATE /Zi) target_compile_definitions(wg_core PRIVATE NDEBUG) endif() +if(WIN32) # wg_ui: the widget kit (owner-drawn buttons, check boxes, progress bar, cards, palette, fonts) of the wizard and the # launcher (src/wg_ui). Windows' own GDI, GDI+, DWM and comctl32 only. add_library(wg_ui STATIC src/wg_ui/kit.cpp) @@ -169,34 +232,6 @@ if(MSVC) target_compile_definitions(wg_ui PRIVATE NDEBUG) endif() -file(GLOB_RECURSE WRONGGPU_PAYLOAD_FILES CONFIGURE_DEPENDS "${WRONGGPU_PAYLOAD_DIR}/*") -set(GEN ${CMAKE_CURRENT_BINARY_DIR}/gen) -set(MANIFEST ${CMAKE_CURRENT_SOURCE_DIR}/src/setup.manifest) -# The application manifest is embedded once: by the MSVC linker (CMake merges .manifest sources into the manifest the -# linker generates), or through the resource script with MinGW, whose linker embeds none. -if(MSVC) - set(MANIFEST_ARGS) - set(MANIFEST_SOURCE ${MANIFEST}) -else() - set(MANIFEST_ARGS --manifest ${MANIFEST}) - set(MANIFEST_SOURCE) -endif() -# A WRONGGPU_TESTING build may embed the test suite's stand-in runtime (tests/run_installer_tests.py --prepare-only: the -# marker and a build manifest that says stand_in); any other build refuses it at this step (make_payload.py --testing). -if(WRONGGPU_TESTING) - set(TESTING_PAYLOAD_ARGS --testing) -else() - set(TESTING_PAYLOAD_ARGS) -endif() -add_custom_command( - OUTPUT ${GEN}/payload_table.h ${GEN}/resources.rc ${GEN}/app.ico - COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tools/make_payload.py - --payload ${WRONGGPU_PAYLOAD_DIR} --map ${WRONGGPU_MAP} ${PRESET_K_MAP_ARGS} --version ${WRONGGPU_VERSION} - --build-id=${WRONGGPU_BUILD_ID} --payload-name=${WRONGGPU_PAYLOAD_NAME} - ${DIRECT_ROUTE_PAYLOAD_ARGS} ${RR_PAYLOAD_ARGS} ${MAP_F_ARGS} ${MAP_L_ARGS} ${MANIFEST_ARGS} ${TESTING_PAYLOAD_ARGS} --out ${GEN} - DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/tools/make_payload.py ${MANIFEST} ${WRONGGPU_MAP} ${PRESET_K_MAP_FILE} ${MAP_F_FILE} ${MAP_L_FILE} ${WRONGGPU_PAYLOAD_FILES} ${WRONGGPU_RR_FILES} - COMMENT "Embedding the payload and the converter map") - # WrongGPU-Restore.exe: the per-game restorer (uninstall.exe in each game's wronggpu-setup folder): wg_core without the # payload, the converter data or the UI. WrongGPU.exe embeds it (resource 960) and writes it into every game it installs. file(GENERATE OUTPUT ${GEN}/restore_app.rc CONTENT "1 ICON \"${GEN}/app.ico\"\n") @@ -227,8 +262,7 @@ file(GENERATE OUTPUT ${GEN}/restore.rc CONTENT "960 RCDATA \"${GEN}/restorer.bin set_source_files_properties(${GEN}/restore.rc PROPERTIES OBJECT_DEPENDS ${GEN}/restorer.bin) # WrongGPU.exe: the launcher (window, command line, elevated worker) with the installer's /switches as aliases. -add_executable(WrongGPU WIN32 src/app/main.cpp src/app/wizard.cpp src/app/cli.cpp src/app/launcher_ui.cpp src/app/ui_gfx.cpp src/app/ui_art.cpp - src/app/ui_widgets.cpp src/app/ui_library.cpp src/app/ui_game.cpp src/app/ui_settings.cpp src/app/ui_uia.cpp src/app/ui_render.cpp src/app/ui_words.cpp src/app/ui_dump.cpp src/app/ui_frame.cpp src/app/ui_play.cpp src/app/ui_rrprep.cpp src/app/ui_rrconfig.cpp src/app/ui_activate.cpp src/app/ui_checks.cpp src/app/payload_embed.cpp +add_executable(WrongGPU WIN32 ${WRONGGPU_APP_SOURCES} ${WRONGGPU_APP_SOURCES_WINDOWS} ${GEN}/resources.rc ${GEN}/restore.rc ${GEN}/restorer.bin ${GEN}/payload_table.h ${MANIFEST_SOURCE}) add_dependencies(WrongGPU WrongGPU-Restore) if(WRONGGPU_TESTING) @@ -255,6 +289,9 @@ if(WRONGGPU_TESTING) -DF4=$ -DOUT=$/wg-test-build.sha256 -P ${CMAKE_CURRENT_SOURCE_DIR}/tools/sha256_list.cmake VERBATIM) +endif() +endif() +if(WRONGGPU_TESTING) add_executable(wizard-policy-tests tests/wizard_policy_tests.cpp) target_compile_definitions(wizard-policy-tests PRIVATE ${PRESET_K_DEFINITION} ${DIRECT_ROUTE_DEFINITION} ${MODEL_L_DEFINITION} ${MODEL_K_DEFINITION}) endif() @@ -302,9 +339,127 @@ add_test(NAME model-choice-k COMMAND model-choice-k-tests) add_test(NAME model-choice-k-only COMMAND model-choice-k-only-tests) add_test(NAME coexist-core COMMAND coexist-core-tests) add_test(NAME convert-ignore COMMAND convert-ignore-tests) +if(NOT WIN32) + # the Linux layer's own checks: sharing, processes and the registry file go further than the core's tests do + add_executable(posix-layer-tests src/platform/posix/tests/posix_layer_tests.cpp) + target_link_libraries(posix-layer-tests PRIVATE wg_core) + add_test(NAME posix-layer COMMAND posix-layer-tests) + # keeps Linux from breaking silently: no wstring-built std::filesystem::path, no Direct2D/WIC/DWM/UIA in the shared UI + # (tools/ci/check_portable.py); the second test proves each rule fails on a planted violation + set(PORTABLE_CHECK ${CMAKE_CURRENT_SOURCE_DIR}/../../tools/ci/check_portable.py) + if(EXISTS ${PORTABLE_CHECK}) + add_test(NAME portable COMMAND ${Python3_EXECUTABLE} -I ${PORTABLE_CHECK} --root ${CMAKE_CURRENT_SOURCE_DIR}) + add_test(NAME portable-selftest COMMAND ${Python3_EXECUTABLE} -I ${PORTABLE_CHECK} --self-test) + endif() + # The launcher's drawing on Linux (Gfx on Cairo and Pango, fonts through fontconfig) and its smoke test (offscreen PNGs) + find_package(PkgConfig REQUIRED) + pkg_check_modules(WG_CAIRO REQUIRED IMPORTED_TARGET cairo pangocairo fontconfig) + # Steam's art is JPEG: libjpeg-turbo's libjpeg API (Ubuntu libjpeg-turbo8-dev), shared, bundled into the AppImage + pkg_check_modules(WG_JPEG REQUIRED IMPORTED_TARGET libjpeg) + # The window layer: the Win32 window calls the launcher's window makes, on SDL3 (static; -DCMAKE_PREFIX_PATH= or + # -DSDL3_DIR=). Only the drawing's live frame and the text fields reach into it; ui-dump and ui-render + # (a message-only window) never start SDL. + find_package(SDL3 CONFIG REQUIRED) + if(TARGET SDL3::SDL3-static) + set(WG_SDL3_TARGET SDL3::SDL3-static) + else() + set(WG_SDL3_TARGET SDL3::SDL3) + endif() + add_library(wg_window STATIC src/platform/posix/win32_window_sdl.cpp src/platform/posix/win32_window_edit.cpp + src/platform/posix/win32_window_misc.cpp) + target_link_libraries(wg_window PUBLIC wg_core ${WG_SDL3_TARGET}) + add_library(wg_gfx_cairo STATIC src/app/ui_gfx_cairo.cpp) + target_link_libraries(wg_gfx_cairo PUBLIC wg_core wg_window PkgConfig::WG_CAIRO) + target_compile_definitions(wg_gfx_cairo PRIVATE WRONGGPU_FONT_DIR="${CMAKE_CURRENT_SOURCE_DIR}/assets/fonts") + # the JPEG decoder: a synthetic JPEG made at test time (size, colours, damaged and missing files) + add_executable(jpeg-linux-tests tests/jpeg_linux_tests.cpp src/app/jpeg_decode_linux.cpp) + target_include_directories(jpeg-linux-tests PRIVATE src) + target_link_libraries(jpeg-linux-tests PRIVATE PkgConfig::WG_JPEG) + add_test(NAME jpeg-linux COMMAND jpeg-linux-tests) + add_executable(gfx-linux-smoke tests/gfx_linux_smoke.cpp) + target_link_libraries(gfx-linux-smoke PRIVATE wg_gfx_cairo) + add_test(NAME gfx-linux-smoke COMMAND gfx-linux-smoke ${CMAKE_CURRENT_BINARY_DIR}/gfx-smoke) + # The launcher itself on Linux: the same window code as Windows (src/app, the Win32 calls answered by src/platform/posix), without + # the old GDI+ wizard (wizard.cpp, wg_ui), the DWM title bar, tooltips and UI Automation, which Windows alone has. + add_executable(WrongGPU ${WRONGGPU_APP_SOURCES} ${WRONGGPU_APP_SOURCES_LINUX} ${GEN}/resources.S ${GEN}/payload_table.h) + target_include_directories(WrongGPU PRIVATE ${GEN}) + # the assembler reads the payload through .incbin, which CMake's dependency scan does not see + set_source_files_properties(${GEN}/resources.S PROPERTIES OBJECT_DEPENDS "${GEN}/payload_table.h;${WRONGGPU_PAYLOAD_FILES};${WRONGGPU_RR_FILES}") + target_compile_definitions(WrongGPU PRIVATE ${PRESET_K_DEFINITION} ${DIRECT_ROUTE_DEFINITION} UNICODE _UNICODE + WRONGGPU_VERSION_TEXT="${WRONGGPU_VERSION}" WRONGGPU_BUILD_ID_TEXT="${WRONGGPU_BUILD_ID}" + WRONGGPU_FONT_DIR="${CMAKE_CURRENT_SOURCE_DIR}/assets/fonts") + target_link_libraries(WrongGPU PRIVATE wg_gfx_cairo wg_window wg_core PkgConfig::WG_JPEG) + # an installed launcher finds its fonts at ../share/wronggpu/assets/fonts from its binary (ui_gfx_cairo.cpp FontDir) + if(WRONGGPU_TESTING) + # A WRONGGPU_TESTING build's identity on Linux, which the launcher suite checks before it runs a program + # (tests/launcher_build_facts.py), as the resource and PE checksum on Windows: the section .wg_testing_id and the file's + # SHA-256 written into it after the link (tools/elf_testing_identity.py). The suite's negative controls: programs that are + # not testing builds (no identity), one with the hook strings, and a load marker; then the build list of their SHA-256 and + # this launcher's, written last. + target_sources(WrongGPU PRIVATE src/platform/posix/testing_identity_linux.cpp) + add_executable(wg-test-canary tests/canary.cpp) + add_executable(wg-test-canary-strings tests/canary.cpp) + target_compile_definitions(wg-test-canary-strings PRIVATE WG_CANARY_HOOK_STRINGS) + target_link_libraries(wg-test-canary PRIVATE wg_core) + target_link_libraries(wg-test-canary-strings PRIVATE wg_core) + add_library(wg-test-canary-dll SHARED tests/canary_dll_linux.cpp) + set_target_properties(wg-test-canary-dll PROPERTIES PREFIX "" SUFFIX ".dll") + add_dependencies(WrongGPU wg-test-canary wg-test-canary-strings wg-test-canary-dll) + add_custom_command(TARGET WrongGPU POST_BUILD + COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tools/elf_testing_identity.py $ + COMMAND ${CMAKE_COMMAND} -DF1=$ -DF2=$ -DF3=$ + -DF4=$ + -DOUT=$/wg-test-build.sha256 -P ${CMAKE_CURRENT_SOURCE_DIR}/tools/sha256_list.cmake + VERBATIM) + # the window's pages (ui-dump, ui-render) and the live window under SDL's offscreen driver with scripted events (a click, a + # scroll, typing, WM_CLOSE): each on a home, XDG folders and registry file of its own + add_test(NAME linux-ui COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tests/run_linux_ui_tests.py + --exe $ --jpeg-tool $ + --work ${CMAKE_CURRENT_BINARY_DIR}/linux-ui-tests) + set_tests_properties(linux-ui PROPERTIES TIMEOUT 900) + add_test(NAME linux-ui-wording COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tests/run_linux_ui_wording_tests.py + --exe $ --work ${CMAKE_CURRENT_BINARY_DIR}/linux-ui-wording-tests) + set_tests_properties(linux-ui-wording PROPERTIES TIMEOUT 600) + add_test(NAME linux-ui-codexfix COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tests/run_linux_ui_codexfix_tests.py + --exe $ --work ${CMAKE_CURRENT_BINARY_DIR}/linux-ui-codexfix-tests) + set_tests_properties(linux-ui-codexfix PROPERTIES TIMEOUT 900) + if(MOCK_PAYLOAD_WORK AND NOT WRONGGPU_PRESET_K) + # the launcher's verbs suite (tests/run_launcher_tests.py) against this binary: it needs the test map and stand-in payload + # the build embeds only when it made them itself; its checks that only mean something on Windows say so and are skipped + add_test(NAME launcher-native COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tests/run_launcher_tests.py + --native-linux $ --work ${CMAKE_CURRENT_BINARY_DIR}/launcher-native-tests) + set_tests_properties(launcher-native PROPERTIES TIMEOUT 1800) + elseif(MOCK_PAYLOAD_WORK) + # the suite's checks are written for a Model M only build (CI's launcher build): with Preset K, every OptiScaler install + # leaves the plugin's wronggpu-asi.ini after an uninstall (install.cpp SeedAsiSelection), which they do not expect + message(STATUS "launcher-native: not added (the launcher suite needs -DWRONGGPU_PRESET_K=OFF)") + endif() + # the window layer's message handling with SDL events pushed by the test (display scale change, a batch of keys, text in an edit, + # WM_QUIT order, posts from a thread, capture, PeekMessageW's filters); SDL's offscreen driver, no window opens + add_executable(window-linux-tests tests/window_linux_tests.cpp) + target_link_libraries(window-linux-tests PRIVATE wg_window) + add_test(NAME window-linux COMMAND window-linux-tests) + set_tests_properties(window-linux PROPERTIES TIMEOUT 120 ENVIRONMENT "SDL_VIDEO_DRIVER=offscreen;SDL_AUDIODRIVER=dummy") + endif() + install(TARGETS WrongGPU RUNTIME DESTINATION bin) + install(DIRECTORY assets/fonts DESTINATION share/wronggpu/assets) + # the notices the bundled libraries' licences ask the AppImage to carry (libjpeg-turbo: THIRD-PARTY-NOTICES section 4) + install(FILES ${CMAKE_CURRENT_SOURCE_DIR}/../../THIRD-PARTY-NOTICES DESTINATION share/doc/wronggpu) + # the AppImage (build-appimage.sh) takes everything it ships from these install rules: the menu entry and the app's own icon + # (the biggest frame of assets/wronggpu.ico) + file(MAKE_DIRECTORY ${GEN}) + execute_process(COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tools/ico_to_png.py ${CMAKE_CURRENT_SOURCE_DIR}/assets/wronggpu.ico + ${GEN}/wronggpu.png RESULT_VARIABLE ICON_PNG_RESULT OUTPUT_QUIET) + if(NOT ICON_PNG_RESULT EQUAL 0) + message(FATAL_ERROR "tools/ico_to_png.py failed") + endif() + install(FILES assets/wronggpu.desktop DESTINATION share/applications) + install(FILES ${GEN}/wronggpu.png DESTINATION share/icons/hicolor/256x256/apps) +endif() if(WRONGGPU_TESTING) add_test(NAME wizard-policy COMMAND wizard-policy-tests) endif() +if(WIN32) target_include_directories(WrongGPU PRIVATE ${GEN}) target_compile_definitions(WrongGPU PRIVATE ${PRESET_K_DEFINITION} ${DIRECT_ROUTE_DEFINITION} ${MODEL_L_DEFINITION} ${MODEL_K_DEFINITION}) target_link_libraries(WrongGPU PRIVATE wg_ui wg_core wgc_core comctl32 shell32 ole32 oleaut32 uuid advapi32 user32 gdi32 gdiplus dwmapi uxtheme d2d1 d3d11 dxgi dwrite windowscodecs uiautomationcore) @@ -316,3 +471,4 @@ if(MSVC) else() target_link_options(WrongGPU PRIVATE -municode -static) endif() +endif() diff --git a/clean/installer/README-linux.md b/clean/installer/README-linux.md new file mode 100644 index 00000000..101a90ff --- /dev/null +++ b/clean/installer/README-linux.md @@ -0,0 +1,133 @@ +# The launcher on Linux + +`WrongGPU` builds and runs as a native Linux program: the same screens, the same `src/app` and `src/wg_core` code as on +Windows. This file is for whoever maintains the launcher. The short version: **write the launcher the Windows way, and if +the Linux build then fails at a line, add that Windows call to `src/platform/posix`.** + +## How it works + +Three layers carry the shared code onto Linux. None of them touch the Windows build. + +- **Stand-in headers and the POSIX layer** (`src/platform/posix`). On Linux, CMake puts this folder first on the include + path, so ``, ``, `` and the other Windows headers the code includes resolve to + stand-ins that declare the calls the code makes. `win32_posix*.cpp` implements them on POSIX: files and paths + (UTF-8, `Z:\` is `/`, case-insensitive names), a registry kept in a file (`$XDG_DATA_HOME/WrongGPU/registry.ini`), + processes, pipes, a small job object, known folders from the XDG variables. The conventions (string widths, path + spelling, what fails on purpose) are in the header comment of `src/platform/posix/win32_posix.h`. +- **The window layer** (`win32_window_*.cpp`). It supplies the Win32 window calls `launcher_ui.cpp` makes (windows, + the message loop, timers, paint, DPI, capture, clipboard, text boxes) on SDL3, turning SDL's events into the `WM_*` + messages the window procedure already handles. The app draws its own title bar, so there is no libdecor. +- **The Cairo `Gfx`** (`src/app/ui_gfx_cairo.cpp`). All screens draw through one class, `Gfx` (`ui_shell.h`). Windows + implements it on Direct2D and DirectWrite (`ui_gfx.cpp`); Linux implements the same methods on Cairo, Pango and + fontconfig. Fonts are vendored in `assets/fonts` (Selawik for text, Noto Sans Math after it for the symbols Selawik lacks, such as the arrow, Fluent System Icons for icons) and found next to + the program, so the look does not depend on the user's fonts. + +## The rule + +A Windows call that the layer lacks **fails the Linux build** at that line. That is the point: the error tells you what +to add. Add it in `src/platform/posix` (declare it in the stand-in header, implement it in a `win32_posix*.cpp` file, +add a check to `src/platform/posix/tests/posix_layer_tests.cpp`). Do not add `#ifdef` branches around shared code unless +the feature is Windows' own (UI Automation, the DWM title bar, the old GDI+ wizard). + +One list in `CMakeLists.txt`, `WRONGGPU_APP_SOURCES`, holds the `src/app` files of both launchers, and `wg_core` has one list +for both, so a new shared file is compiled on Linux without any Linux-specific edit. Two short lists name the exceptions: +`WRONGGPU_APP_SOURCES_WINDOWS` (the GDI+ wizard, the Direct2D drawing) and `WRONGGPU_APP_SOURCES_LINUX` (the live-frame +hook); a new shared file goes in the first list only. The Windows-only targets stay under `if(WIN32)`. + +Two mistakes get past a Windows-only build, so `tools/ci/check_portable.py` looks for them (it runs as the ctest tests +`portable` and `portable-selftest`, and as a step of the Linux CI job): + +1. A `std::filesystem::path` built straight from a `wstring` in `src/wg_core` or `src/app`. Use `wg::FsPath(wstring)` + (`wg_core/util.h`): it spells a Windows-style path the way the host needs. +2. Direct2D, DirectWrite, WIC, DWM or UI Automation names in a shared `src/app` file outside `#ifdef _WIN32`. Names the + POSIX layer stands in for (the DWM calls, today) and names a file defines itself are fine. A file that exists only on + Windows goes in `WINDOWS_ONLY` at the top of the script. + +## Build and test on Linux + +You need CMake 3.16+, Ninja, GCC 11+, Python 3, the development files of Cairo, Pango, fontconfig and libjpeg-turbo (`libjpeg-turbo8-dev`), and SDL3 3.4 +(static; most distributions do not ship it yet: `build-appimage.sh` builds it, and `-DCMAKE_PREFIX_PATH=` +points CMake at one). + + cmake -S clean/installer -B out/linux -G Ninja -DCMAKE_BUILD_TYPE=Release -DWRONGGPU_TESTING=ON -DWRONGGPU_PRESET_K=OFF -DCMAKE_PREFIX_PATH= + cmake --build out/linux + ctest --test-dir out/linux --output-on-failure + +A `WRONGGPU_TESTING` build without `WRONGGPU_PAYLOAD_DIR` makes its own stand-in payload and test map. The tests never +open a window: they run SDL on its `offscreen` driver and give the program a home, XDG folders and registry file of its +own. Run it yourself the same way (`SDL_VIDEO_DRIVER=offscreen`) unless you want the real window. `linux-ui` renders the +screens to PNG and drives the live window with scripted input; `launcher-native` runs the launcher's verbs suite +(`tests/run_launcher_tests.py --native-linux`) against the binary; like CI's launcher build it needs +`-DWRONGGPU_PRESET_K=OFF`, and its one check that fails on main's own launcher too (#219) is skipped while it fails +(`tests/native_linux.py` `KNOWN_ON_MAIN`). + +## Build the AppImage + +One script, in the pinned Ubuntu 22.04 container so the AppImage runs on any desktop Linux with glibc 2.35 or newer, with +the X11 client libraries (libX11, libxcb) that every desktop provides, and the other host libraries the script lists +(`HOST_LIBS`: the glibc family, zlib and libuuid): + + clean/installer/build-appimage-container.sh --payload # podman or docker + clean/installer/build-appimage-container.sh --test-payload # smoke build, never ship + +The payload folder is the one you give `WRONGGPU_PAYLOAD_DIR` on Windows; `--version` and `--out` are optional (version: +`WRONGGPU_VERSION` in `CMakeLists.txt`; output: `build/appimage/out`). Without a container, run `build-appimage.sh` +inside any Ubuntu 22.04 as root (`WG_ALLOW_OTHER_HOST=1` skips the host check for a local trial; the AppImage then +may not run on older systems). The script lists no sources and no screens, only the host libraries it expects from the +system (`HOST_LIBS`, with the reason for each): `cmake --install` decides what ships (see the `install()` lines at the end +of `CMakeLists.txt`; a new asset folder needs an `install()` line there) and linuxdeploy copies in the libraries the +binary needs. The X11 libraries are left to the system on purpose: a second copy would clash with the desktop's. The last +step fails the build if any file needs a glibc or libstdc++ newer than Ubuntu 22.04's, a library that is neither in the +AppDir nor in `HOST_LIBS`, or the fonts are missing. + +The CI job `.github/workflows/linux-appimage.yml` runs only when the maintainer starts it from the Actions tab (Linux AppImage, +Run workflow); no pull request or push starts it. It builds the test stand-in payload (`--test-payload`) and keeps the AppImage for 3 +days (`actions/upload-artifact`, pinned to a commit SHA); it never ships. The release AppImage comes from +`build-appimage-container.sh --payload `. + +**Updating a pin.** The tool versions, their SHA-256 values and the container image digest are the first lines of +`build-appimage.sh` (the digest is also in the workflow; a CI step fails if the two differ). Change a version and its +checksum together, taken from the project's own release page. Use exact release tags, never "latest" or "continuous". + +## Known limits + +- **No upscaler yet:** with a released Proton, WrongGPU's upscaler does not start. vkd3d-proton's dxil-spirv cannot + translate the matrix kernels until dxil-spirv pull request 362 is in a Proton release. For now the native launcher + covers install and settings only; it does not make a game upscale. +- **Art:** Cairo reads PNG and libjpeg-turbo reads JPEG (`src/app/jpeg_decode_linux.cpp`; Windows uses WIC), so Steam's + art (hero, header, capsule) shows. Other formats give the page's plain plate, as for a game without art. +- **No downloads:** WinHTTP is answered "not available" and `DownloadsAvailable()` (`util.h`) is false natively, so the in-launcher + downloads (OptiScaler's edition, the release check) do not run on Linux. Settings says so (the OptiScaler row asks for the + player's own OptiScaler download, the release check has no switch), and a game's install without one says the same in words. +- **Uninstall:** an AppImage has no installer entry, so Settings > Uninstall WrongGPU (`uninstall-appimage --confirm` on the command line) + deletes the AppImage file named by `$APPIMAGE` and WrongGPU's data folder (`$XDG_DATA_HOME/WrongGPU`), after one confirmation that names + both, and nothing else. It refuses unless `$APPIMAGE` is a plain file (not a link) called `WrongGPU...AppImage` with an AppImage's header, + and the system itself ties that file to this running program: `$APPDIR` (resolved case-sensitively) is a FUSE mount in `/proc/self/mountinfo` + that this program runs on, and a live process whose executable is that very file (same device and inode) holds the mount's `/dev/fuse` + connection (`fuse_connection` in its `fdinfo`; the AppImage runtime serves its own mount from its own file). An unpacked AppImage + (`APPIMAGE_EXTRACT_AND_RUN`) or an unreadable `/proc` gives no such proof, so it refuses. The file is checked again just before it + is deleted (same device and inode, still a plain AppImage) and goes first, then the data. It also refuses while a game still has + WrongGPU (uninstall it from the game first). + The player's own ignore list (`ignore-files.txt`) stays, as in the Windows launcher's "Remove data". There is no "Install for this user" + on Linux: the first-run sheet and Settings do not offer it. +- **Engine.ini for Borderlands 4 and Hogwarts Legacy:** it goes into the game's Proton prefix (a Steam game: + `/steamapps/compatdata//pfx/drive_c/users/steamuser`). Until Steam has made that folder (the game was started once) the + launcher says so and writes nothing. A game that is not from Steam needs the Windows user folder of its Wine prefix once: + `WrongGPU windows-folder "" ""`, remembered in `windows-folders.txt` in the data folder. There is no text field for it in + the window yet (no file picker either). +- **Ray Reconstruction preparation:** the game prepares its kernels at its first start (its shader caches are Proton's), so the launcher + runs no helper and its Play never fails on it. +- **No restorer:** `WrongGPU-Restore.exe` is a Windows program. A Linux install does not embed or write it. +- **UI Automation:** the stubs answer nothing; there is no screen-reader support yet (AT-SPI is the Linux equivalent). +- **GPU check:** there is no DXGI here, so the launcher reads Linux's own device list (`/sys/class/drm`): the card's name + comes from a built-in list of the RDNA 4 PCI ids (`kRdna4Cards` in `checks.cpp`; any other card is named by its code), and + only an RDNA 4 card (RX 9000 series) counts as supported. It names the card the system has, not the one a game picks. +- **Parked:** the Ray Reconstruction preparation (it must run in the game's Wine prefix). +- **Not emulated:** NTFS junctions, `.lnk` shortcuts, Apps & features, UAC elevation, share-mode locks between processes. + The launcher tests skip the checks that depend on them and print why. +- **Game running:** the per-game state lock works between Linux processes (file locks), and uninstall, repair and update + refuse while one of your Wine processes has a WrongGPU DLL or program loaded, as Windows does (`/proc` mappings). If + one of your Wine processes cannot be read, the launcher refuses rather than guess. Not covered: other users' processes, + files a program only has open, and a game started after the check. +- **Hidden attribute:** kept as the user extended attribute `user.wronggpu.hidden`, so it shows only on a file system that + allows those. Read-only is the missing write bit, as before. diff --git a/clean/installer/README.md b/clean/installer/README.md index 53ffa1a5..91031aae 100644 --- a/clean/installer/README.md +++ b/clean/installer/README.md @@ -978,6 +978,10 @@ Windows (the Wine run was not repeated for them): the result warns, `status` says `rr_available: false` with `rr_unavailable_why`, and the RR card says RR is unavailable with the plain reason; a repair with the edition makes it available (`optiscaler_edition`, read from the install record's hash of OptiScaler's DLL). Cyberpunk 2077 and RE Requiem always count as game-interface RR games. + `--native-linux ` runs the same suite against the Linux binary (`tests/native_linux.py`: its XDG folders, registry file + and SDL offscreen driver under `--work`, paths in the Windows spelling the program prints; the checks that only mean something + on Windows are skipped with their reasons printed). A Linux `-DWRONGGPU_TESTING=ON` build without `WRONGGPU_PAYLOAD_DIR` makes + the stand-in payload and test map itself and runs the suite as the ctest `launcher-native`. - `tests/coexist_tests.cpp` (ctest `coexist-core`, every build): the marker scan and fingerprints on synthetic bytes, tool and decision names, overlays, the proxy picker on a generated folder, byte-exact OptiScaler.ini value edits, the OptiScaler tab's rules (locked, editable only when present, value checks), the inikey journal (revert byte for diff --git a/clean/installer/assets/fonts/fluent/FluentSystemIcons-Regular.ttf b/clean/installer/assets/fonts/fluent/FluentSystemIcons-Regular.ttf new file mode 100644 index 00000000..cb490ba3 Binary files /dev/null and b/clean/installer/assets/fonts/fluent/FluentSystemIcons-Regular.ttf differ diff --git a/clean/installer/assets/fonts/fluent/LICENSE b/clean/installer/assets/fonts/fluent/LICENSE new file mode 100644 index 00000000..bc9c36b2 --- /dev/null +++ b/clean/installer/assets/fonts/fluent/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 Microsoft Corporation + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/clean/installer/assets/fonts/notosansmath/NotoSansMath-Regular.ttf b/clean/installer/assets/fonts/notosansmath/NotoSansMath-Regular.ttf new file mode 100644 index 00000000..c7d5c6c4 Binary files /dev/null and b/clean/installer/assets/fonts/notosansmath/NotoSansMath-Regular.ttf differ diff --git a/clean/installer/assets/fonts/notosansmath/OFL.txt b/clean/installer/assets/fonts/notosansmath/OFL.txt new file mode 100644 index 00000000..282f3cd4 --- /dev/null +++ b/clean/installer/assets/fonts/notosansmath/OFL.txt @@ -0,0 +1,93 @@ +Copyright 2022 The Noto Project Authors (https://github.com/notofonts/math) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/clean/installer/assets/fonts/selawik/OFL.txt b/clean/installer/assets/fonts/selawik/OFL.txt new file mode 100644 index 00000000..ac8fdb95 --- /dev/null +++ b/clean/installer/assets/fonts/selawik/OFL.txt @@ -0,0 +1,91 @@ +Copyright 2015, Microsoft Corporation (www.microsoft.com), with Reserved Font Name Selawik. All Rights Reserved. Selawik is a trademark of Microsoft Corporation in the United States and/or other countries. + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/clean/installer/assets/fonts/selawik/selawk.ttf b/clean/installer/assets/fonts/selawik/selawk.ttf new file mode 100644 index 00000000..736bac3c Binary files /dev/null and b/clean/installer/assets/fonts/selawik/selawk.ttf differ diff --git a/clean/installer/assets/fonts/selawik/selawkb.ttf b/clean/installer/assets/fonts/selawik/selawkb.ttf new file mode 100644 index 00000000..2134a765 Binary files /dev/null and b/clean/installer/assets/fonts/selawik/selawkb.ttf differ diff --git a/clean/installer/assets/fonts/selawik/selawkl.ttf b/clean/installer/assets/fonts/selawik/selawkl.ttf new file mode 100644 index 00000000..cbfaaf99 Binary files /dev/null and b/clean/installer/assets/fonts/selawik/selawkl.ttf differ diff --git a/clean/installer/assets/fonts/selawik/selawksb.ttf b/clean/installer/assets/fonts/selawik/selawksb.ttf new file mode 100644 index 00000000..5ec501d8 Binary files /dev/null and b/clean/installer/assets/fonts/selawik/selawksb.ttf differ diff --git a/clean/installer/assets/fonts/selawik/selawksl.ttf b/clean/installer/assets/fonts/selawik/selawksl.ttf new file mode 100644 index 00000000..bc3fa080 Binary files /dev/null and b/clean/installer/assets/fonts/selawik/selawksl.ttf differ diff --git a/clean/installer/assets/wronggpu.desktop b/clean/installer/assets/wronggpu.desktop new file mode 100644 index 00000000..184f846a --- /dev/null +++ b/clean/installer/assets/wronggpu.desktop @@ -0,0 +1,8 @@ +[Desktop Entry] +Type=Application +Name=WrongGPU +Comment=Install and manage WrongGPU for your games +Exec=WrongGPU +Icon=wronggpu +Terminal=false +Categories=Utility; diff --git a/clean/installer/build-appimage-container.sh b/clean/installer/build-appimage-container.sh new file mode 100755 index 00000000..7563d837 --- /dev/null +++ b/clean/installer/build-appimage-container.sh @@ -0,0 +1,27 @@ +#!/usr/bin/env bash +# SPDX-License-Identifier: MIT +# Runs build-appimage.sh in the pinned Ubuntu 22.04 container with podman (or docker), from any Linux host. +# ./build-appimage-container.sh --payload [--version x.y.z] [--out ] +# ./build-appimage-container.sh --test-payload +# The repository is mounted read-write at /src; the payload folder and --out must be inside it. Output: build/appimage/out. +set -euo pipefail +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO="$(git -C "$HERE" rev-parse --show-toplevel)" +IMAGE="$(sed -n 's/^CONTAINER_IMAGE="\(.*\)"/\1/p' "$HERE/build-appimage.sh")" +ENGINE="${CONTAINER_ENGINE:-$(command -v podman || command -v docker)}" +[ -n "$ENGINE" ] || { echo "install podman or docker" >&2; exit 1; } +# Paths on the command line are repository-relative inside the container. +args=(); while [ $# -gt 0 ]; do + case "$1" in + --payload|--out) p="$(mkdir -p "$2" && cd "$2" && pwd)"; case "$p" in "$REPO"/*) ;; *) echo "$1 must be inside $REPO" >&2; exit 2 ;; esac + args+=("$1" "/src/${p#"$REPO"/}"); shift 2 ;; + *) args+=("$1"); shift ;; + esac +done +# Rootless podman maps the invoking user to root inside, so files written to the mount belong to the caller. Docker needs +# --user, but apt needs root: it runs as root and the files are handed back at the end. +OWNER=""; [ "$(basename "$ENGINE")" = docker ] && OWNER="chown -R $(id -u):$(id -g) /src/build/appimage;" +# WG_WORK (scratch outside the repository) is mounted at the same path. +MOUNTS=(-v "$REPO:/src"); [ -z "${WG_WORK:-}" ] || { mkdir -p "$WG_WORK"; MOUNTS+=(-v "$WG_WORK:$WG_WORK" -e WG_WORK); } +exec "$ENGINE" run --rm "${MOUNTS[@]}" -w /src "$IMAGE" bash -c \ + "set +e; /src/clean/installer/build-appimage.sh \"\$@\"; rc=\$?; $OWNER exit \$rc" bash "${args[@]}" diff --git a/clean/installer/build-appimage.sh b/clean/installer/build-appimage.sh new file mode 100755 index 00000000..505dace0 --- /dev/null +++ b/clean/installer/build-appimage.sh @@ -0,0 +1,250 @@ +#!/usr/bin/env bash +# SPDX-License-Identifier: MIT +# Builds WrongGPU--x86_64.AppImage, the Linux launcher, from this checkout. +# +# build-appimage.sh --payload [--version x.y.z] [--out ] +# build-appimage.sh --test-payload [--version x.y.z] [--out ] smoke build with the test stand-in payload; never ship it +# +# Run it inside the pinned Ubuntu 22.04 container (build-appimage-container.sh does that from any host). The AppImage runs +# on every system whose glibc is as old as the build system's or newer; building on a newer system raises that floor +# silently, so the script refuses other hosts and step 9 fails on any file that needs a newer glibc. +# +# The script does not know the launcher's source files or screens: CMakeLists.txt's install() rules decide what ships and +# linuxdeploy follows the binary's shared-library dependencies. The only libraries it names are the host libraries it +# expects from the user's system (HOST_LIBS below); step 9 fails on any other dependency the AppDir does not carry. +# New launcher code needs no edit here. +set -euo pipefail + +# ---- 0. Pinned inputs --------------------------------------------------------------------------------------------------- +# Every download is checked against its SHA-256 before use. Exact versions on purpose: a "latest" URL changes under the +# same checksum. To update a pin, change the version and the checksum together (README-linux.md, "Updating a pin"). +CONTAINER_IMAGE="docker.io/library/ubuntu:22.04@sha256:74b12b11ffa550fba1929ad4d8d16533c34f6612728469671afba1b03b66881c" + +SDL_VERSION="3.4.18" +SDL_URL="https://github.com/libsdl-org/SDL/releases/download/release-${SDL_VERSION}/SDL3-${SDL_VERSION}.tar.gz" +SDL_SHA256="9c75cf16330322c217dedd2e0609f1124f1b54b8633e763467b4684d0f4334a3" + +LINUXDEPLOY_TAG="1-alpha-20251107-1" +LINUXDEPLOY_URL="https://github.com/linuxdeploy/linuxdeploy/releases/download/${LINUXDEPLOY_TAG}/linuxdeploy-x86_64.AppImage" +LINUXDEPLOY_SHA256="c20cd71e3a4e3b80c3483cef793cda3f4e990aca14014d23c544ca3ce1270b4d" + +APPIMAGETOOL_TAG="1.9.1" +APPIMAGETOOL_URL="https://github.com/AppImage/appimagetool/releases/download/${APPIMAGETOOL_TAG}/appimagetool-x86_64.AppImage" +APPIMAGETOOL_SHA256="ed4ce84f0d9caff66f50bcca6ff6f35aae54ce8135408b3fa33abfc3cb384eb0" + +# appimagetool fetches "the newest runtime" unless it is given one; that would tie the build to the day it runs. +RUNTIME_TAG="20251108" +RUNTIME_URL="https://github.com/AppImage/type2-runtime/releases/download/${RUNTIME_TAG}/runtime-x86_64" +RUNTIME_SHA256="2fca8b443c92510f1483a883f60061ad09b46b978b2631c807cd873a47ec260d" + +MAX_GLIBC="2.35" # Ubuntu 22.04; decided by the maintainer +# The newest libstdc++ symbol versions Ubuntu 22.04's libstdc++6 (12.x) provides. The binary links libstdc++ statically, so +# nothing in the AppDir should need either; step 9 reports anything that does. +MAX_GLIBCXX="3.4.30" +MAX_CXXABI="1.3.13" + +# The shared libraries the AppImage deliberately does not carry: it takes them from the user's system. Step 9 fails when a +# file in the AppDir needs any other library that the AppDir lacks. Each entry is here for a reason: +# - the glibc family: a second copy cannot work, and MAX_GLIBC bounds what the AppImage asks of it. libdl, libpthread and +# librt are folded into libc since glibc 2.34, kept as empty stubs for programs linked before that; +# - libX11.so.6 and libxcb.so.1: the X11 client libraries. Cairo's X11 backend and SDL3 open the user's own, and linuxdeploy +# excludes them on purpose: a second copy clashes with the one the desktop's other programs load. Every graphical desktop +# has them, Wayland ones through XWayland; +# - libz.so.1 and libuuid.so.1: base libraries of every Debian, Ubuntu, Fedora and Arch install (zlib, util-linux), which +# Cairo, FreeType, GIO and libpng (zlib) and fontconfig (uuid) need. linuxdeploy's exclude list leaves them out too. +# What the build adds beyond the glibc family was read from the AppDir's own NEEDED entries (readelf -d on every ELF file). +HOST_LIBS=( + ld-linux-x86-64.so.2 libc.so.6 libm.so.6 libdl.so.2 libpthread.so.0 librt.so.1 + libX11.so.6 libxcb.so.1 + libz.so.1 libuuid.so.1 +) + +# From Ubuntu 22.04's archive, unpinned: apt versions follow Ubuntu's security updates, the container digest bounds the drift. +APT_PACKAGES=( + ca-certificates curl git binutils file python3 cmake ninja-build pkg-config build-essential + libcairo2-dev libpango1.0-dev libfontconfig-dev # the launcher's drawing + libjpeg-turbo8-dev # Steam's JPEG art (bundled; THIRD-PARTY-NOTICES 4.1) + libx11-dev libxext-dev libxcursor-dev libxi-dev libxfixes-dev libxrandr-dev libxtst-dev # SDL3's X11 backend + libxkbcommon-dev libwayland-dev wayland-protocols libdbus-1-dev libudev-dev # SDL3's Wayland, D-Bus and udev + libasound2-dev libpulse-dev # SDL3's audio +) + +# ---- 1. Arguments and paths --------------------------------------------------------------------------------------------- +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" # clean/installer, where CMakeLists.txt is +PAYLOAD="" ; TEST_PAYLOAD=0 ; VERSION="" ; OUT="" +usage() { sed -n '3,6p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//' >&2; exit 2; } +while [ $# -gt 0 ]; do + case "$1" in + --payload) [ $# -ge 2 ] || usage; PAYLOAD="$(cd "$2" && pwd)"; shift 2 ;; + --test-payload) TEST_PAYLOAD=1; shift ;; + --version) [ $# -ge 2 ] || usage; VERSION="$2"; shift 2 ;; + --out) [ $# -ge 2 ] || usage; mkdir -p "$2"; OUT="$(cd "$2" && pwd)"; shift 2 ;; + *) usage ;; + esac +done +# exactly one of --payload and --test-payload +if [ -n "$PAYLOAD" ] && [ "$TEST_PAYLOAD" = 1 ]; then usage; fi +if [ -z "$PAYLOAD" ] && [ "$TEST_PAYLOAD" = 0 ]; then usage; fi +# One source of the version: the default in CMakeLists.txt, as on Windows. +[ -n "$VERSION" ] || VERSION="$(sed -n 's/^set(WRONGGPU_VERSION "\([^"]*\)".*/\1/p' "$HERE/CMakeLists.txt")" +[ -n "$VERSION" ] || { echo "cannot read WRONGGPU_VERSION from CMakeLists.txt; pass --version" >&2; exit 2; } + +WORK="${WG_WORK:-$HERE/../../build/appimage}" # scratch inside the project, never /tmp (a reboot wipes it) +mkdir -p "$WORK"; WORK="$(cd "$WORK" && pwd)" +OUT="${OUT:-$WORK/out}"; mkdir -p "$OUT" +CACHE="$WORK/cache" ; DEPS="$WORK/deps" ; BUILD="$WORK/cmake" ; APPDIR="$WORK/AppDir" +mkdir -p "$CACHE" "$DEPS" +# The same commit gives the same file times in the squashfs. +export SOURCE_DATE_EPOCH="${SOURCE_DATE_EPOCH:-$(git -c safe.directory='*' -C "$HERE" log -1 --format=%ct 2>/dev/null || date +%s)}" +step() { printf '\n==== %s\n' "$*"; } +START=$SECONDS + +# ---- 2. Host check ------------------------------------------------------------------------------------------------------ +step "2. Host" +# os-release defines VERSION, which is also this script's variable: read it in a subshell. +HOST="$( [ -r /etc/os-release ] && . /etc/os-release && echo "${ID:-unknown} ${VERSION_ID:-}" || echo "unknown" )" +if [ "$HOST" != "ubuntu 22.04" ]; then + [ "${WG_ALLOW_OTHER_HOST:-0}" = 1 ] || { + echo "This is not Ubuntu 22.04 ($HOST): the AppImage would need a newer glibc than 22.04's." >&2 + echo "Use build-appimage-container.sh, or set WG_ALLOW_OTHER_HOST=1 for a local test build that must not be shipped." >&2 + exit 1; } +fi + +# ---- 3. Packages -------------------------------------------------------------------------------------------------------- +step "3. apt packages" +if [ "$(id -u)" = 0 ]; then + export DEBIAN_FRONTEND=noninteractive + apt-get update -qq + apt-get install -y -qq --no-install-recommends "${APT_PACKAGES[@]}" +else + echo "not root: assuming the packages are installed (${APT_PACKAGES[*]})" +fi + +# ---- 4. Pinned tools ---------------------------------------------------------------------------------------------------- +step "4. Pinned tools" +fetch() { # fetch : checks before anything runs, so a changed file stops the build + if [ -f "$3" ] && echo "$2 $3" | sha256sum -c --status -; then return 0; fi + curl --fail --location --silent --show-error --retry 3 --output "$3.part" "$1" + echo "$2 $3.part" | sha256sum -c --status - || { echo "checksum mismatch for $1" >&2; rm -f "$3.part"; exit 1; } + mv "$3.part" "$3" +} +fetch "$SDL_URL" "$SDL_SHA256" "$CACHE/SDL3-$SDL_VERSION.tar.gz" +fetch "$LINUXDEPLOY_URL" "$LINUXDEPLOY_SHA256" "$CACHE/linuxdeploy-$LINUXDEPLOY_TAG.AppImage" +fetch "$APPIMAGETOOL_URL" "$APPIMAGETOOL_SHA256" "$CACHE/appimagetool-$APPIMAGETOOL_TAG.AppImage" +fetch "$RUNTIME_URL" "$RUNTIME_SHA256" "$CACHE/runtime-$RUNTIME_TAG" +chmod +x "$CACHE"/*.AppImage +# Containers have no FUSE: unpack each AppImage once and run its AppRun. +unpack() { # unpack + if [ ! -x "$2/AppRun" ]; then + rm -rf "$2" "$2.tmp"; mkdir -p "$2.tmp" + (cd "$2.tmp" && "$1" --appimage-extract >/dev/null) && mv "$2.tmp/squashfs-root" "$2" && rmdir "$2.tmp" + fi +} +unpack "$CACHE/linuxdeploy-$LINUXDEPLOY_TAG.AppImage" "$CACHE/linuxdeploy-$LINUXDEPLOY_TAG" +unpack "$CACHE/appimagetool-$APPIMAGETOOL_TAG.AppImage" "$CACHE/appimagetool-$APPIMAGETOOL_TAG" +LINUXDEPLOY="$CACHE/linuxdeploy-$LINUXDEPLOY_TAG/AppRun" +APPIMAGETOOL="$CACHE/appimagetool-$APPIMAGETOOL_TAG/AppRun" + +# ---- 5. SDL3, built static ---------------------------------------------------------------------------------------------- +# Ubuntu 22.04 has no SDL3. Static, so there is no SDL soname to match on the user's system. SDL still opens the user's own +# X11, Wayland, audio and udev libraries at run time. The app draws its own title bar, so no libdecor. +step "5. SDL3 $SDL_VERSION (static)" +if [ ! -f "$DEPS/.sdl-$SDL_VERSION" ]; then + rm -rf "$DEPS/sdl-src" "$DEPS/sdl-build"; mkdir -p "$DEPS/sdl-src" + tar -xf "$CACHE/SDL3-$SDL_VERSION.tar.gz" -C "$DEPS/sdl-src" --strip-components=1 + cmake -S "$DEPS/sdl-src" -B "$DEPS/sdl-build" -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX="$DEPS" \ + -DSDL_SHARED=OFF -DSDL_STATIC=ON -DSDL_TESTS=OFF -DSDL_EXAMPLES=OFF -DSDL_X11_XSCRNSAVER=OFF \ + -DSDL_WAYLAND_LIBDECOR=OFF -DCMAKE_POSITION_INDEPENDENT_CODE=ON + # one command per line: in "a && b", set -e ignores a failing a, and the stamp would then claim a build that never finished + cmake --build "$DEPS/sdl-build" + cmake --install "$DEPS/sdl-build" + touch "$DEPS/.sdl-$SDL_VERSION" +fi + +# ---- 6. The launcher ---------------------------------------------------------------------------------------------------- +# -static-libstdc++/-static-libgcc: the C++ runtime is the other thing that raises the glibc/libstdc++ floor. +step "6. Target WrongGPU $VERSION" +CMAKE_PAYLOAD=(-DWRONGGPU_PAYLOAD_DIR="$PAYLOAD" -DWRONGGPU_TESTING=OFF) +# Without a payload folder, a WRONGGPU_TESTING build makes its own stand-in payload; the app is the same code. +[ "$TEST_PAYLOAD" = 1 ] && CMAKE_PAYLOAD=(-DWRONGGPU_TESTING=ON) +cmake -S "$HERE" -B "$BUILD" -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_PREFIX_PATH="$DEPS" \ + -DCMAKE_EXE_LINKER_FLAGS="-static-libstdc++ -static-libgcc" -DWRONGGPU_VERSION="$VERSION" "${CMAKE_PAYLOAD[@]}" +cmake --build "$BUILD" --target WrongGPU + +# ---- 7. AppDir ---------------------------------------------------------------------------------------------------------- +# cmake --install is the one place that lists what ships (the binary, the fonts, the menu entry, the icon). +step "7. AppDir" +rm -rf "$APPDIR" +cmake --install "$BUILD" --prefix "$APPDIR/usr" +# linuxdeploy copies in the shared libraries the binary needs (Cairo, Pango, GLib, ...), but its built-in exclude list leaves +# out fontconfig, FreeType, HarfBuzz, FriBidi and expat, which would then come from the user's system: text could then look +# different from one distribution to the next, or the program fail to start on a minimal one. They are forced in. The X11 +# libraries stay on the exclude list: SDL opens the user's own, and a second copy in the AppImage would clash with them. Libraries SDL opens at run time are not found +# by following the binary either; EXTRA_LIBS="/path/a.so /path/b.so" adds one that turns out missing. +FORCE=() +for soname in libfontconfig.so.1 libfreetype.so.6 libharfbuzz.so.0 libfribidi.so.0 libexpat.so.1; do + path="$(ldconfig -p | awk -v s="$soname" '$1 == s && /x86-64/ { print $NF; exit }')" + [ -n "$path" ] || { echo "$soname is not installed in this container" >&2; exit 1; } + FORCE+=(--library "$path") +done +for l in ${EXTRA_LIBS:-}; do FORCE+=(--library "$l"); done +"$LINUXDEPLOY" --appdir "$APPDIR" --executable "$APPDIR/usr/bin/WrongGPU" \ + --desktop-file "$APPDIR/usr/share/applications/wronggpu.desktop" \ + --icon-file "$APPDIR/usr/share/icons/hicolor/256x256/apps/wronggpu.png" "${FORCE[@]}" + +# ---- 8. Pack ------------------------------------------------------------------------------------------------------------ +step "8. AppImage" +NAME="WrongGPU-$VERSION-x86_64"; [ "$TEST_PAYLOAD" = 1 ] && NAME="$NAME-testpayload" +ARCH=x86_64 "$APPIMAGETOOL" --runtime-file "$CACHE/runtime-$RUNTIME_TAG" "$APPDIR" "$OUT/$NAME.AppImage" +(cd "$OUT" && sha256sum "$NAME.AppImage" > "$NAME.AppImage.sha256") + +# ---- 9. Checks on the AppDir -------------------------------------------------------------------------------------------- +# The ways an AppImage breaks far from the build machine: a file that needs a newer glibc (or libstdc++) than the user's, a +# shared library that is neither in the AppDir nor one the system is expected to have (HOST_LIBS), a drawing library left +# out, and missing fonts (the text would fall back to whatever the user has, and the icons would be blank). +step "9. Checks" +fail=0 +declare -A host_lib=() in_appdir=() +for l in "${HOST_LIBS[@]}"; do host_lib[$l]=1; done +# find -L: a symbolic link that leads nowhere does not count as carried +while IFS= read -r -d '' f; do in_appdir[${f##*/}]=1; done < <(find -L "$APPDIR" -type f -name '*.so*' -print0) +newest() { # newest : the highest version of that prefix, empty when none + { grep -o "$1_[0-9][0-9.]*" <<<"$2" || true; } | sed "s/^$1_//" | sort -V | tail -1 +} +too_new() { # too_new : true when the version is above the limit + [ -n "$1" ] && [ "$(printf '%s\n%s\n' "$1" "$2" | sort -V | tail -1)" != "$2" ] +} +while IFS= read -r -d '' f; do + rel="${f#"$APPDIR"/}" + magic="$(file -b "$f")" + case "$magic" in ELF*) ;; *) continue ;; esac + # a failing readelf or objdump fails the step: it must never read as "nothing needed" + dyn="$(readelf -d "$f" 2>&1)" || { echo "FAIL: readelf -d failed on $rel: $dyn" >&2; fail=1; continue; } + syms="" + if ! grep -q 'There is no dynamic section' <<<"$dyn"; then + syms="$(objdump -T "$f" 2>&1)" || { echo "FAIL: objdump -T failed on $rel: $syms" >&2; fail=1; continue; } + fi + v="$(newest GLIBC "$syms")" + if too_new "$v" "$MAX_GLIBC"; then echo "FAIL: $rel needs GLIBC_$v (limit $MAX_GLIBC)" >&2; fail=1; fi + cxx="$(newest GLIBCXX "$syms")" + if too_new "$cxx" "$MAX_GLIBCXX"; then echo "FAIL: $rel needs GLIBCXX_$cxx (Ubuntu 22.04 has up to $MAX_GLIBCXX)" >&2; fail=1; fi + abi="$(newest CXXABI "$syms")" + if too_new "$abi" "$MAX_CXXABI"; then echo "FAIL: $rel needs CXXABI_$abi (Ubuntu 22.04 has up to $MAX_CXXABI)" >&2; fail=1; fi + while IFS= read -r need; do + [ -n "$need" ] || continue + if [ -z "${host_lib[$need]:-}" ] && [ -z "${in_appdir[$need]:-}" ]; then + echo "FAIL: $rel needs $need, which is neither in the AppDir nor in HOST_LIBS" >&2; fail=1 + fi + done < <(sed -n 's/.*(NEEDED).*\[\(.*\)\]/\1/p' <<<"$dyn") + echo "glibc ${v:-none}: $rel" +done < <(find "$APPDIR" -type f -print0) +for lib in libcairo.so.2 libpango-1.0.so.0 libpangocairo-1.0.so.0 libfontconfig.so.1 libfreetype.so.6 libharfbuzz.so.0 libfribidi.so.0 libexpat.so.1; do + [ -e "$APPDIR/usr/lib/$lib" ] || { echo "FAIL: $lib is not in the AppDir" >&2; fail=1; } +done +for font in selawik/selawk.ttf notosansmath/NotoSansMath-Regular.ttf fluent/FluentSystemIcons-Regular.ttf; do + [ -s "$APPDIR/usr/share/wronggpu/assets/fonts/$font" ] || { echo "FAIL: font $font is not in the AppDir" >&2; fail=1; } +done +[ "$fail" = 0 ] || exit 1 +echo "glibc, libstdc++, dependencies and fonts: ok (limit GLIBC_$MAX_GLIBC; host libraries: ${HOST_LIBS[*]})" +echo +echo "built $OUT/$NAME.AppImage ($(du -h "$OUT/$NAME.AppImage" | cut -f1), $((SECONDS - START)) s)" diff --git a/clean/installer/build-mingw.sh b/clean/installer/build-mingw.sh index 8e61b02e..1b21bf12 100755 --- a/clean/installer/build-mingw.sh +++ b/clean/installer/build-mingw.sh @@ -23,7 +23,7 @@ python3 tools/make_payload.py --payload "$PAYLOAD" --map "$MAP" --version "$VERS CONV=../converter/src CONV_SRC="$CONV/sha256.cpp $CONV/json.cpp $CONV/numeric.cpp $CONV/map.cpp $CONV/locate.cpp $CONV/lz4block.cpp $CONV/convert.cpp $CONV/output.cpp $CONV/pe_version.cpp $CONV/api.cpp" FLAGS="-std=c++17 -O2 -Wall -Wextra -ffp-contract=off -municode -mwindows -static -I$GEN -I$CONV -Isrc $TESTING_DEFINE" -LIBS="-lcomctl32 -lshell32 -lole32 -luuid -ladvapi32 -luser32 -lgdi32 -lgdiplus -ldwmapi -luxtheme -lwinhttp" +LIBS="-lcomctl32 -lshell32 -lole32 -luuid -ladvapi32 -luser32 -lgdi32 -lgdiplus -ldwmapi -luxtheme -lwinhttp -lrstrtmgr" # the restorer: wg_core without payload or UI printf '1 ICON "app.ico"\n' > "$GEN/restore_app.rc" "$WINDRES" -O coff -I"$GEN" -i "$GEN/restore_app.rc" -o "$GEN/restore_app.o" diff --git a/clean/installer/src/app/app.h b/clean/installer/src/app/app.h index 5b33d03f..032aff53 100644 --- a/clean/installer/src/app/app.h +++ b/clean/installer/src/app/app.h @@ -7,7 +7,9 @@ #include "wg_core/install.h" #include "wg_core/logs.h" -#include "wg_ui/kit.h" +#ifdef _WIN32 +#include "wg_ui/kit.h" // the wizard's GDI+ widgets: not on Linux +#endif #include "wizard_policy.h" namespace wg::app { @@ -17,7 +19,9 @@ enum PageId { PG_WELCOME, PG_GAME, PG_REVIEW, PG_PROGRESS, PG_FINISH, PG_UCONFIR struct App { Context ctx; // the engine's state (wg_core): log file, converter map, OptiScaler package, embedded payload HINSTANCE hinst{}; HWND hwnd{}; +#ifdef _WIN32 ui::Kit kit; // the widget kit (wg_ui): DPI scale, fonts, brushes, control backgrounds, hover, wordmark +#endif bool hipCheck = false; bool uninstall = false, collect = false, list = false, fsr4 = false, noScan = false, force = false, silent = false, go = false, elevatedRelaunch = false; bool experimentalOk = false, moveMods = false, removeOld = false; diff --git a/clean/installer/src/app/cli.cpp b/clean/installer/src/app/cli.cpp index 67efccb5..5eb5e320 100644 --- a/clean/installer/src/app/cli.cpp +++ b/clean/installer/src/app/cli.cpp @@ -14,6 +14,11 @@ // set key=value ... per-game settings (written to the game at once); set --global key=value ... // set opti.
.=value: an editable key of the game's OptiScaler.ini // get [key] | get --global +// uninstall-appimage [--confirm] Linux, run from the AppImage: the AppImage file ($APPIMAGE) and WrongGPU's data folder removed, +// nothing else; without --confirm only says what would go (refused while a game has WrongGPU) +// windows-folder [ | --clear] Linux, a game that is not a Steam game: the game's Windows user folder (inside its +// Wine prefix: drive_c/users/) it keeps Engine.ini in, chosen once and remembered; no +// folder shows the one remembered // opti [--reset] [--keep] the OptiScaler tab: locked and editable keys, outside edits; --reset puts the // editable keys back byte for byte, --keep accepts values OptiScaler saved over ours // coexist the rules table for one game: every tool found, its fingerprint and decision, the @@ -56,6 +61,7 @@ #include "wg_core/payload.h" #include "wg_core/pe.h" #include "wg_core/rr.h" +#include "wg_core/appimage.h" #include "wg_core/rrconfig.h" #include "wg_core/rrprep.h" @@ -494,7 +500,7 @@ static void RrConfigAfterInstall(const Args& a, const wstring& dir, OpResult& re return; } if (p.get("rr_config_fix") != "ask") return; - const wstring steps = RrConfigSteps(*rg, RrConfigFile(g.ctx, *rg, nullptr)); + const wstring steps = RrConfigSteps(*rg, RrConfigFile(g.ctx, *rg, m.exe, nullptr)); const wstring set = L"WrongGPU.exe set \"" + m.exe + L"\" rr_config_fix=on"; o.j.Key("rr_config_question").Obj().S("game", rg->name).S("text", RrConfigNotice(*rg)).S("steps", steps).S("fix", set) .S("myself", L"WrongGPU.exe set \"" + m.exe + L"\" rr_config_fix=off").End(); @@ -791,6 +797,33 @@ int Verb(const wstring& verb, const Args& a, Output& o) { ResultJson(o, res); return res.code; } + if (verb == L"uninstall-appimage") { // appimage.h: the AppImage and WrongGPU's data folder, after the player's confirmation + wstring file, why; + if (!OwnAppImage(file, &why)) { o.j.S("error", why); Print(why); return EXIT_REFUSED; } + const wstring data = AppDataPath(); + o.j.Key("appimage").Obj().S("file", file).S("data", data); + if (!a.has(L"confirm")) { + o.j.B("removed", false).End(); + Print(L"Would delete " + file + L" and WrongGPU's data folder " + data + L". Nothing was removed; add --confirm to do it."); + return EXIT_OK; + } + wstring kept, gone; + if (!UninstallAppImage(g.ctx, &why, &gone, &kept)) { o.j.B("removed", !gone.empty()).End(); o.j.S("error", why); Print(why); return EXIT_REFUSED; } + o.j.B("removed", true).S("kept", kept).End(); + Print(L"WrongGPU is uninstalled: " + file + L" and " + data + L" are deleted." + (kept.empty() ? wstring() : L" " + kept)); + return EXIT_OK; + } + if (verb == L"windows-folder") { // rrconfig.h: where a non-Steam game's Windows profile is (asked once, remembered) + wstring exe, dir, why; + if (!Game(a, o, exe, dir)) return o.code; + if (a.pos.size() > 1 || a.has(L"clear")) { + if (!RememberWindowsFolder(g.ctx, exe, a.has(L"clear") ? wstring() : a.pos[1], &why)) { o.j.S("error", why); Print(why); return EXIT_REFUSED; } + } + const wstring chosen = RememberedWindowsFolder(g.ctx, exe); + o.j.Key("windows_folder").Obj().S("exe", exe).S("folder", chosen).End(); + Print(chosen.empty() ? L"No Windows folder is remembered for " + BaseName(exe) + L"." : L"Windows folder for " + BaseName(exe) + L": " + chosen); + return EXIT_OK; + } if (verb == L"set" || verb == L"get") { if (a.has(L"global")) { if (verb == L"set") { @@ -868,8 +901,12 @@ int Verb(const wstring& verb, const Args& a, Output& o) { if (const RrConfigGame* rg = RrConfigGameFor(m.exe)) // waiting: chosen before the game made its settings folder (-1: added after its first start, 1: the folder is there // now and the next Apply adds it; r2b #1) + { + wstring fileWhy; + const wstring cfgFile = m.rrconfig.present ? m.rrconfig.path : RrConfigFile(g.ctx, *rg, m.exe, &fileWhy); o.j.Key("rr_config").Obj().S("game", rg->name).B("fixed", m.rrconfig.present).N("waiting", RrConfigWaiting(g.ctx, m, p.get("rr_config_fix"))) - .S("file", m.rrconfig.present ? m.rrconfig.path : RrConfigFile(g.ctx, *rg, nullptr)).End(); + .S("file", cfgFile).S("file_why", cfgFile.empty() ? fileWhy : wstring()).End(); + } o.j.Key("settings").Obj(); for (size_t i = 0; i < kSettingCount; ++i) { const SettingDef& d = kSettings[i]; diff --git a/clean/installer/src/app/jpeg_decode_linux.cpp b/clean/installer/src/app/jpeg_decode_linux.cpp new file mode 100644 index 00000000..998a663e --- /dev/null +++ b/clean/installer/src/app/jpeg_decode_linux.cpp @@ -0,0 +1,84 @@ +// SPDX-License-Identifier: MIT +// Linux: JPEG decoding with libjpeg-turbo (see jpeg_decode_linux.h). Written for this project. +#include "app/jpeg_decode_linux.h" + +#include +#include +#include +#include + +#include + +namespace wg::app::lui { + +namespace { + +struct Err { + jpeg_error_mgr base; // first: libjpeg hands back this pointer + jmp_buf jump; +}; + +void OnError(j_common_ptr c) { longjmp(reinterpret_cast(c->err)->jump, 1); } +void Silent(j_common_ptr, int) {} + +} // namespace + +bool LooksLikeJpeg(const char* utf8Path) { + FILE* f = std::fopen(utf8Path, "rb"); + if (!f) return false; + unsigned char m[3] = {}; + const size_t n = std::fread(m, 1, 3, f); + std::fclose(f); + return n == 3 && m[0] == 0xFF && m[1] == 0xD8 && m[2] == 0xFF; +} + +bool DecodeJpegFile(const char* utf8Path, unsigned minW, int& w, int& h, std::vector& bgra) { + FILE* f = std::fopen(utf8Path, "rb"); + if (!f) return false; + jpeg_decompress_struct cin; + Err err; + cin.err = jpeg_std_error(&err.base); + err.base.error_exit = OnError; + err.base.emit_message = Silent; + // Changed between setjmp and a longjmp, so volatile (C 7.13.2.1), and plain malloc storage: nothing with a destructor + // lives across the jump, and nothing in the jump region can throw. + uint8_t* volatile px = nullptr; + volatile size_t size = 0; + volatile bool ok = false; + if (!setjmp(err.jump)) { + jpeg_create_decompress(&cin); + jpeg_stdio_src(&cin, f); + jpeg_read_header(&cin, TRUE); + const bool colour = cin.jpeg_color_space == JCS_YCbCr || cin.jpeg_color_space == JCS_RGB; + if ((cin.jpeg_color_space == JCS_GRAYSCALE || colour) && cin.image_width > 0 && cin.image_height > 0 && + cin.image_width <= 8192 && cin.image_height <= 8192) { + cin.out_color_space = JCS_EXT_BGRA; + unsigned denom = 1; + while (denom < 8 && (cin.image_width + denom * 2 - 1) / (denom * 2) >= minW) denom *= 2; + cin.scale_num = 1; + cin.scale_denom = denom; + jpeg_start_decompress(&cin); + const size_t rowBytes = (size_t)cin.output_width * 4; + size = rowBytes * cin.output_height; + px = static_cast(std::malloc(size)); + if (px) { + while (cin.output_scanline < cin.output_height) { + JSAMPROW row = px + (size_t)cin.output_scanline * rowBytes; + jpeg_read_scanlines(&cin, &row, 1); + } + jpeg_finish_decompress(&cin); + w = (int)cin.output_width; + h = (int)cin.output_height; + ok = true; + } + } + } + jpeg_destroy_decompress(&cin); + std::fclose(f); + // The copy may throw bad_alloc; the decoder and the file are already released, and the holder frees the pixels. + const std::unique_ptr hold(px, &std::free); + if (ok) bgra.assign(hold.get(), hold.get() + size); + return ok; +} + +} // namespace wg::app::lui diff --git a/clean/installer/src/app/jpeg_decode_linux.h b/clean/installer/src/app/jpeg_decode_linux.h new file mode 100644 index 00000000..ee0bb815 --- /dev/null +++ b/clean/installer/src/app/jpeg_decode_linux.h @@ -0,0 +1,18 @@ +// SPDX-License-Identifier: MIT +// Linux: decodes a JPEG file (Steam's hero, header and capsule art) with libjpeg-turbo, where Windows uses WIC. +#pragma once +#include +#include + +namespace wg::app::lui { + +// Reads the JPEG at `utf8Path` into 8-bit BGRA bytes (alpha 255: Cairo's ARGB32 on a little-endian machine, premultiplied +// trivially). libjpeg's own DCT scaling shrinks the image by 2, 4 or 8 while the result stays at least `minW` pixels wide, so +// a big hero is not decoded at full size for a small tile. Fails (false, outputs untouched) on a missing or damaged file, a +// side over 8192 pixels, or a colour model other than grey or YCbCr/RGB (CMYK art does not occur in Steam's cache). +bool DecodeJpegFile(const char* utf8Path, unsigned minW, int& w, int& h, std::vector& bgra); + +// Whether the file starts with the JPEG signature (FF D8 FF); the extension is not trusted. +bool LooksLikeJpeg(const char* utf8Path); + +} // namespace wg::app::lui diff --git a/clean/installer/src/app/launcher_ui.cpp b/clean/installer/src/app/launcher_ui.cpp index 2bc6d662..0c75ab47 100644 --- a/clean/installer/src/app/launcher_ui.cpp +++ b/clean/installer/src/app/launcher_ui.cpp @@ -107,6 +107,7 @@ bool pollingRunning = false; bool rechecking = false; // Check again (a game page's callout) is reading that game's folder on a worker bool rrSetupNext = false; // the next Repair is the RR row's Set up: its verb is "Setting up..." (StartOp) bool openedToUninstall = false; // the window opened by Installed apps' Uninstall, its question not answered yet (Cancel closes it) +bool dataRemoved = false; // Linux: the AppImage uninstall deleted WrongGPU's data: the closing window saves nothing into it (WM_DESTROY) bool replaceAsking = false; // a newer download's window, only for "Update WrongGPU to X?": it saves no list or place (WM_DESTROY) // Update all: the games it left out (name; true: gone since the scan, false: its files couldn't be read, its note said so), // said at its end; and the results of the games an earlier game's elevated worker did with it (by folder, lower case) @@ -204,9 +205,14 @@ bool SavedPlacement(RECT& r, HMONITOR& mon, UINT& mdpi, bool& maxed); // the window that hangs off the screen's edge) int FrameY() { return GetSystemMetricsForDpi(SM_CYFRAME, dpi) + GetSystemMetricsForDpi(SM_CXPADDEDBORDER, dpi); } int FrameX() { return GetSystemMetricsForDpi(SM_CXFRAME, dpi) + GetSystemMetricsForDpi(SM_CXPADDEDBORDER, dpi); } +// The accent the settings name. The Windows accent colour is not offered on the native Linux launcher: a saved "windows" shows green. +static int AccentHere() { + const int a = AccentFromKey(gl.global.accent); + return a == A_WINDOWS && NativeLinux() ? (int)A_GREEN : a; +} // The theme of the launcher's "appearance" setting (system: Windows' app mode), applied to the whole window. void ApplyTheme() { - SetAccent(AccentFromKey(gl.global.accent), WindowsAccentRgb()); + SetAccent(AccentHere(), WindowsAccentRgb()); SetTheme(ThemeIsDark(gl.global.appearance)); if (editBrush) { DeleteObject(editBrush); editBrush = nullptr; } ThemeTitleBar(); @@ -329,7 +335,7 @@ PageData ReadPageData(const GameEntry& e, const Profile& defaults) { ReadAll(Join(e.dir, L"OptiScaler.ini"), oini); d.outside = e.hasRecord ? OutsideEdits(d.saved, wini, oini) : std::vector{}; if (const RrConfigGame* rg = e.hasRecord ? RrConfigGameFor(e.exe) : nullptr) { - d.rrcfg = RrConfigLineState(g.ctx, *rg, &d.rrcfgFile, &d.rrcfgWhy); + d.rrcfg = RrConfigLineState(g.ctx, *rg, e.exe, &d.rrcfgFile, &d.rrcfgWhy); Record m; d.rrcfgFixed = LoadRecord(RecordPath(e.dir), m) && m.rrconfig.present; } @@ -2545,7 +2551,7 @@ LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) { case WM_ENDSESSION: // ending: Windows ends the process without WM_DESTROY, so what a close saves is saved here (the window's place, the // Library's list for the next start) - if (wp) { if (v.live && !v.fixture && !replaceAsking) { SavePlacement(hwnd); SaveLibrarySnapshot(); } return 0; } + if (wp) { if (v.live && !v.fixture && !replaceAsking && !dataRemoved) { SavePlacement(hwnd); SaveLibrarySnapshot(); } return 0; } if (!WritesNow()) BlockShutdown(false); // cancelled: the reason goes (an operation's stays while it writes) return 0; case WM_DPICHANGED: { @@ -3314,7 +3320,7 @@ LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) { case WM_DESTROY: StopRrBackground(); // the helper ends at once (what it compiled stays with the driver) if (editBrush) { DeleteObject(editBrush); editBrush = nullptr; } - if (v.live && !v.fixture && !replaceAsking) { SavePlacement(hwnd); SaveLibrarySnapshot(); } // the list as this session leaves it + if (v.live && !v.fixture && !replaceAsking && !dataRemoved) { SavePlacement(hwnd); SaveLibrarySnapshot(); } // the list as this session leaves it if (v.live) { KillTimer(hwnd, 4); ShutdownBlockReasonDestroy(hwnd); @@ -3331,7 +3337,7 @@ HWND CreateLauncherWindow(bool live) { v.live = live; v.rrBuild = RrPayloadAvailable(g.ctx); // this build has the RR files: the RR rows and sections can show (rr-notes.md) v.rrEdition = true; // WrongGPU's edition of OptiScaler (some games' RR needs it): downloaded (optiedition.h) - SetAccent(AccentFromKey(gl.global.accent), WindowsAccentRgb()); + SetAccent(AccentHere(), WindowsAccentRgb()); SetTheme(ThemeIsDark(gl.global.appearance)); gfx.Init(); WNDCLASSEXW wc{}; wc.cbSize = sizeof(wc); @@ -3466,7 +3472,7 @@ int RunLauncherWindow(bool uninstall) { LoadLibrarySnapshot(); // the last session's list at once (SHIP-BAR 3), while the scan reads the games again StartScan(); } else { - v.first.installOffer = !LauncherInstalled() && !gl.paths.portable; + v.first.installOffer = !LauncherInstalled() && !gl.paths.portable && !NativeLinux(); // (Linux: the AppImage runs where it is; there is nothing to install) v.first.choice = v.first.installOffer ? 1 : 0; // a radio choice has its default: install (Continue says so) StartFirstRun(); } diff --git a/clean/installer/src/app/launcher_window.h b/clean/installer/src/app/launcher_window.h index 4c167a0b..e6f45576 100644 --- a/clean/installer/src/app/launcher_window.h +++ b/clean/installer/src/app/launcher_window.h @@ -85,6 +85,9 @@ void CollectLogsBeforeUninstall(); bool FirstRunPortable(); // ui_words.cpp: the first run's "portable" choice (false: refused, a note said why) void HandOverToInstalled(HANDLE& one, const wstring& installedExe, const wchar_t* why); // ui_words.cpp: a newer download, its question answered bool AnswerReplaceOffer(HANDLE& one, const wstring& installedExe, const wstring& have, const LauncherStartDecision& start); // ui_words.cpp: "Update WrongGPU to X?"; true: Not now, this copy runs (rc5) +void AppImageUninstallAsked(); // ui_appimage.cpp: the native Linux launcher's Settings > Uninstall WrongGPU (wg_core/appimage.h) +bool AppImageUninstallQuestion(wstring& text); // ui_appimage.cpp: the dialog's text for this running copy, as the dialog builds it +wstring AppImageUninstallText(const wstring& file, const wstring& data, bool keepsList = false); // keepsList: the data folder has an ignore-files.txt (it is put back) void RemoveDataAsked(); // ui_words.cpp: a portable copy's Settings > Remove data... (RemoveSharedData) void StartHealth(bool gpu); // the model data, the RR data and the graphics card read again (the status line, Settings) // Clean up / Adopt's question; otherSetup (0.6.1): the files are used by another mod's setup (said, Cancel the default) @@ -162,6 +165,11 @@ bool ApplyRrConfigDueNow(const wstring& dir, const wstring& exe); void RrConfigNeedsClick(const wstring& dir); void ForgetRrConfigDue(const wstring& dir); void RrConfigAction(int id); // the Engine.ini steps' Open folder, Copy, Check again +#ifndef _WIN32 +wstring WindowsFolderCommand(const wstring& gameExe); // Linux: this program's `windows-folder` command for a game that is not a Steam game +void CopyTerminalCommand(const wstring& line); // Linux: a command for the terminal on the clipboard, and the toast that says so +void CopyLaunchOption(const wstring& line); // Linux: the Steam launch option for Proton on the clipboard, and the toast that says so +#endif void ShowRrConfigSteps(const wstring& dir); // "Show me how": the game's page at its Engine.ini steps, the keyboard on Open folder // r3 #5: the toast the launcher shows once when a protected game's Engine.ini line is ready to add (RrConfigReadyToAdd); // empty without one diff --git a/clean/installer/src/app/main.cpp b/clean/installer/src/app/main.cpp index 86c228c6..5de7302f 100644 --- a/clean/installer/src/app/main.cpp +++ b/clean/installer/src/app/main.cpp @@ -67,7 +67,9 @@ #include "wg_core/payload.h" #include "wg_core/record.h" #include "wg_core/rrprep.h" -#include "wg_ui/kit.h" +#ifdef _WIN32 +#include "wg_ui/kit.h" // the wizard's GDI+ widgets: the Linux build has no wizard +#endif #ifdef _MSC_VER #pragma comment(lib, "user32.lib") @@ -219,7 +221,9 @@ int WINAPI wWinMain(HINSTANCE hInst, HINSTANCE, PWSTR, int) { SetDefaultDllDirectories(LOAD_LIBRARY_SEARCH_SYSTEM32); g.ctx.data = &EmbeddedPayload(); g.hinst = hInst; +#ifdef _WIN32 g.kit.hinst = hInst; +#endif CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); int argc = 0; LPWSTR* argv = CommandLineToArgvW(GetCommandLineW(), &argc); // The launcher (build/launcher-design.md): no arguments opens its window, a verb runs the command line; the @@ -303,3 +307,20 @@ int WINAPI wWinMain(HINSTANCE hInst, HINSTANCE, PWSTR, int) { return RunWizard(); } + +#ifndef _WIN32 +// Linux: the same entry as Windows' wWinMain, with the process's arguments as the command line it reads. The old wizard +// (GDI+) is not built here: its route says so. +namespace wg::app { +bool NeedsConsent() { return false; } +int RunWizard() { + LogLine(g.ctx, L"The setup wizard is not available on Linux; use the launcher window or a command-line verb."); + return EXIT_USAGE; +} +} // namespace wg::app + +int main(int argc, char** argv) { + WgSetCommandLine(argc, argv); + return wWinMain(nullptr, nullptr, nullptr, 0); +} +#endif diff --git a/clean/installer/src/app/ui_activate.cpp b/clean/installer/src/app/ui_activate.cpp index 2e3d0e8e..a1c81000 100644 --- a/clean/installer/src/app/ui_activate.cpp +++ b/clean/installer/src/app/ui_activate.cpp @@ -26,6 +26,9 @@ void StartOp(OpRequest r); using namespace win; namespace lui { +#ifndef _WIN32 +wstring ProtonLaunchOption(const wstring& proxy); // ui_game.cpp +#endif void ActivateWidget(int id) { if (id >= ID_DIALOG && id < ID_DIALOG + 100) { const size_t i = (size_t)(id - ID_DIALOG); @@ -312,6 +315,10 @@ void ActivateWidget(int id) { case ID_G_RRCFG0: case ID_G_RRCFG0 + 1: SetSetting(v.edit, "rr_config_fix", id == ID_G_RRCFG0 ? "on" : "off", nullptr); Invalidate(); return; case ID_G_RRCFG_OPEN: case ID_G_RRCFG_COPY: case ID_G_RRCFG_CHECK: case ID_G_RRCFG_FIX: RrConfigAction(id); return; +#ifndef _WIN32 + case ID_G_PROTONOPT_COPY: CopyLaunchOption(ProtonLaunchOption(v.opti.proxy)); return; + case ID_G_WINFOLDER_COPY: if (NativeLinux()) CopyTerminalCommand(WindowsFolderCommand(v.cur.exe)); return; +#endif // "Turn it on in the game": OptiScaler's FPS overlay on (an unsaved change: the capsule's Apply writes it) case ID_G_GUIDEFPS: SetSetting(v.edit, "fps_overlay", "on", nullptr); Invalidate(); return; case ID_G_LOG: MenuCommand(0, M_OPEN_LOG); return; @@ -444,6 +451,7 @@ void ActivateWidget(int id) { return; } case ID_S_SELFUNINSTALL: { + if (NativeLinux()) { AppImageUninstallAsked(); return; } // an AppImage has no installer entry: its file and its data folder (ui_appimage.cpp) if (!v.live || v.busy) return; // it can remove WrongGPU from the games: not while an operation works in one if (!LauncherInstalled()) { v.launcherInstalled = false; Invalidate(); return; } // nothing installed to uninstall (removed meanwhile) // destructive: a question with the mark, as a game's Uninstall (POLISH-AUDIT 19), and no default (Return does not diff --git a/clean/installer/src/app/ui_appimage.cpp b/clean/installer/src/app/ui_appimage.cpp new file mode 100644 index 00000000..b9d1c5cc --- /dev/null +++ b/clean/installer/src/app/ui_appimage.cpp @@ -0,0 +1,110 @@ +// SPDX-License-Identifier: MIT +// WrongGPU launcher window: Settings > Uninstall WrongGPU, in the native Linux launcher (wg_core/appimage.h). An AppImage has no +// installer entry: the one question names the AppImage file and WrongGPU's data folder, says nothing else is touched, and the +// answer deletes those two. Written for this project. +#include "app/launcher_window.h" + +#include +#include + +#include "app/launcher_ui_state.h" +#include "wg_core/appimage.h" +#include "wg_core/convert_ignore.h" + +namespace wg::app::win { + +extern bool dataRemoved; // launcher_ui.cpp + +// The question, with what goes by its path (the player decides on what they can read). Nothing in the games is touched. The +// player's ignore list is put back when the data folder goes (RemoveSharedData), so a folder that has one says so. +wstring AppImageUninstallText(const wstring& fileIn, const wstring& dataIn, bool keepsList) { + const wstring file = ShownPath(fileIn), data = ShownPath(dataIn); + return L"Uninstall WrongGPU?\n\nThis deletes two things and cannot be undone:\n\n" + L"• The program file:\n " + file + L"\n• WrongGPU's data folder (the converted Model M and Ray Reconstruction data, the games' list, " + L"settings and logs):\n " + data + L"\n\n" + (keepsList ? wstring(L"Your ignore-files.txt list is kept. ") : wstring()) + + L"Nothing else is deleted. Your games and their files are not touched."; +} + +// The dialog's text for this running copy (false: it is not a proven AppImage). The folder named and looked into for the ignore list is +// the one the uninstall deletes. +bool AppImageUninstallQuestion(wstring& text) { + wstring file; + if (!OwnAppImage(file, nullptr)) return false; + text = AppImageUninstallText(file, AppDataPath(), lui::IgnoreListThere(AppDataPath())); + return true; +} + +void AppImageUninstallAsked() { + using namespace lui; + if (!v.live || v.busy || !NativeLinux()) return; + wstring file, why; + if (!OwnAppImage(file, &why)) { Inform(L"WrongGPU can't uninstall itself from here\n\n" + why, 2); return; } + // what a game still has is read on a worker first, as the launcher's other uninstall reads it (a game on a share that is offline + // holds each look, never the window) + auto look = std::make_shared(); + if (!WaitForRead(L"", kLookVerb, T_NONE, [look] { *look = LookAtSharedData(g.ctx); })) return; + if (look->anyGame) { Inform(L"Your games still use WrongGPU\n\nUninstall WrongGPU from each game first (its page, More, Uninstall), then uninstall WrongGPU here. Nothing was deleted.", 1); return; } + wstring question; + if (!AppImageUninstallQuestion(question)) return; + if (!Confirm(question, 0, L"Uninstall WrongGPU", L"Cancel", true)) return; + auto kept = std::make_shared(); + auto problem = std::make_shared(); + auto ok = std::make_shared(false); + if (!WaitForRead(L"", L"Uninstalling…", T_NONE, [kept, problem, ok] { *ok = UninstallAppImage(g.ctx, problem.get(), nullptr, kept.get()); })) return; + if (!*ok) { + InformDetails(L"WrongGPU couldn't be uninstalled.\n\nA file in its data folder may be in use, or a game may still have WrongGPU. Close what uses it, then try again.", kIconError, *problem); + return; + } + dataRemoved = true; // the window's close does not write its place and list into the folder that is gone + Inform(L"WrongGPU is uninstalled\n\nThe program file and WrongGPU's data folder are deleted." + + (kept->empty() ? wstring() : L" " + *kept) + L"\n\nThe window closes now.", 0); + if (v.hwnd) DestroyWindow(v.hwnd); +} + +} // namespace wg::app::win + +namespace wg::app::lui { +// What Settings says about the removal: where the program and its data are, or why this copy can't remove itself. +wstring AppImageSettingsWords(bool own, const wstring& file, const wstring& data, const wstring& why, bool keepsList, bool gamesHaveIt) { + if (!own) return L"Uninstall WrongGPU is not available here. " + why; + return L"The file: " + ShownPath(file) + L". Uninstall deletes that file and WrongGPU's data folder (" + ShownPath(data) + L") after you confirm. " + + (keepsList ? wstring(L"Your ignore-files.txt list is kept. ") : wstring()) + L"Nothing else is deleted." + + (gamesHaveIt ? wstring(L" Uninstall WrongGPU from your games first.") : wstring()); +} +// Whether this copy runs from its own proven AppImage (the file and the environment do not change while it runs) +bool RunsFromOwnAppImage(wstring* file, wstring* why, wstring* host) { + static wstring imageFile, imageWhy, imageHost; + static const bool own = OwnAppImage(imageFile, &imageWhy, &imageHost); + if (file) *file = imageFile; + if (why) *why = imageWhy; + if (host) *host = imageHost; + return own; +} +// Only a plain file is promised: the uninstall keeps a link to the list, but the file the link points to goes with the folder +bool IgnoreListThere(const wstring& dataDir) { + const DWORD a = GetFileAttributesW(Join(dataDir, wg::kIgnoreListName).c_str()); + return a != INVALID_FILE_ATTRIBUTES && !(a & FILE_ATTRIBUTE_DIRECTORY) && !(a & FILE_ATTRIBUTE_REPARSE_POINT); +} +// Whether a game still has WrongGPU, as the uninstall asks it (LookAtSharedData: the registered and the managed games), not by the +// loaded Library. In the live window the look runs on a worker (a game on an offline share holds each look, never the painting) and +// the page is drawn again when it is done; Settings shows the last finished answer, refreshed every few seconds. The button looks +// again itself before it asks anything. The dumps and offscreen frames look at once. +bool GamesBlockAppImageUninstall() { + static std::atomic answer{-1}; // -1 not looked yet, 0 no, 1 yes + static std::atomic looking{false}; + static std::atomic at{0}; + if (!v.live || !v.hwnd) return LookAtSharedData(Ctx()).anyGame; + const ULONGLONG now = GetTickCount64(); + if (!looking.load() && (answer.load() < 0 || now - at.load() > 3000)) { + looking = true; + const HWND w = v.hwnd; + std::thread([w] { + answer = LookAtSharedData(Ctx()).anyGame ? 1 : 0; + at = GetTickCount64(); + looking = false; + PostMessageW(w, win::WM_APP_ART, 0, 0); // drawn again (WM_APP_ART only repaints) + }).detach(); + } + return answer.load() == 1; +} +} // namespace wg::app::lui diff --git a/clean/installer/src/app/ui_art.cpp b/clean/installer/src/app/ui_art.cpp index 46485a94..abb58455 100644 --- a/clean/installer/src/app/ui_art.cpp +++ b/clean/installer/src/app/ui_art.cpp @@ -19,7 +19,13 @@ #include "wg_core/detect.h" -#ifdef __MINGW32__ +#ifndef _WIN32 +#include + +#include "app/jpeg_decode_linux.h" +#endif + +#if defined(_WIN32) && defined(__MINGW32__) // llvm-mingw's wincodec.h stops at Fant; the Windows SDK's value of HighQualityCubic (Windows 10 1809 and later) #define WICBitmapInterpolationModeHighQualityCubic ((WICBitmapInterpolationMode)4) #endif @@ -78,6 +84,13 @@ wstring FindArt(const wstring& dir, const wchar_t* name) { return best; } +#ifdef _WIN32 +IWICImagingFactory* MakeWic() { + IWICImagingFactory* wic = nullptr; + CoCreateInstance(CLSID_WICImagingFactory, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&wic)); + return wic; +} + // Decodes a JPEG / PNG to premultiplied BGRA, scaled down to at most maxW pixels wide (high-quality scaler). ImageP Decode(IWICImagingFactory* wic, const wstring& path, UINT maxW) { if (path.empty() || !wic) return nullptr; @@ -106,6 +119,52 @@ ImageP Decode(IWICImagingFactory* wic, const wstring& path, UINT maxW) { if (dec) dec->Release(); return out; } +#else +// Linux: Cairo reads PNG and libjpeg-turbo reads JPEG (Steam's hero, header and capsule art); anything else gives no image and +// the page's own plate shows, as for a game without art. +struct IWICImagingFactory { void Release() {} }; +IWICImagingFactory* MakeWic() { static IWICImagingFactory none; return &none; } + +// Decodes a PNG or JPEG to premultiplied BGRA (Cairo's ARGB32), scaled down to at most maxW pixels wide. +ImageP Decode(IWICImagingFactory* wic, const wstring& path, UINT maxW) { + if (path.empty() || !wic) return nullptr; + const std::string file = FsPath(path).string(); // a Windows-style path spelled for this host + std::vector jpegPx; // the JPEG's pixels: the surface below reads them in place + cairo_surface_t* src; + int jw = 0, jh = 0; + if (LooksLikeJpeg(file.c_str())) { + src = DecodeJpegFile(file.c_str(), maxW, jw, jh, jpegPx) + ? cairo_image_surface_create_for_data(jpegPx.data(), CAIRO_FORMAT_ARGB32, jw, jh, jw * 4) + : cairo_image_surface_create(CAIRO_FORMAT_INVALID, 0, 0); + } else { + src = cairo_image_surface_create_from_png(file.c_str()); + } + if (cairo_surface_status(src) != CAIRO_STATUS_SUCCESS) { cairo_surface_destroy(src); return nullptr; } + const int sw = cairo_image_surface_get_width(src), sh = cairo_image_surface_get_height(src); + ImageP out; + if (sw > 0 && sh > 0 && sw <= 8192 && sh <= 8192) { + const int w = (UINT)sw > maxW ? (int)maxW : sw, h = (UINT)sw > maxW ? std::max(1, (int)((double)sh * maxW / sw)) : sh; + cairo_surface_t* dst = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, w, h); + cairo_t* cr = cairo_create(dst); + if (w != sw) cairo_scale(cr, (double)w / sw, (double)h / sh); + cairo_set_source_surface(cr, src, 0, 0); + cairo_pattern_set_filter(cairo_get_source(cr), CAIRO_FILTER_BEST); + cairo_paint(cr); + cairo_destroy(cr); + cairo_surface_flush(dst); + auto img = std::make_shared(); + img->w = w; img->h = h; + img->px.resize((size_t)w * h * 4); + const int stride = cairo_image_surface_get_stride(dst); + const uint8_t* p = cairo_image_surface_get_data(dst); + for (int y = 0; y < h; ++y) memcpy(&img->px[(size_t)y * w * 4], p + (size_t)y * stride, (size_t)w * 4); + out = img; + cairo_surface_destroy(dst); + } + cairo_surface_destroy(src); + return out; +} +#endif // Keeps the newest `keep` of a map by their last use (a quarter dropped at a time); they are decoded again when drawn again template void Trim(M& m, std::map& used, size_t keep) { @@ -173,8 +232,7 @@ void Load(IWICImagingFactory* wic, const wstring& job, bool trim = true) { void Worker() { CoInitializeEx(nullptr, COINIT_MULTITHREADED); - IWICImagingFactory* wic = nullptr; - CoCreateInstance(CLSID_WICImagingFactory, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&wic)); + IWICImagingFactory* wic = MakeWic(); for (;;) { wstring job; { @@ -397,8 +455,7 @@ void ArtLoadNow(const std::vector& appids) { std::lock_guard l(st.m); if (st.cache.empty()) st.cache = LibraryCache(); } - IWICImagingFactory* wic = nullptr; - CoCreateInstance(CLSID_WICImagingFactory, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&wic)); + IWICImagingFactory* wic = MakeWic(); // every game's art and banner-sized hero, none dropped (a frame's banner is never the tile's art stretched) for (auto& id : appids) if (ValidAppId(id)) { Load(wic, id, false); Load(wic, L"big:" + id, false); } std::lock_guard l(st.m); diff --git a/clean/installer/src/app/ui_checks.cpp b/clean/installer/src/app/ui_checks.cpp index 28773ae2..4092ef1d 100644 --- a/clean/installer/src/app/ui_checks.cpp +++ b/clean/installer/src/app/ui_checks.cpp @@ -31,7 +31,7 @@ void FirstRunChecks(HWND hwnd, const GlobalSettings& gs, const wstring& dll, boo } } postAnyway{hwnd, m}; const WinInfo win = WindowsInfo(); - m->lines.push_back({win.ok ? 0 : 2, L"Windows: " + win.text}); + m->lines.push_back({win.ok ? 0 : 2, win.label + L": " + win.text}); // started inside an app package (MSIX), said in words a player knows: what happens, then what to do if (RunningPackaged()) m->lines.push_back({2, L"Opened from: Another app. Games may not see the files WrongGPU writes while it's opened this way. Open WrongGPU from File Explorer instead."}); @@ -41,14 +41,21 @@ void FirstRunChecks(HWND hwnd, const GlobalSettings& gs, const wstring& dll, boo // release 0.6.0 (owner 2026-11-02): the RX 9060 series is supported but not yet tested on hardware; RR takes about twice // the RX 9070 XT's time there (an estimate), and its 8 GB cards are untested const bool rx9060 = gpu.rdna4 && gpu.name.find(L"9060") != wstring::npos; + if (NativeLinux() && gpu.name.empty()) { // no card: a plain sentence, not "detected: none" + m->lines.push_back({2, L"No graphics card found. WrongGPU's models need an RX\u00a09000-series GPU; games use AMD FSR."}); + } else m->lines.push_back({gpu.rdna4 ? 0 : 2, L"Graphics card detected: " + (gpu.name.empty() ? wstring(L"none") : gpu.name) + (!gpu.rdna4 ? L". WrongGPU's models need an RX\u00a09000-series GPU; games use AMD FSR." : rx9060 ? L". Supported, not yet tested on this card. Ray Reconstruction takes about twice as long as on an RX\u00a09070\u00a0XT." : L"")}); // short words behind the sheet's Show details (how Model M runs is the game page's Runs on); without the card, only // what it means here (the card's line above says what to do) - m->lines.push_back({gpu.rdna4 ? 0 : 1, gpu.rdna4 ? L"Direct3D 12: Ready" : L"Direct3D 12: Not available on this card"}); - if (dump) m->lines.push_back({1, L"HIP runtime: Not checked in this run"}); + // natively on Linux the games reach Direct3D 12 through Proton, and no HIP runtime is looked for (nothing here uses one) + const bool native = NativeLinux(); + m->lines.push_back({gpu.rdna4 ? 0 : 1, native ? (gpu.rdna4 ? L"Direct3D 12 (through Proton): Ready" : L"Direct3D 12 (through Proton): Not available on this card") + : (gpu.rdna4 ? L"Direct3D 12: Ready" : L"Direct3D 12: Not available on this card")}); + if (native) {} + else if (dump) m->lines.push_back({1, L"HIP runtime: Not checked in this run"}); else { // optional: a note, not a problem (the probe's own words go to setup.log) const HipInfo h = CheckHip(g.ctx); if (!h.ok) LogLine(g.ctx, L"first run: " + h.text); diff --git a/clean/installer/src/app/ui_dump.cpp b/clean/installer/src/app/ui_dump.cpp index 60703255..17cee406 100644 --- a/clean/installer/src/app/ui_dump.cpp +++ b/clean/installer/src/app/ui_dump.cpp @@ -140,15 +140,30 @@ int RunLauncherUiDump(const wstring& outFile, const wstring& shotDir, bool noSca j.End(); }; // first run (synchronously: the worker thread's result is waited for with a message loop) - v.first.installOffer = !LauncherInstalled() && !gl.paths.portable; + v.first.installOffer = !LauncherInstalled() && !gl.paths.portable && !NativeLinux(); v.first.choice = v.first.installOffer ? 1 : 0; StartFirstRun(); MSG m; while (firstRunBusy && GetMessageW(&m, nullptr, 0, 0)) { TranslateMessage(&m); DispatchMessageW(&m); } ArtLoadNow([] { std::vector ids; for (auto& e : v.games) ids.push_back(e.appid); return ids; }()); dumpPage("first_run", L"Welcome to WrongGPU", L"first-run.png"); + j.Key("first_run_lines").Arr(); // every check line the sheet has (behind Show details too) + for (auto& l : v.first.lines) j.Str(l.second); + j.End(); + j.B("first_run_install_offer", v.first.installOffer); + if (NativeLinux()) { // the removal's words for a made-up AppImage, with and without the ignore list and a game that has WrongGPU (the tests read them) + const wstring file = L"/home/player/Apps/WrongGPU-0.6.5-x86_64.AppImage", data = L"/home/player/.local/share/WrongGPU"; + j.Key("appimage_words").Arr(); + for (int keeps = 0; keeps < 2; ++keeps) + for (int games = 0; games < 2; ++games) j.Str(lui::AppImageSettingsWords(true, file, data, L"", keeps != 0, games != 0)); + j.End(); + j.Key("appimage_uninstall_text").Arr().Str(AppImageUninstallText(file, data, false)).Str(AppImageUninstallText(file, data, true)).End(); + } wstring firstFocus; // what has the keyboard once the checks are done (Continue) for (auto& h : v.hits) if (h.id == v.focus) firstFocus = h.name; + if (!shotDir.empty() && NativeLinux()) { // the sheet with Show details open (every check line), picture only + v.first.checksOpen = true; RenderFrame(kDefaultW, 760, 1, shot(L"first-run-details.png")); v.first.checksOpen = false; + } v.first.open = false; // as FinishFirstRun leaves it (without saving the settings or the release check) v.page = P_LIBRARY; v.focus = 0; @@ -533,6 +548,18 @@ int RunLauncherUiDump(const wstring& outFile, const wstring& shotDir, bool noSca j.End(); } j.End(); + if (NativeLinux() && !v.games.empty()) { // the card's Copy button as a click runs it: the command it puts on the clipboard, and the toast + ShowEntry(v.games[0], false); + Activate(ID_G_WINFOLDER_COPY); + wstring clip; + if (OpenClipboard(nullptr)) { + if (HANDLE h = GetClipboardData(CF_UNICODETEXT)) { if (const wchar_t* t = (const wchar_t*)GlobalLock(h)) { clip = t; GlobalUnlock(h); } } + CloseClipboard(); + } + j.Key("windows_folder_copy").Obj().S("exe", v.cur.exe).S("clipboard", clip).S("toast", v.toast.text).End(); + wstring question; // the live uninstall dialog's text, built by the function the dialog calls (the ignore list is looked for in the real folder) + if (AppImageUninstallQuestion(question)) j.Key("appimage_question").Str(question); + } // the first game with WrongGPU, scrolled down with an unsaved change (all its OptiScaler settings shown), a frame // every 40 DIPs of the scroll range: the page's controls that take a click and its text fields that show (none under // the pinned plate or the unsaved bar); then Tab to a control hidden under the plate (it is scrolled out from under it) @@ -925,6 +952,7 @@ int RunLauncherUiDump(const wstring& outFile, const wstring& shotDir, bool noSca v.page = P_SETTINGS; v.urlText = gl.global.updateUrl; dumpPage("settings", L"Settings", L"settings.png"); + if (!shotDir.empty()) RenderFrame(kDefaultW, std::max(760.f, v.contentH[P_SETTINGS] + 20), 1, Join(shotDir, L"settings-tall.png")); // the whole page in one picture { // Settings' section index: one Tab stop (the section in view); Down goes to the next entry, Up comes back int stops = 0, stop = 0; RenderFrame(kDefaultW, 760, 1, L""); diff --git a/clean/installer/src/app/ui_frame.cpp b/clean/installer/src/app/ui_frame.cpp index 2d111c19..377b7579 100644 --- a/clean/installer/src/app/ui_frame.cpp +++ b/clean/installer/src/app/ui_frame.cpp @@ -19,6 +19,7 @@ extern RECT normalRect; // its last normal place (screen pixels) extern HICON bigIcon, smallIcon; extern Gfx gfx; +#ifdef _WIN32 static COLORREF TitleRgb(Col c) { return RGB((int)std::lround(c.r * 255), (int)std::lround(c.g * 255), (int)std::lround(c.b * 255)); } // The title bar in the theme's colours (Windows 11: caption, border and text colours; Windows 10: light or dark). void ThemeTitleBar() { @@ -119,6 +120,28 @@ bool SavedPlacement(RECT& r, HMONITOR& mon, UINT& mdpi, bool& maxed) { maxed = mx != 0; return true; } +#else +// Linux: no DWM title bar (the toolbar is the title bar), the icon is the mark drawn at 64 px, and the window's place between runs +// is not kept: the window opens centred at its default size (a Wayland compositor decides where a window goes anyway). +void ThemeTitleBar() {} +void SetWindowIcons() { + if (!v.hwnd || !v.live) return; + Gfx g2; + std::vector bgra; + UINT w = 0, h = 0; + if (!g2.Init() || !g2.BeginOffscreen(24, 24, 64 / 24.f)) return; + g2.Clear(Col{0, 0, 0, 0}); + AppMark(g2, Rc{0, 0, 24, 24}); + g2.EndFrame(); + if (!g2.Pixels(bgra, w, h)) return; + for (size_t i = 0; i + 3 < bgra.size(); i += 4) // icons take straight alpha + if (const uint8_t a = bgra[i + 3]; a && a < 255) + for (int c = 0; c < 3; ++c) bgra[i + c] = (uint8_t)std::min(255, bgra[i + c] * 255 / a); + wgwin::SetIcon(v.hwnd, bgra.data(), (int)w, (int)h); +} +void SavePlacement(HWND) {} +bool SavedPlacement(RECT&, HMONITOR&, UINT&, bool&) { return false; } +#endif // ---- offscreen frames (ui-dump, ui-render) ------------------------------------------------------------------------------------ bool RenderFrame(float w, float h, float scale, const wstring& png) { @@ -141,6 +164,17 @@ bool RenderFrame(float w, float h, float scale, const wstring& png) { if (!gfx.BeginOffscreen((int)w, (int)h, scale)) return false; PaintAll(gfx); gfx.EndFrame(); +#ifndef _WIN32 + // Linux tests read what the frame says and offers, a line per control (id, role, name), next to its PNG + if (FILE* f = fopen((FsPath(png).string() + ".texts").c_str(), "w")) { + for (const Hit& hit : v.hits) { + wstring name = hit.name; + for (wchar_t& c : name) if (c == L'\n' || c == L'\r') c = L' '; + fprintf(f, "%d\t%d\t%s\n", hit.id, (int)hit.role, ToUtf8(name).c_str()); + } + fclose(f); + } +#endif return gfx.SavePng(png); } @@ -148,6 +182,7 @@ bool RenderFrame(float w, float h, float scale, const wstring& png) { // fill, as FieldBox draws it offscreen, during a page's entrance and under the toolbar's edge), in the field's own font // where its typed text starts. The EDIT's cue banner (EM_SETCUEBANNER) ignores WM_CTLCOLOREDIT and draws in a fixed system // grey: 2.2:1 on the dark fill, and the placeholder changed colour each time the native field took over from the painted one. +#ifdef _WIN32 COLORREF Ref(Col c); // launcher_ui.cpp LRESULT EditCueProc(HWND h, UINT m, WPARAM wp, LPARAM lp) { const wstring* cue = nullptr; @@ -179,8 +214,22 @@ LRESULT EditCueProc(HWND h, UINT m, WPARAM wp, LPARAM lp) { if (edits && wasEmpty != (GetWindowTextLengthW(h) == 0)) InvalidateRect(h, nullptr, TRUE); return r; } +#else +// Linux: the text field is painted with the page (ui_gfx_cairo.cpp), which takes its placeholder from the field: set here, in the +// field's own paint message, as the Windows version paints it there. +LRESULT EditCueProc(HWND h, UINT m, WPARAM wp, LPARAM lp) { + if (m == WM_PAINT && !wp) { + const wstring* cue = nullptr; + for (auto* e : {&v.edSearch, &v.edUrl}) if (e->h == h) cue = &e->cue; + for (auto& e : v.edOpti) if (e.h == h) cue = &e.cue; + SendMessageW(h, EM_SETCUEBANNER, FALSE, (LPARAM)(cue ? cue->c_str() : L"")); + } + return DefSubclassProc(h, m, wp, lp); +} +#endif int Px(float dip); // DIPs to the window's pixels (launcher_ui.cpp) +#ifdef _WIN32 // Hover tooltips (v.tips: an icon-only button, a name cut off with an ellipsis): one comctl32 tooltip whose tool is the hit // under the pointer; nothing while a menu, a dialog or the first run is open. HWND tipWnd = nullptr; @@ -286,6 +335,11 @@ void UpdateHoverTip() { SendMessageW(tipWnd, TTM_UPDATETIPTEXTW, 0, (LPARAM)&ti); SendMessageW(tipWnd, TTM_ACTIVATE, want ? TRUE : FALSE, 0); } +#else +// Linux: no tooltips yet (the Hit's words are in v.tips for them). +HWND tipWnd = nullptr; +void UpdateTip() {} +#endif // ---- the frames while something moves, and the smooth scroll (launcher_ui.cpp draws them: WM_PAINT) ------------------------ // The overlay scroll thumb is fading out (it is drawn on every frame until it is gone) @@ -371,6 +425,7 @@ void ScrollNow(float dy) { extern int modalDepth; // launcher_ui.cpp: the nested modal loops open (a note waits for them) void ModalClosed(); void UninstallIfWaiting(); +#ifdef _WIN32 // The file and folder pickers (split from launcher_ui.cpp: source size) bool Browse(int mode, wstring& out) { // 0 exe, 1 folder, 2 model dll, 3 OptiScaler archive, 4 OptiScaler folder, 5 RR model dll if (!v.live) return false; @@ -411,6 +466,10 @@ bool Browse(int mode, wstring& out) { // 0 exe, 1 folder, 2 model dll, 3 OptiSc d->Release(); return ok; } +#else +// Linux: no file picker yet (a desktop portal's is a later step): nothing is chosen. +bool Browse(int, wstring&) { return false; } +#endif } // namespace win } // namespace wg::app diff --git a/clean/installer/src/app/ui_game.cpp b/clean/installer/src/app/ui_game.cpp index 3f2a8369..264afae3 100644 --- a/clean/installer/src/app/ui_game.cpp +++ b/clean/installer/src/app/ui_game.cpp @@ -14,6 +14,7 @@ #include "wg_core/gamerules.h" #include "wg_core/rrconfig.h" +namespace wg::app::win { wstring WindowsFolderCommand(const wstring& gameExe); } // ui_rrconfig.cpp namespace wg::app::lui { // "2026-10-17 19:19" -> "Today at 19:19", "Yesterday at ...", "Oct 14 at 16:26" @@ -1447,6 +1448,32 @@ static float StepCodeRow(Gfx& gx, float x, float y, float w, int n, const wstrin return yy + 14 - y; } +// Linux, a game that is not a Steam game: its Windows folder is not known until the player points at it once (rrconfig.h), so the +// card says how, and shows the command (this program's own path, the game's exe) in a box with Copy, as the Steam launch option is. +static bool AsksWindowsFolder() { return NativeLinux() && v.rrcfgWhy.find(L"not a Steam game") != wstring::npos; } +static wstring RrFolderWords() { + if (!AsksWindowsFolder()) return v.rrcfgWhy + L"."; + return L"It isn't a Steam game, so WrongGPU can't tell where its Proton or Wine folder is. Find the game's Windows user folder, the one that holds " + L"Documents and AppData (usually pfx/drive_c/users/ inside its Proton or Wine folder). Then run this once in a terminal, with the folder in place of . Keep the quotes around it, and write a ' inside the folder's name as '\\'':"; +} +static float WindowsFolderCard(Gfx& gx, float x, float y, float w) { + const wstring title = L"Point WrongGPU at the Windows folder", code = win::WindowsFolderCommand(v.cur.exe); + RowLine(gx, x, y, w, false); + const float bw = ButtonW(gx, L"Copy", 0, 30, B_SECONDARY), tx = x + kCellPad, cw = w - 2 * kCellPad; + TS ts = Ts(13.5f, 600, pal.text); + TS ms = Wrap(12.5f, pal.text, 18); ms.face = F_MONO; + const float mh = gx.TextH(code, cw - 20, ms); + float yy = y + 14; + gx.Text(title, Rc{tx, yy, cw - bw - 12, 22}, ts); + Button(gx, ID_G_WINFOLDER_COPY, x + w - kCellPad, yy - 5, L"Copy", B_SECONDARY, 0, true, 30, 0, true, L"Copy the windows-folder command"); + yy += 30; + gx.FillRound(Rc{tx, yy, cw, mh + 14}, 6, pal.fill); + gx.Text(code, Rc{tx + 10, yy + 7, cw - 20, mh + 2}, ms); + yy += mh + 14; + AddText(Rc{tx, y + 14, cw, yy - y - 14}, title + L": " + code); + return yy + 14 - y; +} + // The file check's "Couldn't read Engine.ini" (RrConfigLineState 3, r3 #8): why, and what lets it be read again (not a fix: // adding the line would fail the same way). Myself (mine): the player's own file, which the game may read fine (UTF-16): only // WrongGPU's check can't read it, and how to check it by hand, never a request to save it another way (r4 #6) @@ -1455,12 +1482,12 @@ static wstring CantReadWhy(bool mine, const RrConfigGame& rg) { const bool utf16 = why.find(L"UTF-16") != wstring::npos, inUse = why.find(L"another program") != wstring::npos; if (mine) return L"WrongGPU's check couldn't read it: " + why + L". " + (inUse ? L"Close the program that has it open, then check again, or c" : L"C") + - L"heck it by hand: open Engine.ini in Notepad and look for the line under [SystemSettings]" + - (rg.readOnly ? L", and in its Properties that Read-only is ticked." : L"."); + L"heck it by hand: open Engine.ini in " + (NativeLinux() ? L"a text editor" : L"Notepad") + L" and look for the line under [SystemSettings]" + + (rg.readOnly ? (NativeLinux() ? L", and in its properties that the file is read-only." : L", and in its Properties that Read-only is ticked.") : L"."); return L"WrongGPU couldn't read it: " + why + L". " + - (utf16 ? L"Open it in Notepad, choose Save as, set Encoding to UTF-8, then check again." + (utf16 ? (NativeLinux() ? L"Open it in a text editor, save it as UTF-8, then check again." : L"Open it in Notepad, choose Save as, set Encoding to UTF-8, then check again.") : inUse ? L"Close the program that has it open, then check again." - : L"Check that it opens in Notepad, then check again."); + : NativeLinux() ? L"Check that it opens in a text editor, then check again." : L"Check that it opens in Notepad, then check again."); } // Borderlands 4 / Hogwarts Legacy (wg_core/rrconfig.h): the Engine.ini line their Ray Reconstruction needs, changeable at any @@ -1510,7 +1537,8 @@ static float RrConfigRows(Gfx& gx, float x, float y, float w, const RrConfigGame // (a protected game waits for the player's click, not for itself: r3 #4) const wstring t = st == 1 ? L"Engine.ini has the line" : st == 2 ? L"Not read-only" : st == 3 ? L"Couldn't read Engine.ini" : ready ? L"Ready to add" : st == 0 ? L"Not in Engine.ini now" - : waits && click ? L"Waiting for the game's first start" : waits ? L"Will be added after you start the game once" : L"Couldn't check"; + : waits && click ? L"Waiting for the game's first start" : waits ? L"Will be added after you start the game once" + : !v.rrcfgWhy.empty() ? L"Can't find the game's Windows folder" : L"Couldn't check"; const wstring d = st == 1 ? (rg.readOnly ? L"The file is read-only, so " + name + L" keeps it." : L"Ray Reconstruction can run in " + name + L".") : st == 3 ? CantReadWhy(false, rg) : st == 2 ? name + L" will remove it at its next start. " + (v.rrcfgFixed ? L"Fix it again" : L"Fix it now") + L" makes the file read-only." @@ -1518,6 +1546,7 @@ static float RrConfigRows(Gfx& gx, float x, float y, float w, const RrConfigGame : st == 0 ? L"Until it is back, the game doesn't use Ray Reconstruction. " + wstring(v.rrcfgFixed ? L"Fix it again" : L"Fix it now") + L" adds it." : waits && click ? name + L" makes its settings folder at its first start. Then click Fix it now here to add the line." + askWhy : waits ? name + L" makes its settings folder at its first start. WrongGPU adds the line the next time the launcher opens or you open this page." + : !v.rrcfgWhy.empty() ? RrFolderWords() // (Linux: the game's Windows folder is not known, and why) : wstring(L"Start the game once, then check again."); const bool fix = st == 0 || st == 2; // "again" only where WrongGPU added the line before (the record has it); the player's own line, or none added yet: now. @@ -1529,6 +1558,7 @@ static float RrConfigRows(Gfx& gx, float x, float y, float w, const RrConfigGame !fix ? L"Check again" : again ? L"Fix it again" : L"Fix it now", fix ? B_GO : B_PLAIN, fix ? en && !Locked() : true, !fix ? L"Check Engine.ini again" : again ? L"Fix Engine.ini again" : L"Fix Engine.ini now"); if (fix && Locked()) { v.tips[ID_G_RRCFG_FIX] = BusyWhy(v.cur); Describe(ID_G_RRCFG_FIX, BusyWhy(v.cur)); } + if (st == -1 && !waits && AsksWindowsFolder()) yy += WindowsFolderCard(gx, x, yy, w); } if (want != "off") return yy - y; // the steps (they stay on the page while the player works through them), then the file as it is now @@ -1536,29 +1566,34 @@ static float RrConfigRows(Gfx& gx, float x, float y, float w, const RrConfigGame // WindowsNoEditor): step 1 names the folder the game makes it in and says to start the game first; Open folder makes // nothing (RrConfigAction) (r2 #7) const bool noFolder = v.rrcfg == -1; - wstring folder = !v.rrcfgFile.empty() ? Parent(v.rrcfgFile) + const bool lin = NativeLinux(); // a native Linux player: file manager, text editor, file permissions (the game itself is Windows', under Proton) + wstring folder = !v.rrcfgFile.empty() ? ShownPath(Parent(v.rrcfgFile)) + : lin ? (rg.documents ? L"Documents/" : L"AppData/Local/") + wstring(rg.folder) + L"/Windows" : (rg.documents ? L"Documents\\" : L"%LOCALAPPDATA%\\") + wstring(rg.folder) + L"\\Windows"; - if (noFolder) folder = Parent(folder); + if (noFolder) folder = Parent(folder); // (Parent splits at either slash) // every step spelled out (r2 #5): Borderlands 4 deletes Engine.ini at each start, so the file and its section are usually // not there; the same steps as the release notes and the CLI's (RrConfigSteps) yy += StepCodeRow(gx, x, yy, w, 1, noFolder ? L"Start the game once, then come back (it makes its settings folder here)" : L"Open the game's settings folder", folder, ID_G_RRCFG_OPEN, L"Open folder", L"Open the settings folder of " + name, true); - yy += StepCodeRow(gx, x, yy, w, 2, L"Create or open Engine.ini there with Notepad", L"", 0, L"", L"", true); + yy += StepCodeRow(gx, x, yy, w, 2, lin ? L"Create or open Engine.ini there with a text editor" : L"Create or open Engine.ini there with Notepad", L"", 0, L"", L"", true); yy += StepCodeRow(gx, x, yy, w, 3, L"If the file has no [SystemSettings] line, add it at the end", L"", 0, L"", L"", true); yy += StepCodeRow(gx, x, yy, w, 4, L"Paste this line under [SystemSettings]", RrConfigLineW(), ID_G_RRCFG_COPY, L"Copy", L"Copy the line", true); yy += StepCodeRow(gx, x, yy, w, 5, L"Save the file", L"", 0, L"", L"", true); if (rg.readOnly) - yy += StepCodeRow(gx, x, yy, w, 6, L"Right-click Engine.ini, choose Properties, tick Read-only and click OK (without it, " + name + + yy += StepCodeRow(gx, x, yy, w, 6, (lin ? L"Make Engine.ini read-only: in your file manager open its properties, then Permissions, and set it to read-only (without it, " + : L"Right-click Engine.ini, choose Properties, tick Read-only and click OK (without it, ") + name + L" deletes the file at its next start)", L"", 0, L"", L"", true); const int st = v.rrcfg; const wstring t = st == 1 ? L"Engine.ini has the line" : st == 3 ? L"Couldn't read Engine.ini" : st == 2 ? L"The line is there, but the file isn't read-only" - : st == -1 ? L"The game's settings folder isn't there yet" + : st == -1 ? (v.rrcfgWhy.empty() ? L"The game's settings folder isn't there yet" : L"Can't find the game's Windows folder") : L"Not in Engine.ini yet"; const wstring d = st == 1 ? L"Ray Reconstruction can run in " + name + L"." : st == 3 ? CantReadWhy(true, rg) : st == 2 ? name + L" deletes the file at its next start. Do step 6, then check again." - : st == -1 ? wstring(L"Start the game once, then come back and check again.") : L"Until it is, the game doesn't use Ray Reconstruction."; + : st == -1 ? (v.rrcfgWhy.empty() ? wstring(L"Start the game once, then come back and check again.") : RrFolderWords()) + : L"Until it is, the game doesn't use Ray Reconstruction."; yy += NeedRow(gx, x, yy, w, false, t, d, st == 1 ? pal.green : st == -1 ? pal.greyDot : pal.amber, pal.text, ID_G_RRCFG_CHECK, L"Check again", B_PLAIN, true, L"Check Engine.ini again"); + if (st == -1 && AsksWindowsFolder()) yy += WindowsFolderCard(gx, x, yy, w); return yy - y; } @@ -1665,7 +1700,7 @@ static float RrSection(Gfx& gx, float x, float y, float w) { // rrprep.h): no Prepare button, which would do nothing there if (RrKernelsInGame(e.exe)) yy += DotRow(gx, x, yy, w, false, - UnderWine() ? L"Prepared by the game at its first start (under Proton its shader caches are its own)" + UnderProton() ? L"Prepared by the game at its first start (under Proton its shader caches are its own)" : L"Prepared by the game at its first start (about a minute after a graphics driver update)", pal.greyDot, pal.text); else if (!bg.empty()) @@ -1692,6 +1727,54 @@ static float RrSection(Gfx& gx, float x, float y, float w) { // OptiScaler with WrongGPU's setup: what it is (version, the name it loads as), what can be set (the FPS overlay, the // editable keys this build has: the menu key first, the rest behind "More OptiScaler settings"), the keys WrongGPU manages // under the list. +#ifndef _WIN32 +// The line Steam's launch options need under Proton for OptiScaler's proxy DLL to load: Wine uses its own dxgi.dll (or winmm.dll, +// version.dll...) unless the override says native first ("n"), then its own ("b"). +wstring ProtonLaunchOption(const wstring& proxy) { + wstring name = Lower(proxy); + if (name.size() > 4 && name.compare(name.size() - 4, 4, L".dll") == 0) name.resize(name.size() - 4); + return L"WINEDLLOVERRIDES=\"" + name + L"=n,b\" %command%"; +} + +// After OptiScaler's list, on Linux: the launch option the game needs in Steam, in a box to read exactly, with Copy, and the steps +// to put it there. WrongGPU does not write Steam's config (it belongs to Steam and its client rewrites it); the player pastes the +// line once. +static float ProtonLaunchNote(Gfx& gx, float x, float y, float w, const wstring& proxy) { + const wstring title = L"Steam launch option", line = ProtonLaunchOption(proxy); + const wstring body = L"Under Proton, Steam needs this line to load OptiScaler's " + proxy + L" instead of Wine's own. WrongGPU can't add it for you: " + L"Steam keeps its own settings. Add it once:"; + const std::vector steps{L"1. In Steam, right-click this game in your library and choose Properties.", + L"2. On the General tab, find the box called Launch Options.", + L"3. Click Copy here, then paste the line into that box (replace what is there; if it already has other options, put them before %command%).", + L"4. Close the window. Then start the game from Steam or from Play here."}; + return GroupList(gx, x, y, w, [&](float top) { + const float bw = ButtonW(gx, L"Copy", 0, 30, B_SECONDARY), tx = x + kCellPad, cw = w - 2 * kCellPad; + const TS hs = Ts(13.5f, 600, pal.text), bs = Wrap(12.5f, pal.text2, 18); + TS ms = Wrap(12.5f, pal.text, 18); ms.face = F_MONO; + float yy = top + 14; + gx.Text(title, Rc{tx, yy, cw - bw - 12, 22}, hs); + Button(gx, ID_G_PROTONOPT_COPY, x + w - kCellPad, yy - 5, L"Copy", B_SECONDARY, 0, true, 30, 0, true, L"Copy the launch option"); + yy += 28; + const float bh = gx.TextH(body, cw, bs), mh = gx.TextH(line, cw - 20, ms); + gx.Text(body, Rc{tx, yy, cw, bh + 2}, bs); + yy += bh + 10; + gx.FillRound(Rc{tx, yy, cw, mh + 14}, 6, pal.fill); + gx.Text(line, Rc{tx + 10, yy + 7, cw - 20, mh + 2}, ms); + yy += mh + 14; + wstring said = title + L". " + body + L" " + line; + for (auto& s : steps) { + yy += 8; + const float sh = gx.TextH(s, cw, bs); + gx.Text(s, Rc{tx, yy, cw, sh + 2}, bs); + yy += sh; + said += L" " + s; + } + AddText(Rc{tx, top + 14, cw, yy - top - 14}, said); + return yy + 14 - top; + }); +} +#endif + static float OptiSection(Gfx& gx, float x, float y, float w) { const GameEntry& e = v.cur; const OptiView& o = v.opti; @@ -1746,6 +1829,9 @@ static float OptiSection(Gfx& gx, float x, float y, float w) { } return yy - top; }); +#ifndef _WIN32 + if (o.have && !o.proxy.empty()) y += 12 + ProtonLaunchNote(gx, x, y + 12, w, o.proxy); +#endif // values OptiScaler's menu (or a hand edit) saved over ours if (!o.outside.empty()) { // in the page's words: "Menu key F1 (WrongGPU's: Insert)" diff --git a/clean/installer/src/app/ui_gfx.cpp b/clean/installer/src/app/ui_gfx.cpp index d1e8354a..ced14be4 100644 --- a/clean/installer/src/app/ui_gfx.cpp +++ b/clean/installer/src/app/ui_gfx.cpp @@ -258,6 +258,20 @@ bool Gfx::SavePng(const wstring& path) { ID2D1SolidColorBrush* Gfx::B(Col c) { brush_->SetColor(DC(c)); return brush_; } void Gfx::SetOffset(float dx, float dy) { ox_ = dx; oy_ = dy; rt->SetTransform(D2D1::Matrix3x2F::Translation(dx, dy)); } +// A turn round (cx, cy) on top of the transform now (the scroll offset): what the Library's busy glyph needs +void Gfx::PushRotate(float cx, float cy, float degrees) { + D2D1_MATRIX_3X2_F old = D2D1::Matrix3x2F::Identity(); + if (rt) { + rt->GetTransform(&old); + rt->SetTransform(D2D1::Matrix3x2F::Rotation(degrees, D2D1::Point2F(cx, cy)) * old); + } + rotations_.push_back(old); +} +void Gfx::PopRotate() { + if (rotations_.empty()) return; + if (rt) rt->SetTransform(rotations_.back()); + rotations_.pop_back(); +} void Gfx::Clear(Col c) { if (!dry) rt->Clear(DC(c)); } void Gfx::Fill(const Rc& r, Col c) { if (!dry) rt->FillRectangle(DR(r), B(c)); } void Gfx::FillRound(const Rc& r, float rad, Col c) { diff --git a/clean/installer/src/app/ui_gfx_cairo.cpp b/clean/installer/src/app/ui_gfx_cairo.cpp new file mode 100644 index 00000000..23b43daa --- /dev/null +++ b/clean/installer/src/app/ui_gfx_cairo.cpp @@ -0,0 +1,1032 @@ +// SPDX-License-Identifier: MIT +// WrongGPU launcher window on Linux: the Gfx class (ui_shell.h) drawn with Cairo, Pango and fontconfig instead of Direct2D, +// DirectWrite and WIC (ui_gfx.cpp), so the pages' drawing code is the same on both systems. Offscreen frames (ui-render, +// ui-dump) go to PNG. A live frame (BeginHwnd) is drawn into a Cairo image surface the size of the window's client area and +// shown with SDL's window surface (EndFrame, through the window layer's Present): the page is drawn by the CPU anyway, so +// a renderer and a texture would add a GPU context, its start-up cost and its driver problems for one copy of the same +// pixels; the window surface works on X11, Wayland, in a VM and under SDL's offscreen driver alike. The window's text fields +// are drawn on top of the page at the end of the frame (DrawEdits). +// Fonts: Selawik (text, display), Noto Sans Math (the symbols Selawik lacks: the arrow, the no-break and en spaces) and Fluent +// System Icons (icons), vendored under assets/fonts and registered with fontconfig in Init; the mono face is the system's +// "monospace". Written for this project. +#include "app/ui_shell.h" +#include "platform/posix/win32_posix_internal.h" + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace wg::app::lui { + +namespace { +constexpr double kPi = 3.14159265358979323846; + +std::string U8(const wstring& w) { // wchar_t is UTF-32 here + std::string o; + o.reserve(w.size()); + for (wchar_t wc : w) { + const uint32_t c = (uint32_t)wc; + if (c < 0x80) o += (char)c; + else if (c < 0x800) { o += (char)(0xC0 | c >> 6); o += (char)(0x80 | (c & 63)); } + else if (c >= 0xD800 && c < 0xE000) o += "\xEF\xBF\xBD"; + else if (c < 0x10000) { o += (char)(0xE0 | c >> 12); o += (char)(0x80 | ((c >> 6) & 63)); o += (char)(0x80 | (c & 63)); } + else if (c < 0x110000) { o += (char)(0xF0 | c >> 18); o += (char)(0x80 | ((c >> 12) & 63)); o += (char)(0x80 | ((c >> 6) & 63)); o += (char)(0x80 | (c & 63)); } + } + return o; +} + +void SetSrc(cairo_t* cr, Col c) { cairo_set_source_rgba(cr, c.r, c.g, c.b, c.a); } + +// A rounded rectangle with a radius per corner. Radii that do not fit are scaled down together (as CSS does); one radius is +// never more than half a side, as Direct2D's rounded rectangle clamps it. +void RoundPath(cairo_t* cr, const Rc& r, float tl, float tr, float br, float bl) { + tl = std::max(0.f, tl); tr = std::max(0.f, tr); br = std::max(0.f, br); bl = std::max(0.f, bl); + float f = 1; + if (tl + tr > 0) f = std::min(f, r.w / (tl + tr)); + if (bl + br > 0) f = std::min(f, r.w / (bl + br)); + if (tl + bl > 0) f = std::min(f, r.h / (tl + bl)); + if (tr + br > 0) f = std::min(f, r.h / (tr + br)); + f = std::max(0.f, f); + tl *= f; tr *= f; br *= f; bl *= f; + cairo_new_path(cr); + cairo_move_to(cr, r.x + tl, r.y); + cairo_line_to(cr, r.r() - tr, r.y); + if (tr > 0) cairo_arc(cr, r.r() - tr, r.y + tr, tr, -kPi / 2, 0); + cairo_line_to(cr, r.r(), r.b() - br); + if (br > 0) cairo_arc(cr, r.r() - br, r.b() - br, br, 0, kPi / 2); + cairo_line_to(cr, r.x + bl, r.b()); + if (bl > 0) cairo_arc(cr, r.x + bl, r.b() - bl, bl, kPi / 2, kPi); + cairo_line_to(cr, r.x, r.y + tl); + if (tl > 0) cairo_arc(cr, r.x + tl, r.y + tl, tl, kPi, kPi * 1.5); + cairo_close_path(cr); +} + +// Three box passes approximate a Gaussian of `sigma` pixels (the usual box widths for a Gaussian); the edge pixel repeats +// past the edge. Premultiplied BGRA, 4 channels of 8 bits, `stride` bytes per row. +void BoxPass(uint8_t* p, int n, int step, int r, std::vector& line) { // one line of n pixels, `step` bytes apart + for (int ch = 0; ch < 4; ++ch) { + const uint8_t* q = p + ch; + line.assign((size_t)n, 0); + const int win = 2 * r + 1; + long sum = 0; + for (int i = -r; i <= r; ++i) sum += q[(size_t)std::clamp(i, 0, n - 1) * step]; + for (int i = 0; i < n; ++i) { + line[(size_t)i] = (int)((sum + win / 2) / win); + sum += q[(size_t)std::min(i + r + 1, n - 1) * step] - q[(size_t)std::max(i - r, 0) * step]; + } + uint8_t* o = p + ch; + for (int i = 0; i < n; ++i) o[(size_t)i * step] = (uint8_t)line[(size_t)i]; + } +} +void BoxBlur(uint8_t* px, int w, int h, int stride, float sigma) { + if (sigma < 0.3f || w < 1 || h < 1) return; + const float ideal = std::sqrt(12 * sigma * sigma / 3 + 1); + int wl = (int)std::floor(ideal); + if (wl % 2 == 0) --wl; + const int wu = wl + 2; + const int m = (int)std::lround((12 * sigma * sigma - 3 * wl * wl - 12 * wl - 9) / (-4.f * wl - 4)); + std::vector line; + for (int pass = 0; pass < 3; ++pass) { + const int r = ((pass < m ? wl : wu) - 1) / 2; + if (r < 1) continue; + for (int y = 0; y < h; ++y) BoxPass(px + (size_t)y * stride, w, 4, r, line); + for (int x = 0; x < w; ++x) BoxPass(px + (size_t)x * 4, h, stride, r, line); + } +} + +bool DirHas(const std::string& d) { return access((d + "/selawik/selawk.ttf").c_str(), R_OK) == 0; } + +// assets/fonts next to the executable (an installed or packaged build), else the build's own define (a development build) +std::string FontDir() { + char exe[4096]; + const ssize_t n = readlink("/proc/self/exe", exe, sizeof exe - 1); + if (n > 0) { + std::string d(exe, (size_t)n); + d.resize(d.rfind('/') == std::string::npos ? 0 : d.rfind('/')); + for (const char* rel : {"/assets/fonts", "/../assets/fonts", "/../share/wronggpu/assets/fonts"}) + if (DirHas(d + rel)) return d + rel; + } +#ifdef WRONGGPU_FONT_DIR + if (DirHas(WRONGGPU_FONT_DIR)) return WRONGGPU_FONT_DIR; +#endif + return {}; +} + +// Segoe Fluent Icons codepoint -> Fluent System Icons codepoint, by the glyph's meaning. Names are the font's own +// (FluentSystemIcons-Regular.json from microsoft/fluentui-system-icons commit 67e6dec1ee956af3ab4c746a2b3bb6a2e5520a44, a +// build input that is not vendored), the _20_regular glyph of each (they all exist at that size) and its _16 / _12 glyphs +// (0: the font has none), which Icon uses for small sizes so the strokes land on whole pixels. +constexpr float kIconScale = 1.35f; +struct IconPair { wchar_t segoe, fluent, f16, f12; const char* name; }; +const IconPair kIcons[] = { + {ic::grid, 0xF462, 0xE6C3, 0, "grid_20"}, + {ic::gear, 0xF6A9, 0xF6A8, 0, "settings_20"}, + {ic::refresh, 0xF13D, 0xE0AA, 0xE0A9, "arrow_clockwise_20"}, + {ic::add, 0xF109, 0xF108, 0xF107, "add_20"}, + {ic::download, 0xF150, 0xF14F, 0, "arrow_download_20"}, + {ic::search, 0xF68F, 0xEA7C, 0xEA7B, "search_20"}, + {ic::back, 0xF2AA, 0xF2A9, 0xF2A8, "chevron_left_20"}, + {ic::play, 0xF605, 0xE990, 0xE98F, "play_20"}, + {ic::more, 0xE824, 0, 0, "more_horizontal_20"}, + {ic::warn, 0xF869, 0xF868, 0xEE3B, "warning_20"}, + {ic::folder, 0xF418, 0xE643, 0, "folder_20"}, + {ic::cube, 0xF335, 0xF334, 0xE42E, "cube_20"}, + {ic::panel, 0xE8B0, 0xE8AF, 0, "panel_left_20"}, + {ic::monitor, 0xF359, 0xF358, 0, "desktop_20"}, + {ic::down, 0xF2A3, 0xF2A2, 0xF2A1, "chevron_down_20"}, + {ic::check, 0xF294, 0xE305, 0xF293, "checkmark_20"}, + {ic::close, 0xF369, 0xF368, 0xF367, "dismiss_20"}, + {ic::info, 0xF4A3, 0xF4A2, 0xE736, "info_20"}, + {ic::doc, 0xF378, 0xE4D7, 0, "document_20"}, + {ic::zip, 0xF435, 0xF434, 0, "folder_zip_20"}, + {ic::wrench, 0xEE86, 0xEE85, 0, "wrench_20"}, + {ic::undo, 0xF199, 0xE126, 0, "arrow_undo_20"}, + {ic::trash, 0xF34C, 0xE47B, 0xEEA5, "delete_20"}, + {ic::broom, 0xF201, 0xF1FE, 0, "broom_20"}, + {ic::upload, 0xF1A4, 0xE131, 0, "arrow_upload_20"}, + {ic::link, 0xF4E4, 0xF4E3, 0xE770, "link_20"}, + {ic::minus, 0xEBD0, 0xEBCF, 0xEBCE, "subtract_20"}, + {ic::shield, 0xF6BE, 0xEAC3, 0xF21F, "shield_20"}, + {ic::question, 0xF63D, 0xF63C, 0xE9ED, "question_circle_20"}, + {ic::chip, 0xE4AC, 0xF0D9, 0, "developer_board_20"}, // the font has no chip glyph + {ic::sync, 0xF190, 0xE110, 0xF18F, "arrow_sync_20"}, + {ic::key, 0xF4B6, 0xE740, 0, "key_20"}, + {ic::playLine, 0xF605, 0xE990, 0xE98F, "play_20"}, + {ic::up, 0xF2B6, 0xF2B5, 0xF2B4, "chevron_up_20"}, + {ic::arrowUp, 0xF19B, 0xF1B4, 0xE12A, "arrow_up_20"}, + {ic::palette, 0xF2F5, 0xE3BC, 0, "color_20"}, + {ic::chevron, 0xF2B0, 0xF2AF, 0xF2AE, "chevron_right_20"}, + {ic::external, 0xF582, 0xF581, 0xF02C5, "open_20"}, + {ic::processor, 0xE4AC, 0xF0D9, 0, "developer_board_20"}, + {0xE921, 0xEBD0, 0xEBCF, 0xEBCE, "subtract_20"}, // caption: minimize (ui_widgets.cpp DrawCaption) + {0xE922, 0xEB75, 0xEB74, 0xEB73, "square_20"}, // maximize + {0xE8BB, 0xF369, 0xF368, 0xF367, "dismiss_20"}, // close + {0xE923, 0xEB96, 0xEB95, 0, "square_multiple_20"}, // restore + {0xE793, 0xE452, 0, 0, "dark_theme_20"}, // Settings > Appearance (ui_settings.cpp kGlyphAppearance) + {0xEB3C, 0xF67C, 0xF67B, 0xF0C46, "ruler_20"}, // Settings > Exact mode (kGlyphExact) +}; +} // namespace + +// ---- the drawing state -------------------------------------------------------------------------------------------------- +struct GfxCairo { + cairo_surface_t* surf = nullptr; + cairo_t* cr = nullptr; + HWND live = nullptr; // the window this live frame is for (null: an offscreen frame) + int pw = 0, ph = 0; // the target's size in pixels + PangoFontMap* map = nullptr; + PangoContext* ctx = nullptr; + std::string fam[4]; + unsigned long long frame = 0; + // what is open: a clip (cairo_save) or a fade (cairo_push_group) + struct Layer { bool fade; float opacity; }; + std::vector layers; + // Made once and kept across frames and targets (a Pango layout belongs to the font context, not to the target): text + // layouts by their text, style and box. Those not used for a while are let go (Gfx::Trim). + struct CachedLayout { + PangoLayout* l = nullptr; + PangoAttrList* base = nullptr; // the layout's attributes without the lead's colour + std::string u8; + float w = 0, h = 0, dx = 0; // logical size; Balance's shift + float dy = 0; // the text's shift down, onto Segoe UI's baseline (SegoeLineBox) + unsigned long long used = 0; + int leadBytes = -1; // TextLead's lead length in bytes (-1: not a lead layout) + Col leadCol{-1, -1, -1, -1}; // the colour set on the lead now + }; + std::map, CachedLayout> layouts; + // the images' surfaces, made once and shared by every target; shadow: ImageContain's blurred drop shadow + struct Bmp { + std::weak_ptr img; + cairo_surface_t* s = nullptr; + unsigned long long used = 0; + cairo_surface_t* shadow = nullptr; + std::tuple shadowKey{0, 0, 0}; + }; + std::map bitmaps; + cairo_surface_t* frozen = nullptr; + unsigned long long frozenKey = 0, frozenUsed = 0; + struct Shadowed { cairo_surface_t* s; unsigned long long used; }; + std::map, Shadowed> shadows; // Shadow's blurred masks by shape and strength + + ~GfxCairo() { + DropTarget(); + for (auto& l : layouts) FreeLayout(l.second); + for (auto& b : bitmaps) FreeBmp(b.second); + for (auto& e : shadows) cairo_surface_destroy(e.second.s); + if (ctx) g_object_unref(ctx); + if (map) g_object_unref(map); + } + static void FreeLayout(CachedLayout& c) { + if (c.l) g_object_unref(c.l); + if (c.base) pango_attr_list_unref(c.base); + c.l = nullptr; c.base = nullptr; + } + static void FreeBmp(Bmp& b) { + if (b.s) cairo_surface_destroy(b.s); + if (b.shadow) cairo_surface_destroy(b.shadow); + b.s = b.shadow = nullptr; + } + void DropTarget() { + // a layer left open (an early return in a page) is closed so the target is not left with a pending group + while (!layers.empty()) PopLayer(); + if (cr) cairo_destroy(cr); + if (surf) cairo_surface_destroy(surf); + cr = nullptr; surf = nullptr; live = nullptr; + if (frozen) cairo_surface_destroy(frozen); + frozen = nullptr; frozenKey = 0; + } + void PopLayer() { + if (layers.empty()) return; + const Layer l = layers.back(); + layers.pop_back(); + if (!cr) return; + if (l.fade) { + cairo_pop_group_to_source(cr); + cairo_paint_with_alpha(cr, l.opacity); + } else { + cairo_restore(cr); + } + } +}; + +Gfx::~Gfx() { delete im_; } + +bool Gfx::Init() { + if (im_) return true; + auto g = std::make_unique(); + FcInit(); + // the vendored fonts join fontconfig's set for this process only (nothing is installed); the font map must be made after + const std::string dir = FontDir(); + if (!dir.empty()) FcConfigAppFontAddDir(nullptr, (const FcChar8*)dir.c_str()); + else fprintf(stderr, "wronggpu: assets/fonts not found; text falls back to the system's fonts\n"); + g->map = pango_cairo_font_map_new(); + g->ctx = pango_font_map_create_context(g->map); + // no hinting and no rounded metrics: a layout measures the same at every scale and a glyph sits where DirectWrite's + // natural layout puts it; grayscale antialiasing (the Windows offscreen frames are grayscale too) + cairo_font_options_t* fo = cairo_font_options_create(); + cairo_font_options_set_antialias(fo, CAIRO_ANTIALIAS_GRAY); + cairo_font_options_set_hint_style(fo, CAIRO_HINT_STYLE_NONE); + cairo_font_options_set_hint_metrics(fo, CAIRO_HINT_METRICS_OFF); + pango_cairo_context_set_font_options(g->ctx, fo); + cairo_font_options_destroy(fo); + pango_cairo_context_set_resolution(g->ctx, 96); + pango_context_set_round_glyph_positions(g->ctx, FALSE); + // Noto Sans Math follows Selawik for the symbols it lacks (the arrow, the no-break and en spaces) before any system font + g->fam[F_TEXT] = g->fam[F_DISPLAY] = "Selawik,Noto Sans Math,sans-serif"; + g->fam[F_MONO] = "monospace"; + g->fam[F_ICON] = "FluentSystemIcons-Regular"; + iconFont = false; + PangoFontFamily** fams = nullptr; + int nf = 0; + pango_font_map_list_families(g->map, &fams, &nf); + for (int i = 0; i < nf; ++i) + if (!strcmp(pango_font_family_get_name(fams[i]), "FluentSystemIcons-Regular")) iconFont = true; + g_free(fams); + im_ = g.release(); + return true; +} + +void Gfx::DropTarget() { rt = false; if (im_) im_->DropTarget(); } + +static void ApplyMatrix(GfxCairo& g, float scale, float ox, float oy) { + cairo_identity_matrix(g.cr); + cairo_scale(g.cr, scale, scale); + cairo_translate(g.cr, ox, oy); +} + +// A live frame: the window's client area in pixels at its DPI. The surface is kept while the size stays (every frame draws the +// whole page, and the scrim's frozen picture stays with it); a new size makes a new one. +bool Gfx::BeginHwnd(HWND hwnd, UINT dpi) { + if (!im_ || !hwnd) return false; + GfxCairo& g = *im_; + RECT rc{}; + if (!GetClientRect(hwnd, &rc) || rc.right < 1 || rc.bottom < 1) { DropTarget(); return false; } + ++g.frame; + Trim(); + if (g.surf && !(g.live == hwnd && g.pw == rc.right && g.ph == rc.bottom)) g.DropTarget(); + if (g.cr) { // a new context: the clips and the matrix of the last frame are gone + while (!g.layers.empty()) g.PopLayer(); + cairo_destroy(g.cr); + g.cr = nullptr; + } + if (!g.surf) { + g.surf = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, rc.right, rc.bottom); + if (cairo_surface_status(g.surf) != CAIRO_STATUS_SUCCESS) { g.DropTarget(); rt = false; return false; } + } + g.cr = cairo_create(g.surf); + g.live = hwnd; + g.pw = rc.right; g.ph = rc.bottom; + offscreen = false; + occluded = false; + scale = std::max(0.5f, dpi / 96.f); + rt = true; + pango_cairo_update_context(g.cr, g.ctx); + ox_ = oy_ = 0; + ApplyMatrix(g, scale, 0, 0); + // the window layer's text fields place the caret by the page's own text measure + wgwin::SetEditMeasure([this](const wstring& t, int px, int upTo) { + TS ts; + ts.size = px / scale; + return TextW(t.substr(0, (size_t)std::max(0, upTo)), ts) * scale; + }); + return true; +} +// The next BeginHwnd sees the new size +void Gfx::Resize(HWND) {} + +// The window's text fields over the finished page: the field's fill, its text (or its placeholder), the selection and the caret +// (the window layer keeps their state: win32_window_edit.cpp). The text is the page's own face and size. +static void DrawEdits(Gfx& gx, GfxCairo& g) { + std::vector views; + wgwin::EditViews(g.live, views); + if (views.empty()) return; + gx.SetOffset(0, 0); // window coordinates: the page's scroll does not move them + const float k = 1.f / gx.scale; + for (const wgwin::EditView& ev : views) { + const Rc box{ev.rc.left * k, ev.rc.top * k, (ev.rc.right - ev.rc.left) * k, (ev.rc.bottom - ev.rc.top) * k}; + if (box.w < 1 || box.h < 1) continue; + TS ts; + ts.size = ev.fontPx * k; ts.color = pal.text; ts.valign = 1; + const Rc tr{box.x + ev.marginL * k, box.y, std::max(1.f, box.w - (ev.marginL + ev.marginR) * k), box.h}; + const float lineH = gx.TextH(L"Ag", 1e5f, ts); + auto x = [&](int i) { return i <= 0 ? 0.f : gx.TextW(ev.text.substr(0, (size_t)i), ts); }; + float sc = ev.scroll * k; // the text moved left so the caret stays in view + const float cx = x(ev.caret), vis = tr.w - 1; + if (cx - sc > vis) sc = cx - vis; + if (cx - sc < 0) sc = cx; + if (x((int)ev.text.size()) <= vis) sc = 0; + wgwin::SetEditScroll(ev.h, (int)std::lround(sc * gx.scale)); + gx.Fill(box, pal.fill); + gx.PushClip(tr); + const float ty = tr.y + (tr.h - lineH) / 2; + if (ev.focused && ev.selStart != ev.selEnd) + gx.Fill(Rc{tr.x - sc + x(ev.selStart), ty, x(ev.selEnd) - x(ev.selStart), lineH}, Col{pal.tint.r, pal.tint.g, pal.tint.b, 0.35f}); + if (ev.text.empty()) { + if (!ev.cue.empty()) { TS c = ts; c.color = pal.text2; gx.Text(ev.cue, tr, c); } + } else { + gx.Text(ev.text, Rc{tr.x - sc, tr.y, 1e5f, tr.h}, ts); + } + if (ev.caretOn && ev.selStart == ev.selEnd) + gx.Fill(Rc{tr.x - sc + cx, ty, std::max(1.f, std::round(gx.scale)) * k, lineH}, pal.text); + gx.PopClip(); + } +} + +bool Gfx::BeginOffscreen(int w, int h, float s) { + if (!im_) return false; + GfxCairo& g = *im_; + ++g.frame; + Trim(); + g.DropTarget(); + offscreen = true; + scale = s; + g.pw = (int)std::lround(w * s); + g.ph = (int)std::lround(h * s); + if (g.pw < 1 || g.ph < 1) return false; + g.surf = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, g.pw, g.ph); // premultiplied BGRA on little-endian, as WIC's + if (cairo_surface_status(g.surf) != CAIRO_STATUS_SUCCESS) { g.DropTarget(); return false; } + g.cr = cairo_create(g.surf); + rt = true; + pango_cairo_update_context(g.cr, g.ctx); + ox_ = oy_ = 0; + ApplyMatrix(g, scale, 0, 0); + return true; +} + +void Gfx::EndFrame() { + if (!im_ || !im_->cr) return; + GfxCairo& g = *im_; + while (!g.layers.empty()) g.PopLayer(); + if (g.live) DrawEdits(*this, g); + cairo_surface_flush(g.surf); + // the scrim's frozen picture this frame did not draw (the dialog closed) is let go + if (g.frozen && g.frozenUsed != g.frame) { cairo_surface_destroy(g.frozen); g.frozen = nullptr; g.frozenKey = 0; } + if (g.live) wgwin::Present(g.live, cairo_image_surface_get_data(g.surf), g.pw, g.ph, cairo_image_surface_get_stride(g.surf)); +} + +bool Gfx::Pixels(std::vector& bgra, UINT& w, UINT& h) { + w = h = 0; + if (!im_ || !im_->surf) return false; + GfxCairo& g = *im_; + while (!g.layers.empty()) g.PopLayer(); + cairo_surface_flush(g.surf); + w = (UINT)g.pw; h = (UINT)g.ph; + bgra.resize((size_t)w * h * 4); + const int stride = cairo_image_surface_get_stride(g.surf); + const uint8_t* src = cairo_image_surface_get_data(g.surf); + for (UINT y = 0; y < h; ++y) memcpy(&bgra[(size_t)y * w * 4], src + (size_t)y * stride, (size_t)w * 4); + return true; +} + +bool Gfx::SavePng(const wstring& path) { + if (!im_ || !im_->surf) return false; + while (!im_->layers.empty()) im_->PopLayer(); + cairo_surface_flush(im_->surf); + std::string file; // the app's paths are Windows-style ("Z:\\home\\...", as Wine has them): the layer's own conversion + if (!wgposix::ToPosix(path.c_str(), file)) return false; + return cairo_surface_write_to_png(im_->surf, file.c_str()) == CAIRO_STATUS_SUCCESS; +} + +// The caches let go of what has not been used for a while, and the surfaces of images the art cache let go +void Gfx::Trim() { + GfxCairo& g = *im_; + for (auto it = g.bitmaps.begin(); it != g.bitmaps.end();) + if (it->second.img.expired()) { GfxCairo::FreeBmp(it->second); it = g.bitmaps.erase(it); } else ++it; + for (auto it = g.shadows.begin(); it != g.shadows.end();) + if (it->second.used + 240 < g.frame) { cairo_surface_destroy(it->second.s); it = g.shadows.erase(it); } else ++it; + if (g.layouts.size() > 3000) { + for (auto it = g.layouts.begin(); it != g.layouts.end();) + if (it->second.used + 240 < g.frame) { GfxCairo::FreeLayout(it->second); it = g.layouts.erase(it); } else ++it; + if (g.layouts.size() > 6000) { for (auto& l : g.layouts) GfxCairo::FreeLayout(l.second); g.layouts.clear(); } + } +} + +// ---- shapes ---------------------------------------------------------------------------------------------------------------- +#define LIVE (!dry && im_ && im_->cr) + +void Gfx::SetOffset(float dx, float dy) { + ox_ = dx; oy_ = dy; + if (im_ && im_->cr) ApplyMatrix(*im_, scale, dx, dy); +} +void Gfx::PushRotate(float cx, float cy, float degrees) { + if (!im_ || !im_->cr) { ++rotationsOpen_; return; } + cairo_save(im_->cr); + cairo_translate(im_->cr, cx, cy); + cairo_rotate(im_->cr, degrees * kPi / 180); // clockwise on a y-down page, as Direct2D's + cairo_translate(im_->cr, -cx, -cy); + ++rotationsOpen_; +} +void Gfx::PopRotate() { + if (rotationsOpen_ <= 0) return; + --rotationsOpen_; + if (im_ && im_->cr) cairo_restore(im_->cr); +} +void Gfx::Clear(Col c) { + if (!LIVE) return; + cairo_save(im_->cr); + cairo_set_operator(im_->cr, CAIRO_OPERATOR_SOURCE); + SetSrc(im_->cr, c); + cairo_paint(im_->cr); + cairo_restore(im_->cr); +} +void Gfx::Fill(const Rc& r, Col c) { + if (!LIVE) return; + cairo_t* cr = im_->cr; + cairo_new_path(cr); + cairo_rectangle(cr, r.x, r.y, r.w, r.h); + SetSrc(cr, c); + cairo_fill(cr); +} +void Gfx::FillRound(const Rc& r, float rad, Col c) { + if (!LIVE) return; + if (rad <= 0) { Fill(r, c); return; } + RoundPath(im_->cr, r, rad, rad, rad, rad); + SetSrc(im_->cr, c); + cairo_fill(im_->cr); +} +void Gfx::FillRound4(const Rc& r, float tl, float tr, float br, float bl, Col c) { + if (!LIVE) return; + RoundPath(im_->cr, r, tl, tr, br, bl); + SetSrc(im_->cr, c); + cairo_fill(im_->cr); +} +void Gfx::StrokeRound(const Rc& r, float rad, Col c, float width) { + if (!LIVE) return; + const Rc s = r.in(width / 2); // the stroke lies inside r + const float q = std::max(0.f, rad - width / 2); + RoundPath(im_->cr, s, q, q, q, q); + SetSrc(im_->cr, c); + cairo_set_line_width(im_->cr, width); + cairo_stroke(im_->cr); +} + +void Gfx::GradStops(const Rc& r, float rad, const std::vector>& stops, float x0, float y0, float x1, float y1, float opacity) { + if (!LIVE || stops.empty()) return; + cairo_t* cr = im_->cr; + const float op = std::max(0.f, std::min(1.f, opacity)); + cairo_pattern_t* p = cairo_pattern_create_linear(r.x + x0 * r.w, r.y + y0 * r.h, r.x + x1 * r.w, r.y + y1 * r.h); + for (auto& s : stops) cairo_pattern_add_color_stop_rgba(p, s.first, s.second.r, s.second.g, s.second.b, s.second.a * op); // opacity scales every stop + if (rad > 0) RoundPath(cr, r, rad, rad, rad, rad); + else { cairo_new_path(cr); cairo_rectangle(cr, r.x, r.y, r.w, r.h); } + cairo_set_source(cr, p); + cairo_fill(cr); + cairo_pattern_destroy(p); +} +void Gfx::Grad(const Rc& r, float rad, Col a, Col b, float x0, float y0, float x1, float y1) { GradStops(r, rad, {{0.f, a}, {1.f, b}}, x0, y0, x1, y1); } + +void Gfx::Line(float x1, float y1, float x2, float y2, Col c, float width) { + if (!LIVE) return; + cairo_t* cr = im_->cr; + cairo_new_path(cr); + cairo_move_to(cr, x1, y1); + cairo_line_to(cr, x2, y2); + SetSrc(cr, c); + cairo_set_line_width(cr, width); + cairo_set_line_cap(cr, CAIRO_LINE_CAP_BUTT); + cairo_stroke(cr); +} +void Gfx::Circle(float cx, float cy, float rad, Col c) { + if (!LIVE) return; + cairo_new_path(im_->cr); + cairo_arc(im_->cr, cx, cy, rad, 0, 2 * kPi); + SetSrc(im_->cr, c); + cairo_fill(im_->cr); +} +void Gfx::Ring(float cx, float cy, float rad, Col c, float width) { + if (!LIVE) return; + cairo_new_path(im_->cr); + cairo_arc(im_->cr, cx, cy, rad, 0, 2 * kPi); + SetSrc(im_->cr, c); + cairo_set_line_width(im_->cr, width); + cairo_stroke(im_->cr); +} + +// A soft shadow as CSS draws one: the rounded shape blurred by a Gaussian of `blur` / 2 standard deviation, at the strength +// the Windows version's stack of fading layers reaches deep inside (0.73 of `alpha`). Layers of that few alpha do not add up +// in 8-bit pixels here (each rounds to nothing), so the shadow is made once as a blurred mask (three box passes) and kept +// by its shape and strength (GfxCairo::shadows); a draw is one paint. `covered` has nothing to save: one paint either way. +void Gfx::Shadow(const Rc& r, float rad, float blur, float alpha, float dy, bool) { + if (!LIVE || alpha <= 0 || blur <= 0 || r.w <= 0 || r.h <= 0) return; + GfxCairo& g = *im_; + const float peak = std::min(0.95f, alpha * 0.73f), sd = blur / 2 * scale; + const int m = (int)std::ceil(sd * 3), tw = (int)std::ceil(r.w * scale), th = (int)std::ceil(r.h * scale); + const std::array key{tw, th, (int)std::lround(rad * scale * 4), (int)std::lround(sd * 10), (int)std::lround(peak * 1000)}; + auto it = g.shadows.find(key); + if (it == g.shadows.end()) { + if (g.shadows.size() >= 64) { for (auto& e : g.shadows) cairo_surface_destroy(e.second.s); g.shadows.clear(); } + cairo_surface_t* t = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, tw + 2 * m, th + 2 * m); + cairo_t* cr = cairo_create(t); + const float rr = rad * scale; + RoundPath(cr, Rc{(float)m, (float)m, r.w * scale, r.h * scale}, rr, rr, rr, rr); + cairo_set_source_rgba(cr, 0, 0, 0, 1); + cairo_fill(cr); + cairo_destroy(cr); + cairo_surface_flush(t); + const int w = tw + 2 * m, h = th + 2 * m, stride = cairo_image_surface_get_stride(t); + uint8_t* px = cairo_image_surface_get_data(t); + BoxBlur(px, w, h, stride, sd); + for (int y = 0; y < h; ++y) + for (int x = 0; x < w; ++x) { uint8_t* q = px + (size_t)y * stride + (size_t)x * 4; q[3] = (uint8_t)std::lround(q[3] * peak); } // black: only alpha + cairo_surface_mark_dirty(t); + it = g.shadows.emplace(key, GfxCairo::Shadowed{t, g.frame}).first; + } + it->second.used = g.frame; + cairo_save(g.cr); + cairo_translate(g.cr, r.x, r.y + dy); + cairo_scale(g.cr, 1 / scale, 1 / scale); + cairo_set_source_surface(g.cr, it->second.s, -m, -m); + cairo_paint(g.cr); + cairo_restore(g.cr); +} + +void Gfx::Glow(float cx, float cy, float rx, float ry, Col c) { + if (!LIVE || rx <= 0 || ry <= 0) return; + cairo_t* cr = im_->cr; + cairo_save(cr); + cairo_translate(cr, cx, cy); + cairo_scale(cr, 1, ry / rx); // an ellipse is a circle in the squeezed space + cairo_pattern_t* p = cairo_pattern_create_radial(0, 0, 0, 0, 0, rx); + cairo_pattern_add_color_stop_rgba(p, 0, c.r, c.g, c.b, c.a); + cairo_pattern_add_color_stop_rgba(p, 0.45, c.r, c.g, c.b, c.a * 0.45f); + cairo_pattern_add_color_stop_rgba(p, 1, c.r, c.g, c.b, 0); + cairo_new_path(cr); + cairo_arc(cr, 0, 0, rx, 0, 2 * kPi); + cairo_set_source(cr, p); + cairo_fill(cr); + cairo_pattern_destroy(p); + cairo_restore(cr); +} + +// ---- clips and layers ------------------------------------------------------------------------------------------------------ +// A clip is a cairo_save; the matrix is kept as it is when it is popped (a SetOffset made inside it must outlive it, and an open +// PushRotate must stay open, as on Windows, where a clip never touches the transform). +static void PopLayerKeepMatrix(GfxCairo& g) { + cairo_matrix_t m; + cairo_get_matrix(g.cr, &m); + g.PopLayer(); + cairo_set_matrix(g.cr, &m); +} +void Gfx::PushClip(const Rc& r) { + if (!LIVE) return; + cairo_save(im_->cr); + cairo_new_path(im_->cr); + cairo_rectangle(im_->cr, r.x, r.y, r.w, r.h); + cairo_clip(im_->cr); + im_->layers.push_back({false, 1}); +} +void Gfx::PopClip() { + if (!LIVE) return; + PopLayerKeepMatrix(*im_); +} +// rad < 0: only the top corners are rounded +void Gfx::PushRoundClip(const Rc& r, float rad) { + if (!LIVE) return; + const float a = std::fabs(rad); + cairo_save(im_->cr); + RoundPath(im_->cr, r, a, a, rad < 0 ? 0 : a, rad < 0 ? 0 : a); + cairo_clip(im_->cr); + im_->layers.push_back({false, 1}); +} +void Gfx::PopRoundClip() { + if (!LIVE) return; + PopLayerKeepMatrix(*im_); +} +// Everything drawn until PopFade goes to a group that is painted back at `opacity` +void Gfx::PushFade(float opacity) { + if (!LIVE) return; + cairo_push_group(im_->cr); + im_->layers.push_back({true, std::min(1.f, std::max(0.f, opacity))}); +} +void Gfx::PopFade() { PopRoundClip(); } + +// ---- text ---------------------------------------------------------------------------------------------------------------------- +namespace { +using CachedLayout = GfxCairo::CachedLayout; +constexpr float kBoldTrack = -0.0075f; // em + +// Wrapped text whose last line is a single word is wrapped again at the widest width that brings a second word down to it +// without adding a line (the Windows version's Balance, line for line); returns how far the narrower layout moves. +float Balance(PangoLayout* l, const std::string& u, float w, float boxH, const TS& s) { + if (!s.wrap || u.find('\n') != std::string::npos) return 0; + const int n = pango_layout_get_line_count(l); + if (n < 2 || n > 6) return 0; + PangoRectangle lr; + pango_layout_get_extents(l, nullptr, &lr); + if (pango_layout_is_ellipsized(l) || lr.height / (float)PANGO_SCALE > boxH + 0.5f) return 0; // cut off: left as it is + auto good = [&]() { + if (pango_layout_get_line_count(l) != n) return false; + for (int i = 0; i + 1 < n; ++i) { + PangoLayoutLine* ln = pango_layout_get_line_readonly(l, i); + const int end = ln->start_index + ln->length; + if (end > 0 && u[(size_t)end - 1] == '-') return false; // no word broken at its hyphen + } + PangoLayoutLine* last = pango_layout_get_line_readonly(l, n - 1); + std::string t = u.substr((size_t)last->start_index, (size_t)last->length); + while (!t.empty() && t.back() == ' ') t.pop_back(); + // two words: a space, or NoWidow's no-break space + return t.find(' ') != std::string::npos || t.find("\xC2\xA0") != std::string::npos; + }; + auto setW = [&](float v) { pango_layout_set_width(l, (int)(v * PANGO_SCALE)); }; + if (good()) return 0; + float lo = w * (1 - 0.5f / n), hi = w; + setW(lo); + if (!good()) { setW(w); return 0; } + for (int i = 0; i < 8; ++i) { // the widest width that is still good + const float mid = (lo + hi) / 2; + setW(mid); + if (good()) lo = mid; else hi = mid; + } + setW(lo); + const float slack = w - lo; + return s.align == 1 ? slack / 2 : s.align == 2 ? slack : 0; +} +} // namespace + +// leadLen < 0: not a lead layout. A layout for its text, style (not its colour: that is set as it is drawn), box and lead. +static CachedLayout MakeLayout(GfxCairo& g, const wstring& t, float w, float h, const TS& s, bool balance, long leadLen, int leadWeight) { + CachedLayout c; + c.u8 = U8(t); + PangoLayout* l = pango_layout_new(g.ctx); + PangoFontDescription* d = pango_font_description_new(); + pango_font_description_set_family(d, g.fam[s.face].c_str()); + pango_font_description_set_weight(d, (PangoWeight)s.weight); + pango_font_description_set_absolute_size(d, s.size * PANGO_SCALE); + pango_layout_set_font_description(l, d); + pango_font_description_free(d); + pango_layout_set_text(l, c.u8.data(), (int)c.u8.size()); + pango_layout_set_width(l, (int)(std::min(std::max(1.f, w), 1e6f) * PANGO_SCALE)); + pango_layout_set_alignment(l, s.align == 1 ? PANGO_ALIGN_CENTER : s.align == 2 ? PANGO_ALIGN_RIGHT : PANGO_ALIGN_LEFT); + pango_layout_set_wrap(l, PANGO_WRAP_WORD_CHAR); + if (!s.wrap) { + pango_layout_set_ellipsize(l, PANGO_ELLIPSIZE_END); // height stays -1: one line a paragraph + } else if (s.trim) { + pango_layout_set_ellipsize(l, PANGO_ELLIPSIZE_END); + pango_layout_set_height(l, (int)(std::min(std::max(1.f, h), 1e6f) * PANGO_SCALE)); // the lines that fit the box + } + c.base = pango_attr_list_new(); + // Selawik's semibold and bold run 1-3% wider than Segoe UI's, so those weights are tightened a little. + auto spacing = [&](int weight) { return (int)std::lround((s.spacing + (weight >= 600 ? kBoldTrack * s.size : 0)) * PANGO_SCALE); }; + if (spacing(s.weight) != 0) pango_attr_list_insert(c.base, pango_attr_letter_spacing_new(spacing(s.weight))); + // Windows lays text out on Segoe UI's line box (ascent 1.079 + descent 0.251 em: a line is 1.33 em, the baseline 1.079 em + // down; a set line height puts the baseline at 0.8 of it); Selawik's is 0.990 + 0.210 em, so the lines are made 1.33 em + // and the text shifted onto Segoe's baseline. The icon font has its own box and is left alone. + const bool segoe = s.face != F_ICON; + const float lineH = s.lineH > 0 ? s.lineH : segoe ? 1.33f * s.size : 0; + if (lineH > 0) pango_attr_list_insert(c.base, pango_attr_line_height_new_absolute((int)std::lround(lineH * PANGO_SCALE))); + if (s.underline) pango_attr_list_insert(c.base, pango_attr_underline_new(PANGO_UNDERLINE_SINGLE)); + if (leadLen >= 0) { + c.leadBytes = (int)U8(t.substr(0, (size_t)leadLen)).size(); + PangoAttribute* wa = pango_attr_weight_new((PangoWeight)leadWeight); + wa->start_index = 0; wa->end_index = (guint)c.leadBytes; + pango_attr_list_insert(c.base, wa); + if (spacing(leadWeight) != spacing(s.weight)) { + PangoAttribute* sp = pango_attr_letter_spacing_new(spacing(leadWeight)); + sp->start_index = 0; sp->end_index = (guint)c.leadBytes; + pango_attr_list_insert(c.base, sp); + } + } + pango_layout_set_attributes(l, c.base); + c.l = l; + if (balance) c.dx = Balance(l, c.u8, w, h, s); + PangoRectangle lr; + pango_layout_get_extents(l, nullptr, &lr); + c.w = lr.width / (float)PANGO_SCALE; + c.h = lr.height / (float)PANGO_SCALE; + if (segoe && s.lineH <= 0) c.dy = (1.079f * s.size) - pango_layout_get_baseline(l) / (float)PANGO_SCALE; + c.used = g.frame; + return c; +} + +using LayoutKey = std::tuple; +static int Q64(float f) { return (int)std::lround(std::min(f, 1e6f) * 64); } +static int StyleFlags(const TS& s, bool balance) { + return (int)s.face | s.align << 3 | s.valign << 5 | (s.wrap ? 1 << 7 : 0) | (s.trim ? 1 << 8 : 0) | (s.underline ? 1 << 9 : 0) | (balance ? 1 << 10 : 0) | s.weight << 12; +} + +// Kept in layouts (Trim lets go of those not used for a while); the key is the Windows version's +static const CachedLayout* Cached(GfxCairo& g, const wstring& t, float w, float h, const TS& s, bool balance) { + const LayoutKey key{t, Q64(w), Q64(h), (int)std::lround(s.size * 100), StyleFlags(s, balance), (int)std::lround(s.spacing * 100), (int)std::lround(s.lineH * 100)}; + auto it = g.layouts.find(key); + if (it != g.layouts.end()) { it->second.used = g.frame; return &it->second; } + CachedLayout c = MakeLayout(g, t, w, h, s, balance, -1, 0); + return &(g.layouts[key] = c); +} + +// Display text (the Display face, text of 20 DIPs or more) is grayscale on Windows's screen; here every frame is grayscale +// already (Init), so Text and TextLead draw the same everywhere. +static void ShowLayout(GfxCairo& g, PangoLayout* l, float x, float y, Col c) { + cairo_move_to(g.cr, x, y); + SetSrc(g.cr, c); + pango_cairo_update_layout(g.cr, l); + pango_cairo_show_layout(g.cr, l); +} +static float VAlign(const CachedLayout& c, const Rc& r, const TS& s) { return s.valign == 1 ? (r.h - c.h) / 2 : s.valign == 2 ? r.h - c.h : 0; } + +float Gfx::Text(const wstring& t, const Rc& r, const TS& s) { + if (t.empty() || !im_) return 0; + const CachedLayout* c = Cached(*im_, t, r.w, std::max(r.h, 1.f), s, true); + if (!dry && im_->cr) ShowLayout(*im_, c->l, r.x + c->dx, r.y + VAlign(*c, r, s) + c->dy, s.color); + return c->h; +} +float Gfx::TextW(const wstring& t, const TS& s) { + if (t.empty() || !im_) return 0; + TS n = s; n.wrap = false; n.align = 0; n.valign = 0; n.trim = false; n.underline = false; n.lineH = 0; + return Cached(*im_, t, 100000, 1000, n, false)->w; +} +float Gfx::TextH(const wstring& t, float width, const TS& s) { + if (t.empty() || !im_) return 0; + TS n = s; n.valign = 0; n.underline = false; + return Cached(*im_, t, width, 100000, n, false)->h; +} +void Gfx::TextEnd(const wstring& t, float width, const TS& s, float& x, float& y) { + x = y = 0; + if (t.empty() || !im_) return; + TS n = s; n.valign = 0; n.align = 0; + const CachedLayout* c = Cached(*im_, t, width, 100000, n, true); // balanced: where Text draws it + size_t i = c->u8.size() - 1; + while (i > 0 && (((unsigned char)c->u8[i]) & 0xC0) == 0x80) --i; // the last character's first byte + PangoRectangle pos; + pango_layout_index_to_pos(c->l, (int)i, &pos); + x = (pos.x + pos.width) / (float)PANGO_SCALE; + y = pos.y / (float)PANGO_SCALE + c->dy; +} + +// Warn once for a glyph the table has nothing for (a new icon constant that was not mapped) +void Gfx::Icon(wchar_t glyph, float cx, float cy, float size, Col c) { + const IconPair* pair = nullptr; + for (const IconPair& p : kIcons) if (p.segoe == glyph) { pair = &p; break; } + if (!pair) { + static std::set warned; + if (warned.insert(glyph).second) fprintf(stderr, "wronggpu: no Fluent System Icons glyph mapped for U+%04X; drawn as nothing\n", (unsigned)glyph); + return; + } + // A Segoe glyph fills its em; a Fluent glyph carries padding in its grid (about 3/4 of the em is ink at 20) and its + // strokes are one grid unit wide. Small sizes take the _12 / _16 glyph drawn at its own grid size (a 1 px stroke); + // larger ones the _20 glyph scaled up to the Segoe glyph's ink size. + wchar_t mapped = pair->fluent; + float em = size * kIconScale; + if (size <= 11.5f && pair->f12) { mapped = pair->f12; em = size * 1.4f; } + else if (size <= 13.5f && pair->f16) { mapped = pair->f16; em = size * 1.3f; } + if (em < 18) { cx = std::floor(cx) + 0.5f; cy = std::floor(cy) + 0.5f; } // a 1 px stroke centred on a pixel row, not between two + TS s; s.face = F_ICON; s.size = em; s.color = c; s.align = 1; s.valign = 1; + Text(wstring(1, mapped), Rc{cx - em, cy - em, em * 2, em * 2}, s); +} + +// The lead's colour is an attribute set as the layout is drawn (a layout outlives its colour, as on Windows: the cache key +// has the lead's length and weight, not its colour). +float Gfx::TextLead(const wstring& t, size_t leadLen, Col leadC, int leadWeight, const Rc& r, const TS& s) { + if (t.empty() || !im_) return 0; + GfxCairo& g = *im_; + const size_t lead = std::min(leadLen, t.size()); + const wstring k = t + L'\x1' + std::to_wstring(lead) + L',' + std::to_wstring(leadWeight); + const LayoutKey key{k, Q64(r.w), Q64(std::max(r.h, 1.f)), (int)std::lround(s.size * 100), StyleFlags(s, true) | 1 << 11, (int)std::lround(s.spacing * 100), (int)std::lround(s.lineH * 100)}; + auto it = g.layouts.find(key); + if (it == g.layouts.end()) it = g.layouts.emplace(key, MakeLayout(g, t, r.w, std::max(r.h, 1.f), s, true, (long)lead, leadWeight)).first; + CachedLayout& c = it->second; + c.used = g.frame; + if (!dry && g.cr) { + if (c.leadCol.r != leadC.r || c.leadCol.g != leadC.g || c.leadCol.b != leadC.b || c.leadCol.a != leadC.a) { + PangoAttrList* al = pango_attr_list_copy(c.base); + auto u16 = [](float f) { return (guint16)std::lround(std::max(0.f, std::min(1.f, f)) * 65535); }; + PangoAttribute* fg = pango_attr_foreground_new(u16(leadC.r), u16(leadC.g), u16(leadC.b)); + PangoAttribute* fa = pango_attr_foreground_alpha_new(u16(leadC.a)); + fg->start_index = fa->start_index = 0; + fg->end_index = fa->end_index = (guint)c.leadBytes; + pango_attr_list_insert(al, fg); + pango_attr_list_insert(al, fa); + pango_layout_set_attributes(c.l, al); + pango_attr_list_unref(al); + c.leadCol = leadC; + } + ShowLayout(g, c.l, r.x + c.dx, r.y + VAlign(c, r, s) + c.dy, s.color); + } + return c.h; +} + +// ---- images -------------------------------------------------------------------------------------------------------------------- +// One surface per image, made once (premultiplied BGRA is cairo's ARGB32 as it is); those not drawn this frame go when many are kept +static GfxCairo::Bmp* Bitmap(GfxCairo& g, const ImageP& img) { + if (!img || img->w <= 0 || img->h <= 0 || img->px.size() < (size_t)img->w * img->h * 4) return nullptr; + auto it = g.bitmaps.find(img.get()); + if (it != g.bitmaps.end()) { + const std::weak_ptr& w = it->second.img; + if (!w.owner_before(img) && !img.owner_before(w)) { it->second.used = g.frame; return &it->second; } + GfxCairo::FreeBmp(it->second); // another image at a gone one's address + g.bitmaps.erase(it); + } + if (g.bitmaps.size() >= 128) + for (auto k = g.bitmaps.begin(); k != g.bitmaps.end();) { + if (k->second.used != g.frame) { GfxCairo::FreeBmp(k->second); k = g.bitmaps.erase(k); } else ++k; + } + GfxCairo::Bmp b; + b.img = img; + b.s = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, img->w, img->h); + if (cairo_surface_status(b.s) != CAIRO_STATUS_SUCCESS) { cairo_surface_destroy(b.s); return nullptr; } + cairo_surface_flush(b.s); + const int stride = cairo_image_surface_get_stride(b.s); + uint8_t* dst = cairo_image_surface_get_data(b.s); + for (int y = 0; y < img->h; ++y) memcpy(dst + (size_t)y * stride, &img->px[(size_t)y * img->w * 4], (size_t)img->w * 4); + cairo_surface_mark_dirty(b.s); + b.used = g.frame; + return &(g.bitmaps[img.get()] = b); +} + +// src (sx, sy, sw, sh) of the surface stretched over dst; extend PAD so an edge pixel does not blend with nothing +static void DrawSurf(cairo_t* cr, cairo_surface_t* s, const Rc& dst, float sx, float sy, float sw, float sh, float opacity, cairo_filter_t filter) { + if (dst.w <= 0 || dst.h <= 0 || sw <= 0 || sh <= 0) return; + cairo_save(cr); + cairo_new_path(cr); + cairo_rectangle(cr, dst.x, dst.y, dst.w, dst.h); + cairo_clip(cr); + cairo_translate(cr, dst.x, dst.y); + cairo_scale(cr, dst.w / sw, dst.h / sh); + cairo_translate(cr, -sx, -sy); + cairo_set_source_surface(cr, s, 0, 0); + cairo_pattern_set_filter(cairo_get_source(cr), filter); + cairo_pattern_set_extend(cairo_get_source(cr), CAIRO_EXTEND_PAD); + cairo_paint_with_alpha(cr, std::max(0.f, std::min(1.f, opacity))); + cairo_restore(cr); +} + +void Gfx::ImageCover(const ImageP& img, const Rc& r, float rad, float focusY, float opacity, bool topOnly) { + if (!LIVE) return; + GfxCairo::Bmp* b = Bitmap(*im_, img); + if (!b) return; + const float k = std::max(r.w / img->w, r.h / img->h); + const float sw = r.w / k, sh = r.h / k; + const float sx = (img->w - sw) / 2, sy = (img->h - sh) * focusY; + if (rad > 0) PushRoundClip(r, topOnly ? -rad : rad); + DrawSurf(im_->cr, b->s, r, sx, sy, sw, sh, opacity, CAIRO_FILTER_BEST); + if (rad > 0) PopRoundClip(); +} + +// The alpha of the image at device size, blurred, in the art-shade colour: ImageContain's drop shadow (CSS drop-shadow). Made +// once per bitmap and size and kept (Bmp::shadow); `m` pixels of margin round it for the blur. +static cairo_surface_t* MakeShadow(GfxCairo::Bmp& b, int tw, int th, int m, float sigma, Col c) { + cairo_surface_t* t = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, tw + 2 * m, th + 2 * m); + cairo_t* cr = cairo_create(t); + cairo_translate(cr, m, m); + cairo_scale(cr, (double)tw / cairo_image_surface_get_width(b.s), (double)th / cairo_image_surface_get_height(b.s)); + cairo_set_source_surface(cr, b.s, 0, 0); + cairo_pattern_set_filter(cairo_get_source(cr), CAIRO_FILTER_BEST); + cairo_paint(cr); + cairo_destroy(cr); + cairo_surface_flush(t); + const int w = cairo_image_surface_get_width(t), h = cairo_image_surface_get_height(t), stride = cairo_image_surface_get_stride(t); + uint8_t* p = cairo_image_surface_get_data(t); + BoxBlur(p, w, h, stride, sigma); + for (int y = 0; y < h; ++y) + for (int x = 0; x < w; ++x) { + uint8_t* q = p + (size_t)y * stride + (size_t)x * 4; + const float a = q[3] / 255.f * 0.75f; // premultiplied: the colour scales with the alpha + q[0] = (uint8_t)std::lround(c.b * a * 255); q[1] = (uint8_t)std::lround(c.g * a * 255); q[2] = (uint8_t)std::lround(c.r * a * 255); q[3] = (uint8_t)std::lround(a * 255); + } + cairo_surface_mark_dirty(t); + return t; +} + +void Gfx::ImageContain(const ImageP& img, const Rc& box, int ax, int ay, float opacity, float shadow) { + if (!LIVE) return; + GfxCairo& g = *im_; + GfxCairo::Bmp* b = Bitmap(g, img); + if (!b) return; + const float k = std::min(box.w / img->w, box.h / img->h); + const float w = img->w * k, h = img->h * k; + const float x = box.x + (box.w - w) * ax / 2, y = box.y + (box.h - h) * ay / 2; + if (shadow > 0 && k > 0) { + const int tw = std::max(1, (int)std::lround(w * scale)), th = std::max(1, (int)std::lround(h * scale)); + const float sd = shadow / 2 * scale; // pixels + const int m = (int)std::ceil(sd * 3), sdq = (int)std::lround(sd * 10); + if (!b->shadow || b->shadowKey != std::make_tuple(tw, th, sdq)) { + if (b->shadow) cairo_surface_destroy(b->shadow); + b->shadow = MakeShadow(*b, tw, th, m, sd, pal.artShade); + b->shadowKey = std::make_tuple(tw, th, sdq); + } + cairo_save(g.cr); + cairo_translate(g.cr, x - m / scale, y + shadow / 4 - m / scale); + cairo_scale(g.cr, 1 / scale, 1 / scale); + cairo_set_source_surface(g.cr, b->shadow, 0, 0); + cairo_paint_with_alpha(g.cr, std::max(0.f, std::min(1.f, opacity))); + cairo_restore(g.cr); + } + DrawSurf(g.cr, b->s, Rc{x, y, w, h}, 0, 0, (float)img->w, (float)img->h, opacity, CAIRO_FILTER_BEST); +} + +void Gfx::ImageNearest(const ImageP& img, const Rc& r, float rad, float opacity) { + if (!LIVE) return; + GfxCairo::Bmp* b = Bitmap(*im_, img); + if (!b) return; + if (rad > 0) PushRoundClip(r, rad); + DrawSurf(im_->cr, b->s, r, 0, 0, (float)img->w, (float)img->h, opacity, CAIRO_FILTER_NEAREST); + if (rad > 0) PopRoundClip(); +} + +// ---- backdrop and the frozen frame ------------------------------------------------------------------------------------------------ +// The target's pixels under r (plus three deviations round it for the blur to sample, the Windows version's margin) copied and +// blurred on the CPU (three box passes, the edge pixel repeated), then drawn back through r's rounded shape at `opacity`. +bool Gfx::Backdrop(const Rc& r, float rad, float blur, float opacity) { + if (dry) return true; + if (!im_ || !im_->cr || !im_->layers.empty() || blur <= 0.05f || opacity <= 0) return false; + GfxCairo& g = *im_; + const float m = blur * 3, wx = r.x + ox_, wy = r.y + oy_; // window DIPs + const int x0 = (int)std::max(0.f, std::floor((wx - m) * scale)), y0 = (int)std::max(0.f, std::floor((wy - m) * scale)); + const int x1 = (int)std::min((float)g.pw, std::ceil((wx + r.w + m) * scale)), y1 = (int)std::min((float)g.ph, std::ceil((wy + r.h + m) * scale)); + if (x1 <= x0 + 1 || y1 <= y0 + 1) return false; + cairo_surface_flush(g.surf); + cairo_surface_t* t = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, x1 - x0, y1 - y0); + if (cairo_surface_status(t) != CAIRO_STATUS_SUCCESS) { cairo_surface_destroy(t); return false; } + const int ss = cairo_image_surface_get_stride(g.surf), ts = cairo_image_surface_get_stride(t); + const uint8_t* src = cairo_image_surface_get_data(g.surf); + uint8_t* dst = cairo_image_surface_get_data(t); + for (int y = y0; y < y1; ++y) memcpy(dst + (size_t)(y - y0) * ts, src + (size_t)y * ss + (size_t)x0 * 4, (size_t)(x1 - x0) * 4); + BoxBlur(dst, x1 - x0, y1 - y0, ts, blur * scale); + cairo_surface_mark_dirty(t); + cairo_save(g.cr); + if (rad > 0) RoundPath(g.cr, r, rad, rad, rad, rad); + else { cairo_new_path(g.cr); cairo_rectangle(g.cr, r.x, r.y, r.w, r.h); } + cairo_clip(g.cr); + cairo_identity_matrix(g.cr); // the copy is in device pixels + cairo_set_source_surface(g.cr, t, x0, y0); + cairo_paint_with_alpha(g.cr, std::min(1.f, opacity)); + cairo_restore(g.cr); + cairo_surface_destroy(t); + return true; +} + +bool Gfx::DrawFrozen(unsigned long long key) { + if (dry) return true; + if (!im_ || !im_->cr || !im_->frozen || im_->frozenKey != key || !im_->layers.empty()) return false; + GfxCairo& g = *im_; + if (cairo_image_surface_get_width(g.frozen) != g.pw || cairo_image_surface_get_height(g.frozen) != g.ph) return false; + g.frozenUsed = g.frame; + cairo_save(g.cr); + cairo_identity_matrix(g.cr); + cairo_set_source_surface(g.cr, g.frozen, 0, 0); + cairo_pattern_set_filter(cairo_get_source(g.cr), CAIRO_FILTER_NEAREST); + cairo_paint(g.cr); + cairo_restore(g.cr); + return true; +} +void Gfx::Freeze(unsigned long long key) { + if (!LIVE || !im_->layers.empty()) return; + GfxCairo& g = *im_; + cairo_surface_flush(g.surf); + if (g.frozen && (cairo_image_surface_get_width(g.frozen) != g.pw || cairo_image_surface_get_height(g.frozen) != g.ph)) { cairo_surface_destroy(g.frozen); g.frozen = nullptr; } + if (!g.frozen) g.frozen = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, g.pw, g.ph); + cairo_t* cr = cairo_create(g.frozen); + cairo_set_operator(cr, CAIRO_OPERATOR_SOURCE); + cairo_set_source_surface(cr, g.surf, 0, 0); + cairo_paint(cr); + cairo_destroy(cr); + g.frozenKey = key; + g.frozenUsed = g.frame; +} + +} // namespace wg::app::lui diff --git a/clean/installer/src/app/ui_library.cpp b/clean/installer/src/app/ui_library.cpp index 3699f349..f2490753 100644 --- a/clean/installer/src/app/ui_library.cpp +++ b/clean/installer/src/app/ui_library.cpp @@ -989,11 +989,9 @@ static void ScanGlyph(Gfx& gx, float cx, float cy) { if (!turns) { gx.Icon(ic::refresh, cx, cy, 13, pal.text3); return; } libMoving = true; const float deg = (float)(NowMs() % 1000) * 0.36f; - D2D1_MATRIX_3X2_F old; - gx.rt->GetTransform(&old); - gx.rt->SetTransform(D2D1::Matrix3x2F::Rotation(deg, D2D1::Point2F(cx, cy)) * old); + gx.PushRotate(cx, cy, deg); gx.Icon(ic::refresh, cx, cy, 13, pal.text2); - gx.rt->SetTransform(old); + gx.PopRotate(); } // The mark over a search with nothing in it: the search glyph on a round fill. Not the blank shelf: blank lockups where diff --git a/clean/installer/src/app/ui_live_hook_linux.cpp b/clean/installer/src/app/ui_live_hook_linux.cpp new file mode 100644 index 00000000..04c26791 --- /dev/null +++ b/clean/installer/src/app/ui_live_hook_linux.cpp @@ -0,0 +1,50 @@ +// SPDX-License-Identifier: MIT +// WrongGPU launcher window on Linux, test builds only (WRONGGPU_TESTING): what the window layer's scripted input +// (WRONGGPU_UI_SCRIPT, win32_window_sdl.cpp) can ask of the app. `shot FILE` saves the live frame as it was last drawn (the page +// and its text fields) as a PNG; `dump FILE` writes the window's state and widgets as JSON, so a test can check that a click, a +// scroll and typing changed the page. A release build has neither: it never reads a test variable. +#ifdef WRONGGPU_TESTING +#include "app/launcher_window.h" + +#include "wg_core/json_writer.h" + +namespace wg::app { +using namespace wg::app::lui; +namespace win { +void DumpHits(Json& j); // ui_dump.cpp +extern Gfx gfx; // launcher_ui.cpp + +namespace { +bool LiveHook(const std::string& line) { + const size_t sp = line.find(' '); + const std::string cmd = line.substr(0, sp); + const wstring file = sp == std::string::npos ? wstring() : FromUtf8(line.substr(sp + 1)); + if (file.empty()) return false; + if (cmd == "until") { // until games N: the scan has listed N games + int n = 0; + return swscanf(file.c_str(), L"games %d", &n) == 1 && !v.scanning && (int)v.games.size() >= n; + } + if (cmd == "clickname") { // the middle of the first shown widget whose name starts with this + for (const auto& h : v.hits) + if (h.shown && h.name.rfind(file, 0) == 0) { wgwin::ScriptClick(h.r.cx(), h.r.cy()); return true; } + fprintf(stderr, "wronggpu: no widget named %s\n", line.c_str()); + return false; + } + if (cmd == "shot") return gfx.SavePng(file); + Json j; + j.Obj().N("page", (long long)v.page).S("page_name", v.page == P_LIBRARY ? L"library" : v.page == P_GAME ? L"game" : L"settings") + .N("scroll", (long long)std::lround(v.scroll[v.page])).N("content_h", (long long)std::lround(v.contentH[v.page])) + .S("search", v.search).S("url", v.urlText).N("focus", v.focus).B("dialog_open", v.dialog.open).S("dialog_title", v.dialog.title).S("dialog_body", v.dialog.body).B("menu_open", v.menu.open) + .B("first_run_open", v.first.open).N("games", (long long)v.games.size()).N("w", (long long)std::lround(v.W)).N("h", (long long)std::lround(v.H)); + j.Key("controls"); + DumpHits(j); + j.End(); + const string s = j.str() + "\n"; + try { WriteFileAtomic(file, s.data(), s.size()); } catch (const SetupError&) { return false; } + return true; +} +[[maybe_unused]] const bool kRegistered = (wgwin::SetScriptHook(LiveHook), true); +} // namespace +} // namespace win +} // namespace wg::app +#endif diff --git a/clean/installer/src/app/ui_render.cpp b/clean/installer/src/app/ui_render.cpp index 4c1630ba..c5283b1c 100644 --- a/clean/installer/src/app/ui_render.cpp +++ b/clean/installer/src/app/ui_render.cpp @@ -702,6 +702,17 @@ int RunLauncherUiRender(const wstring& outDir, const wstring& fixtureFile, int w } // Fix it for me before the game's first start (r2b #1): nothing written, the card says it waits for the game's settings // folder; the choice made on the page while it isn't there; the question's result toast + // Linux: the game's Windows folder is not known (rrconfig.h): Steam has made no Proton folder yet, or the game is not from + // Steam and the player has not pointed at its Windows folder; the card says which, in the core's words + frame(L"game-rrconfig-nofolder-steam", [&] { + bl4("on", -1); v.rrcfgFixed = false; v.rrcfgFile.clear(); + v.rrcfgWhy = L"Steam has not made this game's Proton folder yet. Start the game once from Steam, then try again"; cardView(); + }); + frame(L"game-rrconfig-nofolder-other", [&] { + bl4("on", -1); v.rrcfgFixed = false; v.rrcfgFile.clear(); + v.rrcfgWhy = L"WrongGPU cannot find this game's Windows folder, because it is not a Steam game. Point it at the game's Windows user folder once " + L"(the folder with Documents and AppData in it, inside the game's Wine prefix). Run: WrongGPU windows-folder \"\" \"\""; cardView(); + }); frame(L"game-rrconfig-pending", [&] { bl4("on", -1); v.rrcfgFixed = false; cardView(); }); frame(L"game-rrconfig-pending-choose", [&] { bl4("ask", -1); SetSetting(v.edit, "rr_config_fix", "on", nullptr); cardView(); }); frame(L"game-rrconfig-pending-toast", [&] { @@ -1106,6 +1117,13 @@ int RunLauncherUiRender(const wstring& outDir, const wstring& fixtureFile, int w v.dialog.buttons = {{L"Cancel", 0, false, false}, {L"Remove data", 1, true, true}}; // as Confirm(..., danger) builds them v.focus = 0; v.focusVisible = false; }); + frame(L"dialog-uninstall-appimage", [&] { // the native Linux launcher's Settings > Uninstall WrongGPU: its file and its data folder + v.page = P_SETTINGS; v.scroll[P_SETTINGS] = v.target[P_SETTINGS] = 5000; + v.dialog.open = true; v.dialog.icon = 0; + SplitDialogText(AppImageUninstallText(L"/home/player/Applications/WrongGPU-0.6.5-x86_64.AppImage", L"/home/player/.local/share/WrongGPU", NativeLinux()), v.dialog.title, v.dialog.body); + v.dialog.buttons = {{L"Cancel", 0, false, false}, {L"Uninstall WrongGPU", 1, true, true}}; // as Confirm(..., danger) builds them + v.focus = 0; v.focusVisible = false; + }); frame(L"dialog-update", [&] { // a newer release (the opt-in check): Not now, or its page in the browser v.page = P_LIBRARY; v.dialog.open = true; v.dialog.icon = 0; diff --git a/clean/installer/src/app/ui_rrconfig.cpp b/clean/installer/src/app/ui_rrconfig.cpp index e77e2ce9..5ec0d755 100644 --- a/clean/installer/src/app/ui_rrconfig.cpp +++ b/clean/installer/src/app/ui_rrconfig.cpp @@ -23,6 +23,7 @@ #include +#include "wg_core/appimage.h" #include "wg_core/rrconfig.h" namespace wg::app { @@ -218,7 +219,7 @@ wstring RrConfigQuestionText(const wstring& dir, const wstring& exe) { bool first = false; if (prot) { if (IEq(v.cur.dir, dir) && v.rrcfg != -2) first = v.rrcfg == -1; - else if (!v.fixture) { bool known = true; try { RrConfigFile(g.ctx, *rg, nullptr, &known); } catch (...) {} first = !known; } + else if (!v.fixture) { bool known = true; try { RrConfigFile(g.ctx, *rg, exe, nullptr, &known); } catch (...) {} first = !known; } } return RrConfigNotice(*rg, prot, first); } @@ -240,13 +241,41 @@ void AskRrConfigLater(const wstring& dir, const wstring& exe, const Profile& sav SetTimer(v.hwnd, kAskTimer, 400, Tick); } +// A word for a shell: in single quotes, a quote inside it as '\'' (nothing in a path is then read as a command) +static wstring ShellQuote(const wstring& s) { + wstring q = L"'"; + for (wchar_t c : s) q += c == L'\'' ? wstring(L"'\\''") : wstring(1, c); + return q + L"'"; +} +// A core path in the spelling a shell takes (Z:\home\x -> /home/x). The real Linux name is kept: no '\' of it is turned into a '/'. +static wstring ShellSpelling(const wstring& p) { return NativeLinux() ? FromUtf8(FsPath(p).string()) : p; } +// The command a player runs once for a game that is not a Steam game (Heroic, Lutris, Bottles): this launcher's own file (the +// AppImage when the same proof the uninstall asks for says it is the one running, else the running program), the game's exe, and +// their Windows folder to fill in (in single quotes: an apostrophe inside it is written as '\'' , the card says so). +wstring WindowsFolderCommand(const wstring& gameExe) { + wstring host; + const string self = NativeLinux() ? HostSelfPath() : string(); + const wstring image = lui::RunsFromOwnAppImage(nullptr, nullptr, &host) ? host : !self.empty() ? FromUtf8(self) : ShellSpelling(SelfPath()); + return ShellQuote(image) + L" windows-folder " + ShellQuote(ShellSpelling(gameExe)) + L" ''"; +} +void CopyTerminalCommand(const wstring& line) { + ShowToast(CopyToClipboard(line) ? L"The command is on the clipboard. Paste it into a terminal, and put your folder where it says , inside the quotes." + : L"The command couldn't be put on the clipboard. Type it as the page shows it.", 0); +} // The game page's "Engine.ini setting" steps: Open folder (never made here: the game makes it at its first start), Copy (the // line on the clipboard), Check again (the file read again; a small file in the player's profile, read on a click). +#ifndef _WIN32 +void CopyLaunchOption(const wstring& line) { + ShowToast(CopyToClipboard(line) ? L"The launch option is on the clipboard. In Steam, paste it under the game's Properties, Launch options." + : L"The launch option couldn't be put on the clipboard. Type it as the page shows it.", 0); +} +#endif + void RrConfigAction(int id) { const RrConfigGame* rg = RrConfigGameFor(v.cur.exe); if (!rg) return; wstring file = v.rrcfgFile; - if (file.empty()) { try { file = RrConfigFile(g.ctx, *rg, nullptr); } catch (...) {} } + if (file.empty()) { try { file = RrConfigFile(g.ctx, *rg, v.cur.exe, nullptr); } catch (...) {} } if (id == ID_G_RRCFG_OPEN) { // never made here: before the game's first start the sub-folder is a guess (Hogwarts Legacy uses WindowsNoEditor, the // guess is Windows), and a file made in the wrong one would be edited for nothing (UI review r2 #7) @@ -278,7 +307,7 @@ void RrConfigAction(int id) { if (id == ID_G_RRCFG_CHECK) { int state = -1; wstring why; - try { state = RrConfigLineState(g.ctx, *rg, &file, &why); } catch (...) {} + try { state = RrConfigLineState(g.ctx, *rg, v.cur.exe, &file, &why); } catch (...) {} v.rrcfg = state; v.rrcfgFile = file; v.rrcfgWhy = why; @@ -288,7 +317,7 @@ void RrConfigAction(int id) { const bool click = waiting && (v.cur.rrConfigProtected || !v.cur.rrInstalled); ShowToast(state == 1 ? L"Engine.ini has the line. Ray Reconstruction can run in " + wstring(rg->name) + L"." : state == 3 ? (v.saved.get("rr_config_fix") == "off" // Myself: the player's own file, which the game may read fine (r4 #6) - ? L"WrongGPU's check couldn't read Engine.ini: " + why + L". Check it by hand in Notepad." + ? L"WrongGPU's check couldn't read Engine.ini: " + why + (NativeLinux() ? L". Check it by hand in a text editor." : L". Check it by hand in Notepad.") : L"Engine.ini couldn't be read: " + why + L".") // r3 #8 : state == 2 ? L"Engine.ini has the line, but it isn't read-only yet." : state == 0 ? (click ? L"The game's settings folder is there now. Click Fix it now to add the line." diff --git a/clean/installer/src/app/ui_settings.cpp b/clean/installer/src/app/ui_settings.cpp index 1bb6a219..0ee3031e 100644 --- a/clean/installer/src/app/ui_settings.cpp +++ b/clean/installer/src/app/ui_settings.cpp @@ -11,6 +11,7 @@ // eases to a new one instead of jumping. Written for this project. #include "app/ui_shell.h" +#include "wg_core/appimage.h" #include "wg_core/model.h" #include "wg_core/optiscaler.h" #include "wg_core/rr.h" @@ -253,7 +254,9 @@ wstring OptiNameVersion(const wstring& path) { constexpr float kSwatch = 22, kSwatchGap = 10; float AccentRow(Gfx& gx, float x, float y, float w, bool border) { const int sel = CurrentAccent(); - const float sw = A_COUNT * kSwatch + (A_COUNT - 1) * kSwatchGap; + // the Windows accent colour has no meaning on the native Linux launcher: six swatches there (a render's fixture keeps all seven) + const int count = NativeLinux() && !v.fixture ? (int)A_WINDOWS : (int)A_COUNT; + const float sw = count * kSwatch + (count - 1) * kSwatchGap; const float h = SettingRow(gx, x, y, w, border, ic::palette, L"Accent color", Status{}, sel == A_WINDOWS ? L"Follows your Windows accent color." : L"Play, switches and links. Green always means WrongGPU is working; red means something needs you.", @@ -261,7 +264,7 @@ float AccentRow(Gfx& gx, float x, float y, float w, bool border) { const float cy = std::round(y + h / 2); float sx = x + w - kCellPad - sw; const unsigned win = WindowsAccentRgb(); - for (int i = 0; i < A_COUNT; ++i, sx += kSwatch + kSwatchGap) { + for (int i = 0; i < count; ++i, sx += kSwatch + kSwatchGap) { const int id = ID_S_ACCENT0 + i; const Rc r{sx, cy - kSwatch / 2, kSwatch, kSwatch}; const float hl = Down(id) ? -0.08f : Hot(id) ? 0.1f : 0.f; @@ -375,8 +378,10 @@ void PaintSettings(Gfx& gx, const Rc& area) { TS as = Ts(12, 400, pal.text2); as.lineH = 18; const float ay = iy + 2 + 3 * 34 - 2 + 20; gx.Text(L"WrongGPU " + wstring(Ctx().data->version), Rc{x0 + 12, ay, 168, 18}, as); - gx.Text(installed ? L"Installed for this user" : portable ? L"Portable" : L"Not installed", Rc{x0 + 12, ay + 18, 168, 18}, as); - AddText(Rc{x0 + 12, ay, 168, 36}, L"WrongGPU " + wstring(Ctx().data->version) + L", " + (installed ? L"installed for this user" : portable ? L"portable" : L"not installed")); + // natively in an AppImage there is nothing to install: "Not installed" is a Windows idea (Settings' Launcher row says the same) + const bool inImage = NativeLinux() && !v.fixture && RunsInsideAnAppImage(); + gx.Text(inImage ? L"AppImage" : installed ? L"Installed for this user" : portable ? L"Portable" : L"Not installed", Rc{x0 + 12, ay + 18, 168, 18}, as); + AddText(Rc{x0 + 12, ay, 168, 36}, L"WrongGPU " + wstring(Ctx().data->version) + L", " + (inImage ? L"AppImage" : installed ? L"installed for this user" : portable ? L"portable" : L"not installed")); } int sec = 0; @@ -497,8 +502,9 @@ void PaintSettings(Gfx& gx, const Rc& area) { [&](float ry, bool b) { return SettingRow(gx, lx, ry, lw, b, ic::processor, L"HIP runtime", hip.empty() ? Status{2, L"Not found", L""} : Status{0, L"Found", hipWords.empty() ? L"" : hipWords + L"."}, - hip.empty() ? L"Optional. Model M runs on Direct3D\u00a012 without it, and no game setting uses it." - : L"Not used in games: Model M runs on Direct3D\u00a012.", + hip.empty() ? (NativeLinux() ? L"Optional. Model M runs through Proton's Direct3D\u00a012 without it, and no game setting uses it." + : L"Optional. Model M runs on Direct3D\u00a012 without it, and no game setting uses it.") + : (NativeLinux() ? L"Not used in games: Model M runs through Proton's Direct3D\u00a012." : L"Not used in games: Model M runs on Direct3D\u00a012."), {}, 0, -1, {}, 0, hipPath ? ID_S_HIPTEXT : 0, hipPath ? L"HIP runtime file: " + hip : L""); }); section(modelRows); @@ -529,10 +535,15 @@ void PaintSettings(Gfx& gx, const Rc& area) { // from that project's release page (optiedition.h); the player's own download only when that download doesn't work const wstring use = L"Only when the WrongGPU edition can't be downloaded: " + (ver.empty() ? what : L"OptiScaler " + ver + L" from " + what) + L"."; + // Linux: nothing is downloaded (DownloadsAvailable): the player's own OptiScaler download is the way in, said as it is + const bool off = !DownloadsAvailable() && !v.fixture; return SettingRow(gx, lx, ry, lw, b, ic::download, L"OptiScaler", - chosen ? Status{0, L"WrongGPU edition", use} : Status{0, L"WrongGPU edition", L""}, - L"Installs use the WrongGPU edition of OptiScaler. OptiScaler is its own project (GPL); the launcher downloads it from " - L"github.com/phantoslayer21/OptiScaler. If that download doesn't work, you can choose your own OptiScaler download.", + off ? Status{chosen ? 0 : 2, chosen ? L"Your download" : L"Needs your download", chosen ? L"OptiScaler download in use: " + (ver.empty() ? what : L"OptiScaler " + ver + L" from " + what) + L"." : L""} + : chosen ? Status{0, L"WrongGPU edition", use} : Status{0, L"WrongGPU edition", L""}, + off ? L"Downloads are off on Linux for now, so WrongGPU can't fetch its edition of OptiScaler. Download OptiScaler yourself " + L"(github.com/phantoslayer21/OptiScaler) and choose the file or the folder it is in." + : wstring(L"Installs use the WrongGPU edition of OptiScaler. OptiScaler is its own project (GPL); the launcher downloads it from " + L"github.com/phantoslayer21/OptiScaler. If that download doesn't work, you can choose your own OptiScaler download."), {{ID_S_OPTIFILE, L"Choose file\u2026"}, {ID_S_OPTIDIR, L"Choose folder\u2026"}}, 0, -1, {}, 0, chosen ? ID_S_OPTITEXT : 0, chosen ? L"OptiScaler download: " + s.optiPackage : L""); }, @@ -591,14 +602,31 @@ void PaintSettings(Gfx& gx, const Rc& area) { if (portable && !installed) instActs.insert(instActs.begin(), Act{ID_S_REMOVEDATA, looking ? L"Preparing\u2026" : removing ? L"Removing\u2026" : L"Remove data\u2026", false, !v.busy, L"Remove WrongGPU's data from this PC"}); + // the native Linux launcher (a render's fixture keeps the Windows rows): an AppImage has no install and no Installed apps entry; its + // one way out is "Uninstall WrongGPU", which deletes the AppImage file and WrongGPU's data folder (ui_appimage.cpp) + const bool linuxApp = NativeLinux() && !v.fixture; + if (linuxApp) { + wstring imageFile, imageWhy; + const bool own = RunsFromOwnAppImage(&imageFile, &imageWhy); + // the folder the uninstall deletes (AppDataPath, as UninstallAppImage and its question name it), not a --data override + const wstring target = AppDataPath(); + inst = Status{-1, own || RunsInsideAnAppImage() ? L"Runs from an AppImage" : L"Not an AppImage", L""}; + instDesc = AppImageSettingsWords(own, imageFile, target, imageWhy, IgnoreListThere(target), own && GamesBlockAppImageUninstall()); + instActs.clear(); + if (own) instActs.push_back({ID_S_SELFUNINSTALL, v.task == T_SELFUNINSTALL ? L"Uninstalling\u2026" : L"Uninstall WrongGPU\u2026", false, !v.busy}); + } section({ [&](float ry, bool b) { // Windows' own app mode (not the launcher's palette: set to Light, the launcher is light while Windows may be dark); // a render's palette is its theme const bool winDark = v.fixture ? pal.dark : ThemeIsDark(L"system"); - const wstring follows = L"Follows Windows' app mode (now " + wstring(winDark ? L"dark" : L"light") + L")."; + // natively there is no Windows app mode: "System" is the desktop's light or dark setting, which the launcher cannot read on + // Linux yet, so it says what it uses instead (the layer's registry stand-in has no value: light) + const bool desktop = NativeLinux() && !v.fixture; + const wstring follows = desktop ? L"System should follow the desktop's light or dark setting, but WrongGPU can't read it on Linux yet, so it uses " + wstring(winDark ? L"dark" : L"light") + L" for now." + : L"Follows Windows' app mode (now " + wstring(winDark ? L"dark" : L"light") + L")."; const float h = SettingRow(gx, lx, ry, lw, b, kGlyphAppearance, L"Appearance", Status{}, - sel == 0 ? follows : L"The launcher stays " + wstring(sel == 1 ? L"light" : L"dark") + L". System follows Windows' app mode.", + sel == 0 ? follows : L"The launcher stays " + wstring(sel == 1 ? L"light" : L"dark") + (desktop ? L". " + follows : L". System follows Windows' app mode."), {}, ID_S_THEME0, -1, {L"System", L"Light", L"Dark"}, sel); // each option's help text says what that option does (the row's sentence says what the chosen one does) Describe(ID_S_THEME0, follows); @@ -608,6 +636,9 @@ void PaintSettings(Gfx& gx, const Rc& area) { }, [&](float ry, bool b) { return AccentRow(gx, lx, ry, lw, b); }, [&](float ry, bool b) { + if (!DownloadsAvailable() && !v.fixture) // Linux: no switch, nothing to turn on (DownloadsAvailable) + return SettingRow(gx, lx, ry, lw, b, ic::sync, L"Check for new releases", Status{-1, L"Off on Linux", L""}, + L"The launcher never uses the network on Linux for now. To update, get the new AppImage from the release page yourself.", {}); float h = SettingRow(gx, lx, ry, lw, b, ic::sync, L"Check for new releases", Status{}, s.updateCheck ? L"On: one request to the release address below when the launcher starts. Nothing else is sent." : L"Off: the launcher never uses the network.", @@ -630,7 +661,7 @@ void PaintSettings(Gfx& gx, const Rc& area) { }, [&](float ry, bool b) { const float h = SettingRow(gx, lx, ry, lw, b, ic::monitor, L"Launcher install", inst, instDesc, instActs, 0, -1, {}, 0, - ID_S_DATATEXT, L"Settings and logs: " + dataDir); + ID_S_DATATEXT, L"Settings and logs: " + ShownPath(dataDir)); waits(instActs, busyWait, v.task == T_SELFINSTALL || v.task == T_SELFUNINSTALL || looking || removing); return h; }, @@ -699,6 +730,8 @@ void PaintFirstRun(Gfx& gx) { const bool installing = v.task == T_FIRSTRUN; // Continue is installing the launcher (a worker thread): the choice waits const float labW = iw < 440 ? 92.f : 104.f; const TS vs = Wrap(12.5f, pal.text, 17.5f); + // natively a long label ("Graphics card detected") wraps in its column: its second line takes room, so the next row is not drawn over it + auto LabelH = [&](Gfx& g2, const wstring& lab) { return lab.empty() || !NativeLinux() ? 0.f : g2.TextH(lab, labW, vs); }; // the foot that stays put under the part that scrolls: Continue (full width, naming what it will do) and a hint // (an installed launcher can be uninstalled in Settings, not made portable; a portable one can be installed there) wstring hint = !v.first.installOffer ? L"" : v.first.choice == 1 ? L"You can uninstall it later in Settings." : L"You can install it later in Settings."; @@ -748,7 +781,7 @@ void PaintFirstRun(Gfx& gx) { wstring lab, val; SplitCheck(l.second, lab, val); TS mt = vs; mt.weight = l.first == 2 ? 600 : 400; - listH += std::max(17.5f, gx.TextH(val, iw - 50 - (lab.empty() ? 0 : labW + 10), mt)) + 4; + listH += std::max(17.5f, std::max(gx.TextH(val, iw - 50 - (lab.empty() ? 0 : labW + 10), mt), LabelH(gx, lab))) + 4; } const Rc well{ix, y, iw, std::round(listH)}; gx.FillRound(well, 10, pal.bg); @@ -773,7 +806,7 @@ void PaintFirstRun(Gfx& gx) { // the check in words, with what it means ("Problem: Graphics card: ..."): the glyph says it to the eye AddText(Rc{well.x + 36, ly, well.r() - 14 - well.x - 36, th + 2}, (l.first == 2 ? L"Problem: " : l.first == 1 ? L"Note: " : L"") + (lab.empty() ? val : lab + L": " + val)); - ly += std::max(17.5f, th) + 4; + ly += std::max(17.5f, std::max(th, LabelH(gx, lab))) + 4; } // the fold: a link on the list's last line, its chevron in the glyphs' column, its words in the labels'; 2 DIPs under // the lines, so its keyboard focus ring (4 DIPs out) clears the line above it, and kLinkFoot over the list's foot, so diff --git a/clean/installer/src/app/ui_shell.h b/clean/installer/src/app/ui_shell.h index ce73b119..983574e4 100644 --- a/clean/installer/src/app/ui_shell.h +++ b/clean/installer/src/app/ui_shell.h @@ -12,11 +12,13 @@ #pragma once #include "app/launcher_app.h" +#ifdef _WIN32 #include #include #include #include #include +#endif #include #include @@ -124,6 +126,9 @@ struct TS { // text style bool underline = false; bool trim = false; // wrapped text: an ellipsis on the last line that fits the box }; +#ifndef _WIN32 +struct GfxCairo; // the Linux drawing state (ui_gfx_cairo.cpp) +#endif class Gfx { public: ~Gfx(); @@ -189,7 +194,11 @@ class Gfx { // material. A dry pass returns true and draws nothing. bool Backdrop(const Rc& r, float rad, float blur, float opacity = 1); void SetOffset(float dx, float dy); // content scroll: everything drawn after this is moved + // Everything drawn until PopRotate is turned by `degrees` (clockwise) round (cx, cy): the Library's busy glyph. + void PushRotate(float cx, float cy, float degrees); + void PopRotate(); float OffsetY() const { return oy_; } // the vertical offset SetOffset set (the Library's scroll anchoring moves it) +#ifdef _WIN32 ID2D1RenderTarget* rt = nullptr; IDWriteFactory* dw = nullptr; IWICImagingFactory* wic = nullptr; @@ -254,10 +263,65 @@ class Gfx { ID2D1PathGeometry* RoundPath(const Rc& r, float tl, float tr, float br, float bl); std::vector layers_; int clips_ = 0; // axis-aligned clips open (PushClip) + std::vector rotations_; // the transforms PushRotate replaced float ox_ = 0, oy_ = 0; void PushMask(const Rc& r, float rad, float opacity); // a rounded mask layer at `opacity` (popped with PopRoundClip) +#else + // Cairo and Pango (ui_gfx_cairo.cpp); the state lives behind one pointer so this header needs neither library + bool iconFont = true; + bool rt = false; // a drawing target exists (the Windows member of this name is Direct2D's render target: the window tests it) + +private: + GfxCairo* im_ = nullptr; + float ox_ = 0, oy_ = 0; + int rotationsOpen_ = 0; // PushRotate's not yet popped + void Trim(); +#endif }; +// Icons (Segoe Fluent Icons / Segoe MDL2 Assets code points) +namespace ic { // one per line +const wchar_t grid = 0xF0E2; +const wchar_t gear = 0xE713; +const wchar_t refresh = 0xE72C; +const wchar_t add = 0xE710; +const wchar_t download = 0xE896; +const wchar_t search = 0xE721; +const wchar_t back = 0xE76B; +const wchar_t play = 0xF5B0; +const wchar_t more = 0xE712; +const wchar_t warn = 0xE7BA; +const wchar_t folder = 0xE8B7; +const wchar_t cube = 0xE7B8; +const wchar_t panel = 0xEA86; +const wchar_t monitor = 0xE7F4; +const wchar_t down = 0xE70D; +const wchar_t check = 0xE73E; +const wchar_t close = 0xE711; +const wchar_t info = 0xE946; +const wchar_t doc = 0xE8A5; +const wchar_t zip = 0xF012; +const wchar_t wrench = 0xE90F; +const wchar_t undo = 0xE7A7; +const wchar_t trash = 0xE74D; +const wchar_t broom = 0xEA99; +const wchar_t upload = 0xE898; +const wchar_t link = 0xE71B; +const wchar_t minus = 0xE738; +const wchar_t shield = 0xEA18; +const wchar_t question = 0xE897; +const wchar_t chip = 0xE964; +const wchar_t sync = 0xE895; +const wchar_t key = 0xE8D7; +const wchar_t playLine = 0xE768; +const wchar_t up = 0xE70E; +const wchar_t arrowUp = 0xE74A; // an update ready (UpdateMark) +const wchar_t palette = 0xE790; +const wchar_t chevron = 0xE76C; +const wchar_t external = 0xE8A7; +const wchar_t processor = 0xE950; +} + // ---- art (ui_art.cpp) ---------------------------------------------------------------------------------------------------- // hero: the wide library_hero.jpg at a tile's size and logo: the game's logo.png (alpha) at the banner's (the Library's tiles // and banner, the game page's banner); header: header.jpg (a tile without a hero: it has the title on it); cover: the @@ -367,12 +431,14 @@ enum : int { ID_G_TITLE, ID_G_DIRTEXT, ID_G_EXETEXT, // text for UI Automation (not focusable): the game's whole name, its folder, its exe ID_G_COVER, // the game page's cover: not a hit, the name of its upscale wipe (UpscaleWipe) ID_G_STATUS, ID_G_PROGRESS, ID_G_UNSAVED, // text for UI Automation: the header's status (or step), its progress, the capsule's words + ID_G_WINFOLDER_COPY, // Linux: a game that is not a Steam game's "windows-folder" command (Copy); must stay below ID_G_RRON // Ray Reconstruction (rr.h): its switch, the data's Convert, Repair (an install without the RR files); its quality's // segments + 0 Exact, 1 Accurate, 2 Fast (Exact is drawn only with Settings' Exact mode, or while the game is set to it) ID_G_RRON = 3086, ID_G_RRCONVERT, ID_G_RRREPAIR, ID_G_RRPREP, ID_G_RRMODE0 = 3090, // ID_G_RRPREP: Prepare (rrprep.h) // Borderlands 4 / Hogwarts Legacy's Engine.ini setting (UI review #2): its segments (+ 0 WrongGPU, 1 Myself) and the steps' // Open folder, Copy and Check again; Fix it again (WrongGPU's line gone or the file no longer read-only: r2 #6) ID_G_RRCFG0 = 3093, ID_G_RRCFG_OPEN = 3095, ID_G_RRCFG_COPY, ID_G_RRCFG_CHECK, ID_G_RRCFG_FIX, + ID_G_PROTONOPT_COPY, // Linux: OptiScaler section's Steam launch option (Copy) ID_G_OPTI0 = 3100, // + editable OptiScaler row (x10: + option) ID_G_OPTI_END = ID_G_OPTI0 + 10 * 64, // room for 64 rows; the Settings ids start above it ID_S_MODELFILE = 4000, ID_S_RECONVERT, ID_S_OPTIFILE, ID_S_OPTIDIR, ID_S_ADDFOLDER, ID_S_CLEARFOLDERS, ID_S_PLAY, ID_S_UPDATE, @@ -400,6 +466,7 @@ enum : int { M_REMOVEGAME, // a game added by hand taken out of the Library (its page's More) M_FILTER0 = 200, M_OPTI0 = 300, }; +static_assert(ID_G_WINFOLDER_COPY < ID_G_RRON, "the Windows-folder Copy id sits in the free number below the Ray Reconstruction ids"); constexpr int kTileSpan = ID_TILEQA - ID_TILE; // the Library draws at most this many games (ui_library.cpp) constexpr int kMaxFolderRows = 256; // Settings lists at most this many added game folders, each with its Remove @@ -810,48 +877,6 @@ bool PageEntering(); // the page is making its entrance (the native text field bool PageUnderSheet(); constexpr float kPageMs = 180, kMenuMs = 140, kDialogMs = 180, kToastMs = 220, kToastOutMs = 260, kFirstMs = 240; constexpr float kThumbHoldMs = 900, kThumbFadeMs = 300; // the overlay scroll thumb: shown this long after the page last moved, then fades -// Icons (Segoe Fluent Icons / Segoe MDL2 Assets code points) -namespace ic { // one per line -const wchar_t grid = 0xF0E2; -const wchar_t gear = 0xE713; -const wchar_t refresh = 0xE72C; -const wchar_t add = 0xE710; -const wchar_t download = 0xE896; -const wchar_t search = 0xE721; -const wchar_t back = 0xE76B; -const wchar_t play = 0xF5B0; -const wchar_t more = 0xE712; -const wchar_t warn = 0xE7BA; -const wchar_t folder = 0xE8B7; -const wchar_t cube = 0xE7B8; -const wchar_t panel = 0xEA86; -const wchar_t monitor = 0xE7F4; -const wchar_t down = 0xE70D; -const wchar_t check = 0xE73E; -const wchar_t close = 0xE711; -const wchar_t info = 0xE946; -const wchar_t doc = 0xE8A5; -const wchar_t zip = 0xF012; -const wchar_t wrench = 0xE90F; -const wchar_t undo = 0xE7A7; -const wchar_t trash = 0xE74D; -const wchar_t broom = 0xEA99; -const wchar_t upload = 0xE898; -const wchar_t link = 0xE71B; -const wchar_t minus = 0xE738; -const wchar_t shield = 0xEA18; -const wchar_t question = 0xE897; -const wchar_t chip = 0xE964; -const wchar_t sync = 0xE895; -const wchar_t key = 0xE8D7; -const wchar_t playLine = 0xE768; -const wchar_t up = 0xE70E; -const wchar_t arrowUp = 0xE74A; // an update ready (UpdateMark) -const wchar_t palette = 0xE790; -const wchar_t chevron = 0xE76C; -const wchar_t external = 0xE8A7; -const wchar_t processor = 0xE950; -} // ---- pages (ui_library.cpp, ui_game.cpp, ui_settings.cpp) --------------------------------------------------------------- void PaintLibrary(Gfx& gx, const Rc& area); @@ -922,6 +947,11 @@ void RevealId(int id); // a widget or words brought into view without // danger: the action destroys something (Uninstall, Clean up, Reset, Remove): its button is red and never the default bool Confirm(const wstring& text, int icon = 0, const wstring& yes = L"Yes", const wstring& no = L"No", bool danger = false); void Inform(const wstring& text, int icon = 2); +// ui_appimage.cpp: Settings' row of the native Linux launcher's own removal (own: this copy can remove its AppImage; else why not) +wstring AppImageSettingsWords(bool own, const wstring& file, const wstring& data, const wstring& why, bool keepsList, bool gamesHaveIt); +bool RunsFromOwnAppImage(wstring* file, wstring* why, wstring* host = nullptr); // OwnAppImage, asked once (host: the file as a shell spells it) +bool IgnoreListThere(const wstring& dataDir); // the data folder has the player's ignore-files.txt as a plain file (an uninstall keeps it) +bool GamesBlockAppImageUninstall(); // a game still has WrongGPU by the uninstall's own look (registered and managed games) // A note that arrives on its own (a worker's result): shown at once, or once the dialog or file dialog that is open closes, so // it never answers a question the player has open. void InformLater(const wstring& text, int icon = 2); diff --git a/clean/installer/src/app/ui_uia.cpp b/clean/installer/src/app/ui_uia.cpp index 5e8e9615..0930001b 100644 --- a/clean/installer/src/app/ui_uia.cpp +++ b/clean/installer/src/app/ui_uia.cpp @@ -30,6 +30,7 @@ #include "app/ui_shell.h" #include "app/launcher_window.h" +#ifdef _WIN32 // UI Automation is Windows' own: the Linux build has the stand-ins at the end of this part (AT-SPI is a later step) #include #include @@ -1080,6 +1081,37 @@ bool UiaInvokeMessage(UINT msg, WPARAM wp, LPARAM lp) { } } // namespace wg::app::lui +#else +namespace wg::app::lui { +// No accessibility tree yet: the calls the window makes into UI Automation do nothing. EditOf and FieldInvalidWhy are the +// window's own lookups (the same as above, which UI Automation shares). +LRESULT UiaGetObject(HWND, WPARAM, LPARAM) { return 0; } +void UiaFocusChanged(int) {} +void UiaNotify(const wstring&, bool, int) {} +void UiaFrame() {} +void UiaNameEdit(HWND, const wstring&) {} +void UiaForgetEdit(HWND) {} +void UiaMarkEdit(HWND, const wstring&) {} +void UiaShutdown(HWND) {} +bool UiaInvokeMessage(UINT, WPARAM, LPARAM) { return false; } +HWND EditOf(int id) { + if (id == ID_SEARCH) return v.edSearch.h; + if (id == ID_S_URL) return v.edUrl.h; + if (id >= ID_G_OPTI0 && id < ID_G_OPTI_END && (id - ID_G_OPTI0) % 10 == 0) { + const size_t row = (size_t)(id - ID_G_OPTI0) / 10; + if (row < v.edOpti.size()) return v.edOpti[row].h; + } + return nullptr; +} +wstring FieldInvalidWhy(int id) { + const auto& b = v.optiBad; + if (id < ID_G_OPTI0 || id >= ID_G_OPTI_END || (id - ID_G_OPTI0) % 10 != 0 || v.page != P_GAME) return L""; + const size_t row = (size_t)(id - ID_G_OPTI0) / 10; + if (row != b.row || row >= v.optiValues.size() || v.optiValues[row] != b.value || b.dir.empty() || !IEq(b.dir, v.cur.dir)) return L""; + return b.why; +} +} // namespace wg::app::lui +#endif // ---- the keyboard focus on the Library's places -------------------------------------------------------------------------- // A lockup's ids (ID_TILE, ID_TILEQA + its index) are its game's place in v.games, and the featured banner's (ID_FEAT0 + 1, + 2) diff --git a/clean/installer/src/platform/posix/commctrl.h b/clean/installer/src/platform/posix/commctrl.h new file mode 100644 index 00000000..638cfb9a --- /dev/null +++ b/clean/installer/src/platform/posix/commctrl.h @@ -0,0 +1,4 @@ +// SPDX-License-Identifier: MIT +// Linux: stands in for the Windows header of the same name (win32_window.h). +#pragma once +#include "win32_window.h" diff --git a/clean/installer/src/platform/posix/dwmapi.h b/clean/installer/src/platform/posix/dwmapi.h new file mode 100644 index 00000000..638cfb9a --- /dev/null +++ b/clean/installer/src/platform/posix/dwmapi.h @@ -0,0 +1,4 @@ +// SPDX-License-Identifier: MIT +// Linux: stands in for the Windows header of the same name (win32_window.h). +#pragma once +#include "win32_window.h" diff --git a/clean/installer/src/platform/posix/dxgi.h b/clean/installer/src/platform/posix/dxgi.h new file mode 100644 index 00000000..b13ed666 --- /dev/null +++ b/clean/installer/src/platform/posix/dxgi.h @@ -0,0 +1,4 @@ +// SPDX-License-Identifier: MIT +// Linux: stands in for the Windows header of the same name (win32_posix.h). +#pragma once +#include "win32_posix.h" diff --git a/clean/installer/src/platform/posix/dxgi1_6.h b/clean/installer/src/platform/posix/dxgi1_6.h new file mode 100644 index 00000000..b13ed666 --- /dev/null +++ b/clean/installer/src/platform/posix/dxgi1_6.h @@ -0,0 +1,4 @@ +// SPDX-License-Identifier: MIT +// Linux: stands in for the Windows header of the same name (win32_posix.h). +#pragma once +#include "win32_posix.h" diff --git a/clean/installer/src/platform/posix/objbase.h b/clean/installer/src/platform/posix/objbase.h new file mode 100644 index 00000000..b13ed666 --- /dev/null +++ b/clean/installer/src/platform/posix/objbase.h @@ -0,0 +1,4 @@ +// SPDX-License-Identifier: MIT +// Linux: stands in for the Windows header of the same name (win32_posix.h). +#pragma once +#include "win32_posix.h" diff --git a/clean/installer/src/platform/posix/restartmanager.h b/clean/installer/src/platform/posix/restartmanager.h new file mode 100644 index 00000000..fb806a21 --- /dev/null +++ b/clean/installer/src/platform/posix/restartmanager.h @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: MIT +// Linux: stands in for the Windows header of the same name (win32_posix_rm.cpp). The Restart Manager's "which processes +// hold these files" on /proc: a process holds a file when one of its open files (/proc//fd) or mapped files +// (/proc//maps: a library, or a DLL a Wine process has loaded) is that file (same device and inode). Only this +// user's processes are looked at (another user's fd and maps are closed to it): a file another account's program holds is +// not listed. A process of this user whose fd or maps cannot be read (not dumpable, or holding capabilities: on a desktop +// the compositor and ssh-agent, for example) adds RmRebootReasonPermissionDenied to the reasons, so on most desktops that +// reason is always there; an empty list means "none seen", never more. Restarting or shutting down applications is not available. +#pragma once +#include "win32_posix.h" + +constexpr DWORD CCH_RM_SESSION_KEY = 32; // sizeof(GUID) * 2 +constexpr DWORD CCH_RM_MAX_APP_NAME = 255; +constexpr DWORD CCH_RM_MAX_SVC_NAME = 63; +typedef enum _RM_APP_TYPE { RmUnknownApp = 0, RmMainWindow = 1, RmOtherWindow = 2, RmService = 3, RmExplorer = 4, RmConsole = 5, RmCritical = 1000 } RM_APP_TYPE; +typedef enum _RM_REBOOT_REASON { + RmRebootReasonNone = 0x0, RmRebootReasonPermissionDenied = 0x1, RmRebootReasonSessionMismatch = 0x2, RmRebootReasonCriticalProcess = 0x4, + RmRebootReasonCriticalService = 0x8, RmRebootReasonDetectedSelf = 0x10 +} RM_REBOOT_REASON; +typedef struct _RM_UNIQUE_PROCESS { DWORD dwProcessId; FILETIME ProcessStartTime; } RM_UNIQUE_PROCESS; +typedef struct _RM_PROCESS_INFO { + RM_UNIQUE_PROCESS Process; // ProcessStartTime: the process's start (from /proc//stat) + WCHAR strAppName[CCH_RM_MAX_APP_NAME + 1]; // the program's file name (a Wine process: its Windows program's name) + WCHAR strServiceShortName[CCH_RM_MAX_SVC_NAME + 1]; // always empty + RM_APP_TYPE ApplicationType; // always RmUnknownApp + ULONG AppStatus; + DWORD TSSessionId; + BOOL bRestartable; // always FALSE +} RM_PROCESS_INFO; + +DWORD RmStartSession(DWORD* session, DWORD flags, WCHAR key[]); +// files only: applications or services to register are ERROR_NOT_SUPPORTED +DWORD RmRegisterResources(DWORD session, UINT nFiles, LPCWSTR files[], UINT nApplications, RM_UNIQUE_PROCESS applications[], UINT nServices, + LPCWSTR services[]); +// ERROR_MORE_DATA (and *needed) when *count is too small; *reasons as above +DWORD RmGetList(DWORD session, UINT* needed, UINT* count, RM_PROCESS_INFO info[], LPDWORD reasons); +DWORD RmEndSession(DWORD session); diff --git a/clean/installer/src/platform/posix/sddl.h b/clean/installer/src/platform/posix/sddl.h new file mode 100644 index 00000000..b13ed666 --- /dev/null +++ b/clean/installer/src/platform/posix/sddl.h @@ -0,0 +1,4 @@ +// SPDX-License-Identifier: MIT +// Linux: stands in for the Windows header of the same name (win32_posix.h). +#pragma once +#include "win32_posix.h" diff --git a/clean/installer/src/platform/posix/shellapi.h b/clean/installer/src/platform/posix/shellapi.h new file mode 100644 index 00000000..b13ed666 --- /dev/null +++ b/clean/installer/src/platform/posix/shellapi.h @@ -0,0 +1,4 @@ +// SPDX-License-Identifier: MIT +// Linux: stands in for the Windows header of the same name (win32_posix.h). +#pragma once +#include "win32_posix.h" diff --git a/clean/installer/src/platform/posix/shlobj.h b/clean/installer/src/platform/posix/shlobj.h new file mode 100644 index 00000000..b13ed666 --- /dev/null +++ b/clean/installer/src/platform/posix/shlobj.h @@ -0,0 +1,4 @@ +// SPDX-License-Identifier: MIT +// Linux: stands in for the Windows header of the same name (win32_posix.h). +#pragma once +#include "win32_posix.h" diff --git a/clean/installer/src/platform/posix/shobjidl.h b/clean/installer/src/platform/posix/shobjidl.h new file mode 100644 index 00000000..b13ed666 --- /dev/null +++ b/clean/installer/src/platform/posix/shobjidl.h @@ -0,0 +1,4 @@ +// SPDX-License-Identifier: MIT +// Linux: stands in for the Windows header of the same name (win32_posix.h). +#pragma once +#include "win32_posix.h" diff --git a/clean/installer/src/platform/posix/testing_identity_linux.cpp b/clean/installer/src/platform/posix/testing_identity_linux.cpp new file mode 100644 index 00000000..dc5e11bd --- /dev/null +++ b/clean/installer/src/platform/posix/testing_identity_linux.cpp @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: MIT +// Linux, WRONGGPU_TESTING builds of the launcher only: the identity the launcher suite checks before it runs a program +// (tests/launcher_build_facts.py), as the WRONGGPU_TESTING_BUILD resource on Windows (CMakeLists.txt): the same text, then +// "wg-sha256:" and 32 bytes that tools/elf_testing_identity.py fills after the link with the file's SHA-256 (those bytes +// counted as zero), as the PE checksum on Windows. +extern "C" __attribute__((section(".wg_testing_id"), used)) const char wg_testing_identity[] = + "wg-testing-build 1: store libraries, access log, edition download, uninstall root\0" + "wg-sha256:" + "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"; diff --git a/clean/installer/src/platform/posix/tests/posix_layer_tests.cpp b/clean/installer/src/platform/posix/tests/posix_layer_tests.cpp new file mode 100644 index 00000000..6ddfb18a --- /dev/null +++ b/clean/installer/src/platform/posix/tests/posix_layer_tests.cpp @@ -0,0 +1,1640 @@ +// SPDX-License-Identifier: MIT +// Tests of the Linux layer itself (src/platform/posix): the Windows calls it implements, checked against what Windows does. +// The core's own tests exercise it only as far as the core goes; this covers the rest (sharing, processes, the registry file). +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "win32_posix_internal.h" +#include "wg_core/appimage.h" +#include "wg_core/checks.h" +#include "wg_core/launcher.h" +#include "wg_core/optiedition.h" +#include "../../../../../wgshared/include/wg_state.h" + +namespace { +int checks = 0, failures = 0; +void check(bool ok, const char* what) { + ++checks; + if (!ok) { ++failures; std::printf("FAILED: %s (last error %u)\n", what, (unsigned)GetLastError()); } +} +std::wstring Tmp; // a fresh folder of this run +std::wstring In(const wchar_t* rel) { return Tmp + L"\\" + rel; } +bool Put(const std::wstring& p, const char* text) { + HANDLE h = CreateFileW(p.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + if (h == INVALID_HANDLE_VALUE) return false; + DWORD w = 0; + const bool ok = WriteFile(h, text, (DWORD)std::strlen(text), &w, nullptr); + CloseHandle(h); + return ok; +} +std::string Slurp(const std::wstring& p) { + HANDLE h = CreateFileW(p.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + if (h == INVALID_HANDLE_VALUE) return ""; + char b[4096]; DWORD got = 0; + ReadFile(h, b, sizeof(b), &got, nullptr); + CloseHandle(h); + return std::string(b, got); +} + +void Paths() { + check(GetFileAttributesW(L"C:\\Windows") == INVALID_FILE_ATTRIBUTES && GetLastError() == ERROR_PATH_NOT_FOUND, "a drive other than Z: does not exist"); + check((GetFileAttributesW(L"Z:\\") & FILE_ATTRIBUTE_DIRECTORY) != 0, "Z:\\ is the root folder"); + check((GetFileAttributesW(L"\\\\?\\Z:\\") & FILE_ATTRIBUTE_DIRECTORY) != 0, "a \\\\?\\ prefix is dropped"); + check(GetFileAttributesW(L"Z:\\no?such") == INVALID_FILE_ATTRIBUTES && GetLastError() == ERROR_INVALID_NAME, "a ? in a name: invalid name"); + check(GetFileAttributesW((Tmp + L"\\nothing-here\\x").c_str()) == INVALID_FILE_ATTRIBUTES && GetLastError() == ERROR_PATH_NOT_FOUND, "a missing folder: path not found"); + check(GetFileAttributesW(In(L"nothing-here").c_str()) == INVALID_FILE_ATTRIBUTES && GetLastError() == ERROR_FILE_NOT_FOUND, "a missing file: file not found"); + Put(In(L"MixedCase.TXT"), "x"); + check(GetFileAttributesW(In(L"mixedcase.txt").c_str()) != INVALID_FILE_ATTRIBUTES, "names match ignoring case, as on NTFS"); + wchar_t full[MAX_PATH * 2]; + const DWORD n = GetFullPathNameW(L"Z:\\a\\.\\b\\..\\c/d", (DWORD)(sizeof(full) / sizeof(full[0])), full, nullptr); + check(n && std::wstring(full, n) == L"Z:\\a\\c\\d", "GetFullPathNameW folds . and .. and uses backslashes"); + const DWORD m = GetFullPathNameW(L"C:\\x\\..\\y", (DWORD)(sizeof(full) / sizeof(full[0])), full, nullptr); + check(m && std::wstring(full, m) == L"C:\\y", "a drive other than Z: is spelled, not looked at"); + check(std::wstring(Tmp).rfind(L"Z:\\", 0) == 0, "GetTempPathW is a Z:\\ path"); +} + +void Files() { + check(Put(In(L"a.txt"), "hello") && Slurp(In(L"a.txt")) == "hello", "write and read back"); + HANDLE held = CreateFileW(In(L"a.txt").c_str(), GENERIC_READ, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + check(held != INVALID_HANDLE_VALUE, "open with no sharing"); + check(CreateFileW(In(L"a.txt").c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr) == INVALID_HANDLE_VALUE && GetLastError() == ERROR_SHARING_VIOLATION, + "a second open of a file held without sharing: sharing violation"); + check(!DeleteFileW(In(L"a.txt").c_str()) && GetLastError() == ERROR_SHARING_VIOLATION, "a held file cannot be deleted"); + check(!MoveFileExW(In(L"a.txt").c_str(), In(L"b.txt").c_str(), 0) && GetLastError() == ERROR_SHARING_VIOLATION, "a held file cannot be moved"); + CloseHandle(held); + HANDLE shared = CreateFileW(In(L"a.txt").c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, 0, nullptr); + check(shared != INVALID_HANDLE_VALUE && Slurp(In(L"a.txt")) == "hello", "a reader that allows readers and deleters lets another read"); + check(MoveFileExW(In(L"a.txt").c_str(), In(L"b.txt").c_str(), 0), "and lets the file move"); + CloseHandle(shared); + + Put(In(L"c.txt"), "new"); + check(!MoveFileExW(In(L"c.txt").c_str(), In(L"b.txt").c_str(), 0) && GetLastError() == ERROR_ALREADY_EXISTS, "a move onto a file without REPLACE_EXISTING fails"); + check(MoveFileExW(In(L"c.txt").c_str(), In(L"b.txt").c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH) && Slurp(In(L"b.txt")) == "new", "a move with REPLACE_EXISTING replaces"); + + check(SetFileAttributesW(In(L"b.txt").c_str(), FILE_ATTRIBUTE_READONLY) && (GetFileAttributesW(In(L"b.txt").c_str()) & FILE_ATTRIBUTE_READONLY), "read-only is a missing write bit"); + check(!DeleteFileW(In(L"b.txt").c_str()) && GetLastError() == ERROR_ACCESS_DENIED, "a read-only file is not deleted"); + check(CreateFileW(In(L"b.txt").c_str(), GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, 0, nullptr) == INVALID_HANDLE_VALUE && GetLastError() == ERROR_ACCESS_DENIED, "nor opened for writing"); + check(SetFileAttributesW(In(L"b.txt").c_str(), FILE_ATTRIBUTE_NORMAL) && DeleteFileW(In(L"b.txt").c_str()), "normal again: deleted"); + + check(CreateDirectoryW(In(L"d").c_str(), nullptr) && !CreateDirectoryW(In(L"d").c_str(), nullptr) && GetLastError() == ERROR_ALREADY_EXISTS, "CreateDirectoryW twice: already exists"); + Put(In(L"d\\one.txt"), "1"); Put(In(L"d\\Two.txt"), "2"); Put(In(L"d\\three.dat"), "3"); + WIN32_FIND_DATAW fd; + std::vector names; + HANDLE f = FindFirstFileW(In(L"d\\*.txt").c_str(), &fd); + if (f != INVALID_HANDLE_VALUE) { do names.push_back(fd.cFileName); while (FindNextFileW(f, &fd)); check(GetLastError() == ERROR_NO_MORE_FILES, "the end of a listing: no more files"); FindClose(f); } + check(names.size() == 2 && names[0] == L"one.txt" && names[1] == L"Two.txt", "FindFirstFileW: the wildcard, sorted ignoring case"); + check(FindFirstFileW(In(L"d\\*.zip").c_str(), &fd) == INVALID_HANDLE_VALUE && GetLastError() == ERROR_FILE_NOT_FOUND, "no match: file not found"); + check(FindFirstFileW(In(L"nope\\*").c_str(), &fd) == INVALID_HANDLE_VALUE && GetLastError() == ERROR_PATH_NOT_FOUND, "no folder: path not found"); + + check(CreateSymbolicLinkW(In(L"link").c_str(), In(L"d").c_str(), SYMBOLIC_LINK_FLAG_DIRECTORY), "a symbolic link"); + const DWORD la = GetFileAttributesW(In(L"link").c_str()); + check((la & FILE_ATTRIBUTE_REPARSE_POINT) && (la & FILE_ATTRIBUTE_DIRECTORY), "a link to a folder is a reparse point and a folder"); + check(RemoveDirectoryW(In(L"link").c_str()) && Slurp(In(L"d\\one.txt")) == "1", "RemoveDirectoryW on the link leaves the target"); + check(!RemoveDirectoryW(In(L"d").c_str()) && GetLastError() == ERROR_DIR_NOT_EMPTY, "a folder with files stays: directory not empty"); + + HANDLE h = CreateFileW(In(L"d\\one.txt").c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr); + BY_HANDLE_FILE_INFORMATION bi{}; + FILE_ID_INFO id{}; + check(h != INVALID_HANDLE_VALUE && GetFileInformationByHandle(h, &bi) && bi.nFileSizeLow == 1 && GetFileInformationByHandleEx(h, FileIdInfo, &id, sizeof(id)), "file information by handle"); + CloseHandle(h); + check(!CloseHandle(h) && GetLastError() == ERROR_INVALID_HANDLE, "closing a handle twice: invalid handle"); + + HANDLE a = CreateFileW(In(L"log.txt").c_str(), FILE_APPEND_DATA, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_ALWAYS, 0, nullptr); + DWORD w = 0; + WriteFile(a, "ab", 2, &w, nullptr); CloseHandle(a); + a = CreateFileW(In(L"log.txt").c_str(), FILE_APPEND_DATA, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_ALWAYS, 0, nullptr); + check(GetLastError() == ERROR_ALREADY_EXISTS, "OPEN_ALWAYS on a file that is there: already exists, success"); + WriteFile(a, "cd", 2, &w, nullptr); CloseHandle(a); + check(Slurp(In(L"log.txt")) == "abcd", "FILE_APPEND_DATA appends"); +} + +void Times() { + SYSTEMTIME st{2001, 9, 0, 9, 1, 46, 40, 0}; // 1e9 seconds after the Unix epoch, UTC + FILETIME ft{}; + check(SystemTimeToFileTime(&st, &ft) && (((ULONGLONG)ft.dwHighDateTime << 32) | ft.dwLowDateTime) == (1000000000ull + 11644473600ull) * 10000000ull, "SystemTimeToFileTime"); + SYSTEMTIME back{}; + check(FileTimeToSystemTime(&ft, &back) && back.wYear == 2001 && back.wMonth == 9 && back.wDay == 9 && back.wHour == 1 && back.wMinute == 46 && back.wSecond == 40, "FileTimeToSystemTime"); + FILETIME loc{}, utc{}; + check(FileTimeToLocalFileTime(&ft, &loc) && LocalFileTimeToFileTime(&loc, &utc) && CompareFileTime(&ft, &utc) == 0, "local and UTC file times convert back and forth"); + SYSTEMTIME lst{2026, 10, 0, 2, 20, 20, 0, 0}; + FILETIME lf{}, uf{}, again{}; + SYSTEMTIME shown{}; + SystemTimeToFileTime(&lst, &lf); LocalFileTimeToFileTime(&lf, &uf); FileTimeToLocalFileTime(&uf, &again); FileTimeToSystemTime(&again, &shown); + check(shown.wHour == 20 && shown.wMinute == 20 && shown.wDay == 2, "a local reading survives the round trip"); +} + +void Strings() { + const char bad[] = {'a', (char)0xFF, 'b', 0}; + check(MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, bad, -1, nullptr, 0) == 0, "bytes that are not UTF-8 are refused with MB_ERR_INVALID_CHARS"); + check(MultiByteToWideChar(CP_UTF8, 0, bad, -1, nullptr, 0) == 4, "and replaced without it"); + wchar_t w[8]{}; + const char eacute[] = "\xC3\xA9"; + check(MultiByteToWideChar(CP_UTF8, 0, eacute, 2, w, 8) == 1 && w[0] == 0xE9, "UTF-8 to wide"); + char u[8]{}; + check(WideCharToMultiByte(CP_UTF8, 0, w, 1, u, 8, nullptr, nullptr) == 2 && (unsigned char)u[0] == 0xC3, "wide to UTF-8"); + check(_wcsicmp(L"Game.EXE", L"game.exe") == 0 && _wcsicmp(L"a", L"b") < 0, "_wcsicmp"); +} + +void Registry() { + HKEY k = nullptr; + DWORD disposition = 0; + check(RegCreateKeyExW(HKEY_CURRENT_USER, L"Software\\WgLayerTest\\Sub", 0, nullptr, 0, KEY_WRITE, nullptr, &k, &disposition) == ERROR_SUCCESS && disposition == REG_CREATED_NEW_KEY, "create a key"); + const std::wstring text = L"C:\\Games\\\u00e9"; + RegSetValueExW(k, L"Text", 0, REG_SZ, (const BYTE*)text.c_str(), (DWORD)((text.size() + 1) * 2)); + const DWORD num = 42; + RegSetValueExW(k, L"Num", 0, REG_DWORD, (const BYTE*)&num, 4); + RegCloseKey(k); + check(RegOpenKeyExW(HKEY_CURRENT_USER, L"software\\wgLAYERtest\\sub", 0, KEY_READ, &k) == ERROR_SUCCESS, "key names ignore case"); + wchar_t buf[64]{}; DWORD sz = sizeof(buf), type = 0; + check(RegQueryValueExW(k, L"TEXT", nullptr, &type, (LPBYTE)buf, &sz) == ERROR_SUCCESS && type == REG_SZ && text == buf && sz == (text.size() + 1) * sizeof(wchar_t), "a string value reads back (value names ignore case)"); + DWORD got = 0, gsz = sizeof(got); + check(RegGetValueW(HKEY_CURRENT_USER, L"Software\\WgLayerTest\\Sub", L"Num", RRF_RT_REG_DWORD, nullptr, &got, &gsz) == ERROR_SUCCESS && got == 42, "RegGetValueW reads a DWORD"); + DWORD small = 2; + check(RegQueryValueExW(k, L"Text", nullptr, &type, (LPBYTE)buf, &small) == ERROR_MORE_DATA && small == sz, "a short buffer: more data, with the size"); + check(RegSetValueExW(k, L"X", 0, REG_SZ, (const BYTE*)L"", 2) == ERROR_ACCESS_DENIED, "a key opened for reading refuses writes"); + RegCloseKey(k); + check(RegDeleteKeyW(HKEY_CURRENT_USER, L"Software\\WgLayerTest") == ERROR_ACCESS_DENIED, "a key with a subkey is not deleted"); + check(RegOpenKeyExW(HKEY_CURRENT_USER, L"Software\\WgLayerTest", 0, KEY_READ, &k) == ERROR_SUCCESS, "its parent exists"); + wchar_t name[64]; DWORD len = 64; + check(RegEnumKeyExW(k, 0, name, &len, nullptr, nullptr, nullptr, nullptr) == ERROR_SUCCESS && std::wstring(name) == L"Sub" && RegEnumKeyExW(k, 1, name, &len, nullptr, nullptr, nullptr, nullptr) == ERROR_NO_MORE_ITEMS, "enumerate subkeys"); + RegCloseKey(k); + check(RegDeleteKeyW(HKEY_CURRENT_USER, L"Software\\WgLayerTest\\Sub") == ERROR_SUCCESS && RegDeleteKeyW(HKEY_CURRENT_USER, L"Software\\WgLayerTest") == ERROR_SUCCESS, "delete leaf first, then parent"); + check(RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft", 0, KEY_READ, &k) == ERROR_FILE_NOT_FOUND, "HKEY_LOCAL_MACHINE reads as empty"); + check(RegCreateKeyExW(HKEY_LOCAL_MACHINE, L"Software\\Nope", 0, nullptr, 0, KEY_WRITE, nullptr, &k, nullptr) == ERROR_ACCESS_DENIED, "and refuses writes"); + + // an app hive is a file: what one load wrote, the next reads + const std::wstring hive = In(L"hive.dat"); + HKEY h = nullptr, key = nullptr; + check(RegLoadAppKeyW(hive.c_str(), &h, KEY_ALL_ACCESS, 0, 0) == ERROR_SUCCESS, "load an app hive"); + check(RegCreateKeyExW(h, L"A\\B", 0, nullptr, 0, KEY_WRITE, nullptr, &key, nullptr) == ERROR_SUCCESS && RegSetValueExW(key, L"v", 0, REG_SZ, (const BYTE*)L"x\ny=z%", 14) == ERROR_SUCCESS, "write to it"); + RegCloseKey(key); RegCloseKey(h); + h = nullptr; + check(RegLoadAppKeyW(hive.c_str(), &h, KEY_READ, 0, 0) == ERROR_SUCCESS, "load it again"); + std::wstring seen = L"?"; + if (RegOpenKeyExW(h, L"a\\b", 0, KEY_READ, &key) == ERROR_SUCCESS) { wchar_t v[16]{}; DWORD vs = sizeof(v); RegQueryValueExW(key, L"v", nullptr, nullptr, (LPBYTE)v, &vs); seen = v; RegCloseKey(key); } + check(seen == L"x\ny=z%", "the value (newline, = and % too) comes back from the file"); + RegCloseKey(h); +} + +void Processes() { + SECURITY_ATTRIBUTES sa{sizeof(sa), nullptr, TRUE}; + HANDLE rd = nullptr, wr = nullptr; + check(CreatePipe(&rd, &wr, &sa, 0), "a pipe"); + SetHandleInformation(rd, HANDLE_FLAG_INHERIT, 0); + STARTUPINFOW si{}; si.cb = sizeof(si); si.dwFlags = STARTF_USESTDHANDLES; si.hStdOutput = wr; si.hStdError = wr; + PROCESS_INFORMATION pi{}; + std::wstring cmd = L"\"/bin/sh\" -c \"printf '%s|' \\\"a b\\\" c; exit 7\""; + std::vector buf(cmd.begin(), cmd.end()); buf.push_back(0); + check(CreateProcessW(nullptr, buf.data(), nullptr, nullptr, TRUE, CREATE_NO_WINDOW | CREATE_UNICODE_ENVIRONMENT, nullptr, nullptr, &si, &pi), "start a program"); + CloseHandle(wr); + check(WaitForSingleObject(pi.hProcess, 10000) == WAIT_OBJECT_0, "wait for it"); + DWORD code = 0, avail = 0, got = 0; + char out[64]{}; + check(GetExitCodeProcess(pi.hProcess, &code) && code == 7, "its exit code"); + check(PeekNamedPipe(rd, nullptr, 0, nullptr, &avail, nullptr) && avail == 6 && ReadFile(rd, out, sizeof(out), &got, nullptr) && std::string(out, got) == "a b|c|", "its output through the pipe, quoted arguments kept together"); + check(!ReadFile(rd, out, sizeof(out), &got, nullptr) && GetLastError() == ERROR_BROKEN_PIPE, "a pipe whose writer is gone: broken pipe"); + CloseHandle(pi.hProcess); CloseHandle(pi.hThread); CloseHandle(rd); + + // looked up in PATH when it has no folder; stopped by TerminateProcess with the code asked for + std::wstring sleepCmd = L"sleep 30"; + std::vector sb(sleepCmd.begin(), sleepCmd.end()); sb.push_back(0); + PROCESS_INFORMATION sp{}; + STARTUPINFOW si2{}; si2.cb = sizeof(si2); + check(CreateProcessW(nullptr, sb.data(), nullptr, nullptr, FALSE, 0, nullptr, nullptr, &si2, &sp), "start sleep from PATH"); + check(WaitForSingleObject(sp.hProcess, 0) == WAIT_TIMEOUT && (GetExitCodeProcess(sp.hProcess, &code), code == STILL_ACTIVE), "it runs: still active"); + check(TerminateProcess(sp.hProcess, 98) && WaitForSingleObject(sp.hProcess, 5000) == WAIT_OBJECT_0 && (GetExitCodeProcess(sp.hProcess, &code), code == 98), "TerminateProcess: the exit code asked for"); + CloseHandle(sp.hProcess); CloseHandle(sp.hThread); + + // a job: processes in it end with TerminateJobObject + HANDLE job = CreateJobObjectW(nullptr, nullptr); + JOBOBJECT_EXTENDED_LIMIT_INFORMATION li{}; + li.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; + check(job && SetInformationJobObject(job, JobObjectExtendedLimitInformation, &li, sizeof(li)), "a job object"); + PROCESS_INFORMATION jp{}; + check(CreateProcessW(nullptr, sb.data(), nullptr, nullptr, FALSE, CREATE_SUSPENDED, nullptr, nullptr, &si2, &jp) && AssignProcessToJobObject(job, jp.hProcess), "a process in the job"); + JOBOBJECT_BASIC_ACCOUNTING_INFORMATION ai{}; + check(QueryInformationJobObject(job, JobObjectBasicAccountingInformation, &ai, sizeof(ai), nullptr) && ai.ActiveProcesses == 1, "one active process"); + check(TerminateJobObject(job, 97) && WaitForSingleObject(jp.hProcess, 5000) == WAIT_OBJECT_0, "TerminateJobObject ends it"); + QueryInformationJobObject(job, JobObjectBasicAccountingInformation, &ai, sizeof(ai), nullptr); + check(ai.ActiveProcesses == 0 && (GetExitCodeProcess(jp.hProcess, &code), code == 97), "none left, exit code 97"); + CloseHandle(jp.hProcess); CloseHandle(jp.hThread); CloseHandle(job); + + std::wstring missing = L"Z:\\no\\such\\program.exe"; + std::vector mb(missing.begin(), missing.end()); mb.push_back(0); + PROCESS_INFORMATION mp{}; + check(!CreateProcessW(nullptr, mb.data(), nullptr, nullptr, FALSE, 0, nullptr, nullptr, &si2, &mp) && GetLastError() == ERROR_PATH_NOT_FOUND, "a program that is not there: path not found"); + Put(In(L"prog.exe"), "MZ not a program"); + std::wstring notProg = In(L"prog.exe"); + std::vector nb(notProg.begin(), notProg.end()); nb.push_back(0); + check(!CreateProcessW(nullptr, nb.data(), nullptr, nullptr, FALSE, 0, nullptr, nullptr, &si2, &mp), "a Windows program does not start here"); +} + +// ---- the review findings of the process, case, suspended-start and registry-write code ---------------------------------- +std::wstring WinOf(const std::string& posix) { + std::wstring w(posix.begin(), posix.end()); + for (auto& c : w) if (c == L'/') c = L'\\'; + return L"Z:" + w; +} +char StateOf(int pid) { // the state letter of /proc//stat + std::string s; + if (FILE* f = std::fopen(("/proc/" + std::to_string(pid) + "/stat").c_str(), "r")) { char b[512]; size_t n = std::fread(b, 1, sizeof(b) - 1, f); s.assign(b, n); std::fclose(f); } + const size_t p = s.rfind(')'); + return p == std::string::npos || p + 2 >= s.size() ? '?' : s[p + 2]; +} + +void ProcessImage() { + const std::string dirPosix(Tmp.begin() + 2, Tmp.end()); + std::string dir = dirPosix; + for (auto& c : dir) if (c == '\\') c = '/'; + const std::string exeName = "a-program-with-a-long-name.exe"; // 29 characters: /proc//comm keeps 15 + const std::string exePath = dir + "/" + exeName; + std::error_code ec; + std::filesystem::copy_file("/bin/sleep", exePath, std::filesystem::copy_options::overwrite_existing, ec); + chmod(exePath.c_str(), 0755); + const std::string real = std::filesystem::canonical(exePath, ec).string(); + const std::wstring winForm = WinOf(real); + std::wstring cmd = L"\"" + In(L"a-program-with-a-long-name.exe") + L"\" 30"; + std::vector cb(cmd.begin(), cmd.end()); cb.push_back(0); + STARTUPINFOW si{}; si.cb = sizeof(si); + PROCESS_INFORMATION pi{}; + check(CreateProcessW(nullptr, cb.data(), nullptr, nullptr, FALSE, 0, nullptr, nullptr, &si, &pi), "start a copy of sleep with a long .exe name"); + std::wstring seen = L""; + HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); + PROCESSENTRY32W pe{}; pe.dwSize = sizeof(pe); + for (BOOL ok = Process32FirstW(snap, &pe); ok; ok = Process32NextW(snap, &pe)) if (pe.th32ProcessID == pi.dwProcessId) seen = pe.szExeFile; + CloseHandle(snap); + check(seen == L"a-program-with-a-long-name.exe", "the snapshot shows the whole name, not the kernel's 15 characters"); + wchar_t path[MAX_PATH * 2]; DWORD n = (DWORD)(sizeof(path) / sizeof(path[0])); + HANDLE op = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pi.dwProcessId); + const bool got = op && QueryFullProcessImageNameW(op, 0, path, &n); + check(got && std::wstring(path) == winForm, "the image path is the Z:\\ form of the file"); + check(got && _wcsicmp(path, winForm.c_str()) == 0, "and it equals the path the caller holds (the GameRunning comparison)"); + if (op) CloseHandle(op); + TerminateProcess(pi.hProcess, 1); + WaitForSingleObject(pi.hProcess, 5000); + CloseHandle(pi.hProcess); CloseHandle(pi.hThread); +} + +void Suspended() { + std::wstring cmd = L"sleep 5"; + std::vector cb(cmd.begin(), cmd.end()); cb.push_back(0); + STARTUPINFOW si{}; si.cb = sizeof(si); + PROCESS_INFORMATION pi{}; + check(CreateProcessW(nullptr, cb.data(), nullptr, nullptr, FALSE, CREATE_SUSPENDED, nullptr, nullptr, &si, &pi), "start sleep suspended"); + check(StateOf((int)pi.dwProcessId) == 'T', "a suspended process is stopped before it runs"); + check(ResumeThread(pi.hThread) == 1, "ResumeThread: the previous suspend count was 1"); + char st = 'T'; + for (int i = 0; i < 100 && (st = StateOf((int)pi.dwProcessId)) == 'T'; ++i) Sleep(10); + check(st != 'T', "and it runs after ResumeThread"); + check(ResumeThread(pi.hThread) == 0, "a second ResumeThread: count 0"); + check(ResumeThread(nullptr) == (DWORD)-1, "ResumeThread of a bad handle: -1"); + TerminateProcess(pi.hProcess, 1); + WaitForSingleObject(pi.hProcess, 5000); + CloseHandle(pi.hProcess); CloseHandle(pi.hThread); +} + +// ---- a process started suspended: failures at the call, no inherited files, its own image, no signal handlers -------------- +std::string PosixTmp() { + std::string dir(Tmp.begin() + 2, Tmp.end()); + for (auto& c : dir) if (c == '\\') c = '/'; + return dir; +} +std::string ExeOf(int pid) { + char link[4096]; + const ssize_t n = readlink(("/proc/" + std::to_string(pid) + "/exe").c_str(), link, sizeof(link) - 1); + return n < 0 ? std::string() : std::string(link, (size_t)n); +} +// a copy of sleep with a name of its own, so that it is not the test's own image; the path as the kernel spells it +std::string CopyOfSleep(const char* name) { + const std::string path = PosixTmp() + "/" + name; + std::error_code ec; + std::filesystem::copy_file("/bin/sleep", path, std::filesystem::copy_options::overwrite_existing, ec); + chmod(path.c_str(), 0755); + return std::filesystem::canonical(path, ec).string(); +} +void EndProcess(PROCESS_INFORMATION& pi) { + TerminateProcess(pi.hProcess, 1); + WaitForSingleObject(pi.hProcess, 5000); + CloseHandle(pi.hProcess); CloseHandle(pi.hThread); +} +std::vector Cmd(const std::wstring& s) { std::vector v(s.begin(), s.end()); v.push_back(0); return v; } + +extern "C" void HangingHandler(int) { for (;;) pause(); } // stands for a handler that waits for a lock another thread holds + +void SuspendedStart() { + STARTUPINFOW si{}; si.cb = sizeof(si); + PROCESS_INFORMATION pi{}; + + // early failures come back from the call, as they do without CREATE_SUSPENDED + auto bare = Cmd(L"no-such-program-in-any-path-folder 1"); + check(!CreateProcessW(nullptr, bare.data(), nullptr, nullptr, FALSE, CREATE_SUSPENDED, nullptr, nullptr, &si, &pi) && GetLastError() == ERROR_FILE_NOT_FOUND, + "suspended: a program that is not in PATH: file not found"); + check(!CreateProcessW(nullptr, bare.data(), nullptr, nullptr, FALSE, 0, nullptr, nullptr, &si, &pi) && GetLastError() == ERROR_FILE_NOT_FOUND, + "not suspended: the same"); + const std::string notElf = PosixTmp() + "/not-an-elf-file"; + Put(In(L"not-an-elf-file"), "just some text, no program\n"); + chmod(notElf.c_str(), 0755); + auto ne = Cmd(In(L"not-an-elf-file")); + check(!CreateProcessW(nullptr, ne.data(), nullptr, nullptr, FALSE, 0, nullptr, nullptr, &si, &pi) && GetLastError() == ERROR_BAD_EXE_FORMAT, + "not suspended: a file that is no program: bad exe format"); + check(!CreateProcessW(nullptr, ne.data(), nullptr, nullptr, FALSE, CREATE_SUSPENDED, nullptr, nullptr, &si, &pi) && GetLastError() == ERROR_BAD_EXE_FORMAT, + "suspended: the same"); + const std::string plain = PosixTmp() + "/not-executable"; + Put(In(L"not-executable"), "\x7f" "ELF"); + chmod(plain.c_str(), 0644); + auto nx = Cmd(In(L"not-executable")); + check(!CreateProcessW(nullptr, nx.data(), nullptr, nullptr, FALSE, 0, nullptr, nullptr, &si, &pi) && GetLastError() == ERROR_ACCESS_DENIED, + "not suspended: a file without the execute bit: access denied"); + check(!CreateProcessW(nullptr, nx.data(), nullptr, nullptr, FALSE, CREATE_SUSPENDED, nullptr, nullptr, &si, &pi) && GetLastError() == ERROR_ACCESS_DENIED, + "suspended: the same"); + + // the stopped child holds none of the parent's close-on-exec files + int fds[2]; + check(pipe2(fds, O_CLOEXEC) == 0, "a close-on-exec pipe"); + auto sl = Cmd(L"sleep 30"); + check(CreateProcessW(nullptr, sl.data(), nullptr, nullptr, FALSE, CREATE_SUSPENDED, nullptr, nullptr, &si, &pi), "start sleep suspended, a pipe open"); + close(fds[1]); + struct pollfd pf = {fds[0], POLLIN, 0}; + const int ready = poll(&pf, 1, 1000); + check(StateOf((int)pi.dwProcessId) == 'T', "the child is still stopped"); + check(ready == 1 && (pf.revents & POLLHUP), "the reader sees the writer gone while the child is stopped (the child did not keep the write end)"); + close(fds[0]); + EndProcess(pi); + + // while stopped, the program is the target, not the parent + const std::string real = CopyOfSleep("suspended-target-with-a-long-name.exe"); + auto tc = Cmd(L"\"" + In(L"suspended-target-with-a-long-name.exe") + L"\" 30"); + check(CreateProcessW(nullptr, tc.data(), nullptr, nullptr, FALSE, CREATE_SUSPENDED, nullptr, nullptr, &si, &pi), "start a copy of sleep suspended"); + wchar_t path[MAX_PATH * 2]; DWORD n = (DWORD)(sizeof(path) / sizeof(path[0])); + const bool got = QueryFullProcessImageNameW(pi.hProcess, 0, path, &n); + check(got && std::wstring(path) == WinOf(real), "stopped: the image path is the target's Z:\\ path"); + std::wstring seen = L""; + HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); + PROCESSENTRY32W pe{}; pe.dwSize = sizeof(pe); + for (BOOL ok = Process32FirstW(snap, &pe); ok; ok = Process32NextW(snap, &pe)) if (pe.th32ProcessID == pi.dwProcessId) seen = pe.szExeFile; + CloseHandle(snap); + check(seen == L"suspended-target-with-a-long-name.exe", "stopped: the snapshot name is the target's name"); + ResumeThread(pi.hThread); + for (int i = 0; i < 300 && ExeOf((int)pi.dwProcessId) != real; ++i) Sleep(10); + n = (DWORD)(sizeof(path) / sizeof(path[0])); + check(ExeOf((int)pi.dwProcessId) == real && QueryFullProcessImageNameW(pi.hProcess, 0, path, &n) && std::wstring(path) == WinOf(real), "resumed: the same answer"); + EndProcess(pi); + + // a signal that a handler of the parent would catch does not run that handler in the stopped child + struct sigaction sa{}, old{}; + sa.sa_handler = HangingHandler; + sigemptyset(&sa.sa_mask); + sigaction(SIGUSR1, &sa, &old); + check(CreateProcessW(nullptr, tc.data(), nullptr, nullptr, FALSE, CREATE_SUSPENDED, nullptr, nullptr, &si, &pi), "start it again with a handler installed"); + kill((int)pi.dwProcessId, SIGUSR1); + ResumeThread(pi.hThread); + bool ended = false, execd = false; + for (int i = 0; i < 300 && !ended && !execd; ++i) { + ended = WaitForSingleObject(pi.hProcess, 0) == WAIT_OBJECT_0; + execd = ExeOf((int)pi.dwProcessId) == real; + if (!ended && !execd) Sleep(10); + } + check(ended || execd, "SIGUSR1 while stopped: the child ends or runs the target, it does not stay in the parent's image"); + sigaction(SIGUSR1, &old, nullptr); + EndProcess(pi); +} + +void CaseFolding() { + check(Put(In(L"\u00C9.txt"), "e"), "create \xC3\x89.txt"); + check(GetFileAttributesW(In(L"\u00E9.txt").c_str()) != INVALID_FILE_ATTRIBUTES, "GetFileAttributesW finds it spelled with the lower-case letter"); + WIN32_FIND_DATAW fd; + HANDLE f = FindFirstFileW(In(L"\u00E9.txt").c_str(), &fd); + check(f != INVALID_HANDLE_VALUE && std::wstring(fd.cFileName) == L"\u00C9.txt", "FindFirstFileW finds it by the lower-case name"); + if (f != INVALID_HANDLE_VALUE) FindClose(f); + f = FindFirstFileW(In(L"\u00E9*").c_str(), &fd); + check(f != INVALID_HANDLE_VALUE, "and by a wildcard"); + if (f != INVALID_HANDLE_VALUE) FindClose(f); + check(CompareStringOrdinal(L"\u00C9", 1, L"\u00E9", 1, TRUE) == CSTR_EQUAL, "CompareStringOrdinal ignores the case of an accented letter"); + check(CompareStringOrdinal(L"\u00C9", 1, L"\u00E9", 1, FALSE) != CSTR_EQUAL, "and not when asked to be exact"); + check(_wcsicmp(L"\u00C9", L"\u00E9") == 0 && _wcsnicmp(L"\u00C9x", L"\u00E9y", 1) == 0, "_wcsicmp and _wcsnicmp too"); +} + +void RegistryWrites() { + // a hive whose file cannot be written: its folder is a regular file + Put(In(L"not-a-folder"), "x"); + HKEY h = nullptr, key = nullptr; + check(RegLoadAppKeyW(In(L"not-a-folder\\hive.dat").c_str(), &h, KEY_ALL_ACCESS, 0, 0) == ERROR_SUCCESS, "load a hive whose file cannot be written"); + const LSTATUS c = RegCreateKeyExW(h, L"K", 0, nullptr, 0, KEY_ALL_ACCESS, nullptr, &key, nullptr); + check(c != ERROR_SUCCESS, "creating a key that cannot be saved fails"); + check(RegOpenKeyExW(h, L"K", 0, KEY_READ, &key) != ERROR_SUCCESS, "and the key is not kept in memory"); + // the value case on a key that exists in memory only because the load made the root + check(RegSetValueExW(h, L"v", 0, REG_SZ, (const BYTE*)L"x", 4) != ERROR_SUCCESS, "setting a value that cannot be saved fails"); + wchar_t buf[8]{}; DWORD sz = sizeof(buf); + check(RegQueryValueExW(h, L"v", nullptr, nullptr, (LPBYTE)buf, &sz) == ERROR_FILE_NOT_FOUND, "and a fresh read does not see it"); + RegCloseKey(h); + // the error code is the one for the cause: a read-only folder is access denied + if (geteuid() != 0) { + const std::string dir(Tmp.begin() + 2, Tmp.end()); + std::string d = dir; for (auto& ch : d) if (ch == '\\') ch = '/'; + mkdir((d + "/ro").c_str(), 0755); + HKEY r = nullptr; + check(RegLoadAppKeyW(In(L"ro\\hive.dat").c_str(), &r, KEY_ALL_ACCESS, 0, 0) == ERROR_SUCCESS, "load a hive in a folder"); + chmod((d + "/ro").c_str(), 0555); + check(RegSetValueExW(r, L"v", 0, REG_SZ, (const BYTE*)L"x", 4) == ERROR_ACCESS_DENIED, "a read-only folder: access denied"); + RegCloseKey(r); + chmod((d + "/ro").c_str(), 0755); + } +} + +void FinishedChildren() { + std::wstring cmd = L"true"; + std::vector cb(cmd.begin(), cmd.end()); cb.push_back(0); + STARTUPINFOW si{}; si.cb = sizeof(si); + PROCESS_INFORMATION pi{}; + CreateProcessW(nullptr, cb.data(), nullptr, nullptr, FALSE, 0, nullptr, nullptr, &si, &pi); + WaitForSingleObject(pi.hProcess, 5000); + wgposix::ChildState c; + check(wgposix::PollChild((int)pi.dwProcessId, c) && c.exited, "a finished child is known while its handle is open"); + CloseHandle(pi.hProcess); CloseHandle(pi.hThread); + check(!wgposix::PollChild((int)pi.dwProcessId, c), "and forgotten once its handle is closed"); + wchar_t* msg = nullptr; + check(FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER, nullptr, ERROR_INVALID_NAME, 0, (LPWSTR)&msg, 0, nullptr) > 0, "FormatMessageW has text for ERROR_INVALID_NAME"); + std::free(msg); +} + +void NotAvailable() { + check(LoadLibraryExW(L"dxgi.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32) == nullptr && GetLastError() == ERROR_MOD_NOT_FOUND, "no Windows DLL loads"); + check(GetModuleHandleW(L"nothere.dll") == nullptr && GetProcAddress(GetModuleHandleW(L"nothere.dll"), "RtlGetVersion") == nullptr, + "and GetProcAddress of a missing module is null"); + // the one module that answers: ntdll's RtlGetVersion says Windows 10 (what a Proton prefix reports), no other export exists + typedef LONG(WINAPI * RtlGetVersionFn)(OSVERSIONINFOW*); + RtlGetVersionFn rtl = reinterpret_cast(GetProcAddress(GetModuleHandleW(L"NTDLL.DLL"), "RtlGetVersion")); + OSVERSIONINFOW ver{}; ver.dwOSVersionInfoSize = sizeof(ver); + check(rtl && rtl(&ver) == 0 && ver.dwMajorVersion == 10 && ver.dwBuildNumber >= 10240, "ntdll's RtlGetVersion reports Windows 10"); + check(GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "NtCreateFile") == nullptr, "and ntdll has no other export"); + check(FindResourceW(nullptr, MAKEINTRESOURCEW(900), MAKEINTRESOURCEW(10)) == nullptr && LockResource(LoadResource(nullptr, nullptr)) == nullptr && + SizeofResource(nullptr, nullptr) == 0, "a program with no embedded resources finds none (this one links no payload table)"); + check(WinHttpOpen(L"x", WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY, nullptr, nullptr, 0) == nullptr, "WinHTTP does not open"); + IShellLinkW* sl = nullptr; + check(FAILED(CoCreateInstance(CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER, IID_IShellLinkW, (void**)&sl)) && !sl, "no shell link object"); + SHELLEXECUTEINFOW sei{}; sei.cbSize = sizeof(sei); sei.lpFile = L"Z:\\bin\\Game.exe"; sei.lpVerb = L"open"; + check(!ShellExecuteExW(&sei) && GetLastError() == ERROR_NOT_SUPPORTED, "ShellExecuteExW does not start a Windows program"); + + URL_COMPONENTS uc{}; uc.dwStructSize = sizeof(uc); + wchar_t host[64]{}, path[64]{}; + uc.lpszHostName = host; uc.dwHostNameLength = 64; uc.lpszUrlPath = path; uc.dwUrlPathLength = 64; + check(WinHttpCrackUrl(L"https://example.org:8443/a/b?c=1", 0, 0, &uc) && uc.nScheme == INTERNET_SCHEME_HTTPS && uc.nPort == 8443 && std::wstring(host) == L"example.org" && std::wstring(path) == L"/a/b", "WinHttpCrackUrl: scheme, host, port, path"); + URL_COMPONENTS bad{}; bad.dwStructSize = sizeof(bad); + check(!WinHttpCrackUrl(L"ftp://example.org/", 0, 0, &bad), "WinHttpCrackUrl: another scheme is refused"); +} + +// S1: the native launcher names its graphics card from Linux's device list (no DXGI here). A made-up /sys/class/drm with the +// `driver` link a real card has; every card of the folder is looked at, the AMD RDNA 4 one wins. +void GpuIdentity() { + check(wg::NativeLinux(), "NativeLinux: this layer's ntdll carries the marker"); + const wg::WinInfo sys = wg::WindowsInfo(); + check(sys.label == L"Linux" && sys.ok && !sys.text.empty() && sys.text.find(L"Windows") == std::wstring::npos, "WindowsInfo natively: Linux, the distribution, never a Windows version"); + std::string posixTmp(Tmp.begin(), Tmp.end()); + posixTmp.erase(0, 2); + for (auto& c : posixTmp) if (c == '\\') c = '/'; + const std::filesystem::path root = std::filesystem::path(posixTmp) / "gpu-drm"; + std::filesystem::create_directories(root / "drivers" / "amdgpu"); + std::filesystem::create_directories(root / "drivers" / "i915"); + auto card = [&](const char* name, const char* vendor, const char* device, const char* driver) { + const auto d = root / "drm" / name / "device"; + std::filesystem::create_directories(d); + std::FILE* f = std::fopen((d / "vendor").c_str(), "w"); std::fputs(vendor, f); std::fclose(f); + f = std::fopen((d / "device").c_str(), "w"); std::fputs(device, f); std::fclose(f); + if (driver) std::filesystem::create_directory_symlink(root / "drivers" / driver, d / "driver"); + }; + const std::wstring drm = Tmp + L"\\gpu-drm\\drm"; + check(wg::GpuFromDrm(drm).name.empty() && !wg::GpuFromDrm(drm).amd, "no cards: no GPU"); + card("card0", "0x8086\n", "0x46a6\n", "i915"); // an Intel iGPU + wg::GpuInfo g = wg::GpuFromDrm(drm); + check(!g.amd && !g.rdna4 && g.name == L"Intel graphics (code 8086:46A6)" && g.driver == L"i915", "Intel only: named by code, driver i915, not AMD"); + card("card1", "0x1002\n", "0x744c\n", "amdgpu"); // an RX 7900 XTX (RDNA 3) + g = wg::GpuFromDrm(drm); + check(g.amd && !g.rdna4 && g.name == L"AMD Radeon (code 1002:744C)" && g.driver == L"amdgpu", "RDNA 3: AMD, not RDNA 4, by code, driver amdgpu"); + card("card2", "0x1002\n", "0x7550\n", "amdgpu"); // an RX 9070 XT + g = wg::GpuFromDrm(drm); + check(g.amd && g.rdna4 && g.name == L"AMD Radeon RX 9070 XT" && g.driver == L"amdgpu", "RDNA 4 after an earlier non-RDNA 4 card: it wins, named, driver amdgpu"); + card("card3", "0x1002\n", "0x7590\n", nullptr); // a second RDNA 4 card without a driver link: the first stays + g = wg::GpuFromDrm(drm); + check(g.rdna4 && g.name == L"AMD Radeon RX 9070 XT", "two RDNA 4 cards: the lower number stays"); + card("card4-DP-1", "0x1002\n", "0x7551\n", nullptr); // a connector, ignored + card("card5", "garbage", "0x7551\n", nullptr); // unreadable ids: skipped + check(wg::GpuFromDrm(drm).name == L"AMD Radeon RX 9070 XT", "connectors and unreadable cards are ignored"); + // a file the system will not let this program open (a different failure from garbage text): that card is skipped, the search goes on + card("card6", "0x1002\n", "0x7550\n", nullptr); + std::filesystem::permissions(root / "drm" / "card6" / "device" / "vendor", std::filesystem::perms::none); + check(wg::GpuFromDrm(drm).name == L"AMD Radeon RX 9070 XT", "a card whose vendor file cannot be opened is skipped, not fatal"); + const std::wstring lonely = Tmp + L"\\gpu-drm\\unreadable"; + { + const auto d = root / "unreadable" / "card0" / "device"; + std::filesystem::create_directories(d); + std::FILE* f = std::fopen((d / "vendor").c_str(), "w"); std::fputs("0x1002\n", f); std::fclose(f); + f = std::fopen((d / "device").c_str(), "w"); std::fputs("0x7550\n", f); std::fclose(f); + std::filesystem::permissions(d / "device", std::filesystem::perms::none); + } + check(wg::GpuFromDrm(lonely).name.empty() && !wg::GpuFromDrm(lonely).amd && !wg::GpuFromDrm(lonely).rdna4, "the only card has an unreadable device file: no GPU, no crash"); + std::filesystem::permissions(root / "unreadable" / "card0" / "device" / "device", std::filesystem::perms::owner_all); + check(wg::GpuFromDrm(lonely).rdna4, "...and the same card with the file readable again is the RDNA 4 card (the probe can show the card)"); + std::filesystem::permissions(root / "drm" / "card6" / "device" / "vendor", std::filesystem::perms::owner_all); + std::filesystem::remove_all(root / "drm" / "card6"); + card("card10", "0x10de\n", "0x2684\n", nullptr); // NVIDIA + check(wg::GpuFromDrm(drm).rdna4, "an NVIDIA card does not displace it"); + std::filesystem::remove_all(root / "drm" / "card2"); + std::filesystem::remove_all(root / "drm" / "card3"); + g = wg::GpuFromDrm(drm); + check(g.amd && !g.rdna4 && g.name == L"AMD Radeon (code 1002:744C)", "without the RDNA 4 cards, the first AMD card is chosen over NVIDIA"); + const std::wstring nvOnly = Tmp + L"\\gpu-drm\\nv"; + { + const auto d = root / "nv" / "card0" / "device"; + std::filesystem::create_directories(d); + std::FILE* f = std::fopen((d / "vendor").c_str(), "w"); std::fputs("0x10de\n", f); std::fclose(f); + f = std::fopen((d / "device").c_str(), "w"); std::fputs("0x2684\n", f); std::fclose(f); + } + g = wg::GpuFromDrm(nvOnly); + check(!g.amd && !g.rdna4 && g.name == L"NVIDIA graphics (code 10DE:2684)" && g.driver.empty(), "NVIDIA only: not AMD, no driver link: driver unknown"); + // DetectGpu on this machine follows Linux's own list: it must agree with GpuFromDrm() on /sys/class/drm + unsetenv("WRONGGPU_TEST_DRM_ROOT"); + const wg::GpuInfo here = wg::DetectGpu(), direct = wg::GpuFromDrm(); + check(here.name == direct.name && here.rdna4 == direct.rdna4 && here.amd == direct.amd, "DetectGpu natively is GpuFromDrm of /sys/class/drm"); + // a test build can point DetectGpu at a made-up folder (the UI tests and the screenshots use it) + setenv("WRONGGPU_TEST_DRM_ROOT", "Z:\\nonexistent-drm-root", 1); + check(wg::DetectGpu().name.empty(), "WRONGGPU_TEST_DRM_ROOT: a folder with no cards is no GPU"); + std::string r1 = posixTmp + "/gpu-drm/nv"; + setenv("WRONGGPU_TEST_DRM_ROOT", r1.c_str(), 1); + check(wg::DetectGpu().name == L"NVIDIA graphics (code 10DE:2684)", "WRONGGPU_TEST_DRM_ROOT: DetectGpu reads that folder"); + unsetenv("WRONGGPU_TEST_DRM_ROOT"); + // the toolbar names Direct3D 12 the way the first-run sheet does: through Proton, natively + wg::GpuInfo r4; + r4.amd = true; r4.rdna4 = true; + wg::GpuInfo r3; + r3.amd = true; + check(wg::GpuToolbarLine(L"RX 9070 XT", r4) == L"RX 9070 XT (detected) \u00b7 Direct3D 12 (through Proton)", "toolbar: an RDNA 4 card on Linux says Direct3D 12 (through Proton)"); + check(wg::GpuToolbarLine(L"RX 7900 XT", r3) == L"RX 7900 XT (detected) \u00b7 " + wg::NeedsRx9000Sentence(), "toolbar: a card that is not RDNA 4 keeps the FSR sentence"); + check(wg::GpuToolbarLine(L"", r4) == L"No graphics card detected \u00b7 " + wg::NeedsRx9000Sentence(), "toolbar: no card keeps its sentence"); +} + +// S5: which file the native launcher will delete as its own AppImage: every refusal, and the one yes. The system's process folder is +// a made-up tree (WRONGGPU_TEST_PROC_ROOT) with the entries the AppImage runtime's mount has for real: a mount table line for $APPDIR, +// a process started from the AppImage file, and that process's /dev/fuse descriptor naming the mount's connection. +void AppImageIdentity() { + std::string posixTmp(Tmp.begin(), Tmp.end()); + posixTmp.erase(0, 2); + for (auto& c : posixTmp) if (c == '\\') c = '/'; + const std::filesystem::path dir = std::filesystem::path(posixTmp) / "appimage"; + std::filesystem::create_directories(dir); + auto make = [&](const char* name, const char* head16) { + std::FILE* f = std::fopen((dir / name).c_str(), "wb"); + std::fwrite(head16, 1, 16, f); std::fputs("payload", f); std::fclose(f); + return (dir / name).string(); + }; + const char good[17] = "\x7f" "ELF\x02\x01\x01\x00" "AI\x02\x00\x00\x00\x00\x00"; + const char plainElf[17] = "\x7f" "ELF\x02\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00"; + const std::string app = std::filesystem::canonical(make("WrongGPU-0.6.5-x86_64.AppImage", good)).string(); + const std::wstring selfW = wg::SelfPath(); // "Z:\\home\\...\\posix-layer-tests" + std::string selfHost(selfW.begin(), selfW.end()); + selfHost.erase(0, 2); + for (auto& c : selfHost) if (c == '\\') c = '/'; + const std::string appdir = std::filesystem::canonical(std::filesystem::path(selfHost).parent_path()).string(); // this test program stands in for the program inside the AppImage's mount + struct stat dst{}; + stat(appdir.c_str(), &dst); + const unsigned devMajor = major(dst.st_dev), devMinor = minor(dst.st_dev); + const std::filesystem::path proc = dir / "proc"; + auto put = [&](const std::filesystem::path& f, const std::string& text) { + std::filesystem::create_directories(f.parent_path()); + std::FILE* o = std::fopen(f.c_str(), "wb"); std::fputs(text.c_str(), o); std::fclose(o); + }; + // the mount table and the process list as the real ones read after the runtime mounted $APPDIR + auto system = [&](const std::string& point, const std::string& fstype, unsigned connection, const std::string& serverExe, bool server = true) { + std::filesystem::remove_all(proc); + std::string esc; + for (char c : point) esc += c == ' ' ? std::string("\\040") : std::string(1, c); + put(proc / "self" / "mountinfo", "22 1 0:5 / /sys rw - sysfs sysfs rw\n" + std::to_string(1003) + " 60 " + std::to_string(devMajor) + ":" + std::to_string(devMinor) + + " / " + esc + " ro,nosuid,nodev,relatime shared:1453 - " + fstype + " WrongGPU-0.6.5-x86_64.AppImage ro,user_id=1000,group_id=1000\n"); + put(proc / "1" / "fdinfo" / "0", "pos:\t0\nflags:\t0100002\nmnt_id:\t43\nino:\t4\n"); + std::filesystem::create_directories(proc / "1"); + std::filesystem::create_symlink("/usr/bin/true", proc / "1" / "exe"); + if (server) { + std::filesystem::create_directories(proc / "4242"); + std::filesystem::create_symlink(serverExe, proc / "4242" / "exe"); + put(proc / "4242" / "fdinfo" / "3", "pos:\t0\nflags:\t0100000\nmnt_id:\t60\nino:\t60675985\n"); + put(proc / "4242" / "fdinfo" / "5", "pos:\t0\nflags:\t02100002\nmnt_id:\t43\nino:\t136\nfuse_connection:\t" + std::to_string(connection) + "\n"); + } + }; + setenv("WRONGGPU_TEST_PROC_ROOT", proc.c_str(), 1); + std::wstring file, why; + auto env = [&](const char* image, const char* appDir) { + if (image) setenv("APPIMAGE", image, 1); else unsetenv("APPIMAGE"); + if (appDir) setenv("APPDIR", appDir, 1); else unsetenv("APPDIR"); + }; + auto refused = [&](const wchar_t* words) { file.clear(); why.clear(); return !wg::OwnAppImage(file, &why) && file.empty() && why.find(words) != std::wstring::npos; }; + system(appdir, "fuse.WrongGPU-0.6.5-x86_64.AppImage", devMinor, app); + env(nullptr, appdir.c_str()); + check(refused(L"not running from an AppImage"), "OwnAppImage: no $APPIMAGE is refused in words"); + env((dir / "missing.AppImage").c_str(), appdir.c_str()); + check(refused(L"not a plain file"), "OwnAppImage: a file that is not there is refused"); + env(dir.c_str(), appdir.c_str()); + check(refused(L"not a plain file"), "OwnAppImage: a folder is refused"); + std::filesystem::create_symlink(app, dir / "WrongGPU-link.AppImage"); + env((dir / "WrongGPU-link.AppImage").c_str(), appdir.c_str()); + check(refused(L"not a plain file"), "OwnAppImage: a link to the AppImage is refused (the link is not the file)"); + env(make("notes.AppImage", good).c_str(), appdir.c_str()); + check(refused(L"not WrongGPU"), "OwnAppImage: another name is refused"); + env(make("WrongGPU.txt", good).c_str(), appdir.c_str()); + check(refused(L"not WrongGPU"), "OwnAppImage: a name without .AppImage is refused"); + env(make("WrongGPU-plain.AppImage", plainElf).c_str(), appdir.c_str()); + check(refused(L"not an AppImage file"), "OwnAppImage: an ELF file without the AppImage mark is refused"); + env(app.c_str(), nullptr); + check(refused(L"not inside"), "OwnAppImage: no $APPDIR: this program is not inside it"); + env(app.c_str(), (dir / "elsewhere").c_str()); + check(refused(L"not inside"), "OwnAppImage: this program is not under $APPDIR"); + // the case of the folder is the disk's: a Linux disk tells "Appimage" from "appimage" + std::string upper = appdir; + for (auto& c : upper) c = (char)std::toupper((unsigned char)c); + env(app.c_str(), upper.c_str()); + check(upper != appdir && refused(L"not inside"), "OwnAppImage: $APPDIR in another letter case is not the folder (no case-insensitive test)"); + env(app.c_str(), appdir.c_str()); + file.clear(); + const std::string expected = "Z:" + [&] { std::string s = app; for (auto& c : s) if (c == '/') c = '\\'; return s; }(); + check(wg::OwnAppImage(file, &why) && std::string(file.begin(), file.end()) == expected, + "OwnAppImage: the file named by $APPIMAGE, a plain AppImage called WrongGPU...AppImage, this program inside its $APPDIR, a mount served by a process started from that file: yes"); + // $APPDIR given through a link is the same folder + std::filesystem::create_directory_symlink(appdir, dir / "appdir-link"); + env(app.c_str(), (dir / "appdir-link").c_str()); + check(wg::OwnAppImage(file, &why), "OwnAppImage: $APPDIR through a link is the folder the link leads to"); + env(app.c_str(), appdir.c_str()); + // a valid WrongGPU...AppImage elsewhere, with the real current $APPDIR: the mount is not served from that file + const std::string old = make("WrongGPU-old.AppImage", good); + env(old.c_str(), appdir.c_str()); + check(refused(L"cannot prove"), "OwnAppImage: a valid WrongGPU AppImage that is not the running one (the real $APPDIR) is refused"); + // the same bytes in another file are not the file either (the identity is the disk's, not the content) + std::filesystem::copy_file(app, dir / "WrongGPU-copy.AppImage", std::filesystem::copy_options::overwrite_existing); + env((dir / "WrongGPU-copy.AppImage").c_str(), appdir.c_str()); + check(refused(L"cannot prove"), "OwnAppImage: an identical copy of the running AppImage is refused"); + env(app.c_str(), appdir.c_str()); + // each part of the proof, taken away + system(appdir, "fuse.WrongGPU-0.6.5-x86_64.AppImage", devMinor, app, false); + check(refused(L"No process started from the file serves the mount"), "OwnAppImage: no process serves the mount: refused"); + system(appdir, "fuse.WrongGPU-0.6.5-x86_64.AppImage", devMinor + 1, app); + check(refused(L"No process started from the file serves the mount"), "OwnAppImage: a server for another mount (another connection number) is refused"); + system(appdir, "fuse.WrongGPU-0.6.5-x86_64.AppImage", devMinor * 10, app); + check(refused(L"No process started from the file serves the mount"), "OwnAppImage: connection 10 times the number is not the number"); + system(appdir, "ext4", devMinor, app); + check(refused(L"is not a mounted AppImage"), "OwnAppImage: $APPDIR that is not a FUSE mount is refused"); + system(appdir + "/x", "fuse.WrongGPU-0.6.5-x86_64.AppImage", devMinor, app); + check(refused(L"is not a mounted AppImage"), "OwnAppImage: a mount at another place is refused"); + system(appdir, "fuse.WrongGPU-0.6.5-x86_64.AppImage", devMinor, old); + check(refused(L"No process started from the file serves the mount"), "OwnAppImage: a server started from another file is refused"); + std::filesystem::remove_all(proc); + check(refused(L"is not a mounted AppImage"), "OwnAppImage: no process folder to read: refused (fail closed)"); + system(appdir, "fuse.WrongGPU-0.6.5-x86_64.AppImage", devMinor + 7, app); + std::filesystem::permissions(proc / "4242" / "fdinfo" / "5", std::filesystem::perms::none); + check(refused(L"No process started from the file serves the mount"), "OwnAppImage: an unreadable descriptor entry is a refusal, not a yes"); + std::filesystem::permissions(proc / "4242" / "fdinfo" / "5", std::filesystem::perms::owner_all); + system(appdir, "fuse.WrongGPU-0.6.5-x86_64.AppImage", devMinor, app); + check(wg::OwnAppImage(file, &why), "OwnAppImage: the proof back in place: yes again"); + + // the removal itself: the file goes first, after a fresh look; then the data + const std::filesystem::path local = dir / "local", data = local / "WrongGPU"; + setenv("LOCALAPPDATA", local.c_str(), 1); + wg::Context ctx; + ctx.logFile = Tmp + L"\\appimage-removal.log"; + auto fresh = [&] { + std::filesystem::remove_all(local); + std::filesystem::remove(app); // (a link left in its place by the last case is not written through) + make("WrongGPU-0.6.5-x86_64.AppImage", good); + system(appdir, "fuse.WrongGPU-0.6.5-x86_64.AppImage", devMinor, app); + put(data / "launcher.ini", "[settings]\r\n"); + put(data / "model" / "M" / "model.wgcm", "converted data"); + }; + auto there = [&](const std::filesystem::path& f) { return std::filesystem::exists(f); }; + env(app.c_str(), appdir.c_str()); + { + fresh(); + std::wstring gone, kept; + check(wg::UninstallAppImage(ctx, &why, &gone, &kept) && !there(app) && !there(data) && std::string(gone.begin(), gone.end()) == expected, + "UninstallAppImage: the proven file and the data folder go"); + } + { // a replacement renamed into the path between the check and the delete: it is another file now + fresh(); + make("WrongGPU-replacement.AppImage", good); + wg::SetFaultHook([&](const char* s) { + if (std::string(s) == "appimage-before-delete") std::filesystem::rename(dir / "WrongGPU-replacement.AppImage", app); + return false; + }); + std::wstring gone; + const bool ok = wg::UninstallAppImage(ctx, &why, &gone); + wg::SetFaultHook(nullptr); + check(!ok && gone.empty() && why.find(L"changed while WrongGPU was checking it") != std::wstring::npos && there(app) && there(data / "model" / "M" / "model.wgcm"), + "UninstallAppImage: a file renamed into the path after the check is refused; it and the data folder stay"); + } + { // a plain file with no AppImage header put there is refused too + fresh(); + wg::SetFaultHook([&](const char* s) { + if (std::string(s) == "appimage-before-delete") { std::filesystem::remove(app); make("WrongGPU-0.6.5-x86_64.AppImage", plainElf); } + return false; + }); + const bool ok = wg::UninstallAppImage(ctx, &why); + wg::SetFaultHook(nullptr); + check(!ok && there(app) && there(data / "launcher.ini"), "UninstallAppImage: the path emptied and another file put there is refused; nothing is deleted"); + } + { // a link put in the path is refused (it is not the file) + fresh(); + make("WrongGPU-target.AppImage", good); + wg::SetFaultHook([&](const char* s) { + if (std::string(s) == "appimage-before-delete") { std::filesystem::remove(app); std::filesystem::create_symlink(dir / "WrongGPU-target.AppImage", app); } + return false; + }); + const bool ok = wg::UninstallAppImage(ctx, &why); + wg::SetFaultHook(nullptr); + check(!ok && there(dir / "WrongGPU-target.AppImage") && there(data / "launcher.ini"), "UninstallAppImage: a link put in the path is refused; its target and the data stay"); + } + { // the proof fails: nothing goes + fresh(); + env((dir / "WrongGPU-old.AppImage").c_str(), appdir.c_str()); + check(!wg::UninstallAppImage(ctx, &why) && there(dir / "WrongGPU-old.AppImage") && there(app) && there(data / "launcher.ini"), + "UninstallAppImage: not the running AppImage: the other file, the running one and the data all stay"); + env(app.c_str(), appdir.c_str()); + } + { // the data folder is a link: the link goes, what it leads to stays + fresh(); + std::filesystem::remove_all(data); + std::filesystem::create_directories(dir / "outside-data"); + put(dir / "outside-data" / "keep.txt", "keep"); + put(dir / "outside-data" / "launcher.ini", "[settings]\r\n"); + std::filesystem::create_directory_symlink(dir / "outside-data", data); + check(wg::UninstallAppImage(ctx, &why) && !there(app) && !std::filesystem::is_symlink(data) && !there(data) && there(dir / "outside-data" / "keep.txt") && + there(dir / "outside-data" / "launcher.ini"), "UninstallAppImage: a data folder that is a link: the link goes, its target and everything in it stay"); + } + { // links inside the data folder: unlinked, never followed + fresh(); + std::filesystem::create_directories(dir / "outside-nested"); + put(dir / "outside-nested" / "keep.txt", "keep"); + put(dir / "outside-file.txt", "keep"); + std::filesystem::create_directory_symlink(dir / "outside-nested", data / "model" / "linkdir"); + std::filesystem::create_symlink(dir / "outside-file.txt", data / "linkfile"); + check(wg::UninstallAppImage(ctx, &why) && !there(app) && !there(data) && there(dir / "outside-nested" / "keep.txt") && there(dir / "outside-file.txt"), + "UninstallAppImage: links inside the data folder are removed, their targets stay"); + } + unsetenv("APPIMAGE"); unsetenv("APPDIR"); unsetenv("WRONGGPU_TEST_PROC_ROOT"); unsetenv("LOCALAPPDATA"); +} + +// S6: nothing is downloaded on Linux, and what needs a download says so in words (no WinHTTP error, no wait) +void DownloadsOff() { + check(!wg::DownloadsAvailable(), "DownloadsAvailable: off in the native launcher"); + wg::Context ctx; + ctx.logFile = Tmp + L"\\downloads.log"; + const wg::EditionResult r = wg::GetEdition(ctx, Tmp + L"\\downloads-data", nullptr); + check(r.path.empty() && r.error.find(L"doesn't download anything on Linux") != std::wstring::npos && r.error.find(L"choose an OptiScaler file") != std::wstring::npos && + r.detail == L"downloads are off on Linux", "GetEdition: no download on Linux, the player's own OptiScaler is asked for"); + wg::GlobalSettings gs; + gs.updateCheck = true; + gs.updateUrl = L"https://example.org/releases/latest"; + const wg::UpdateInfo u = wg::CheckForUpdate(gs, L"0.6.5"); + check(!u.checked && !u.newer && u.message.find(L"on Linux") != std::wstring::npos && u.message.find(L"AppImage") != std::wstring::npos, "CheckForUpdate: no request on Linux, said in words"); +} + +void Folders() { + PWSTR p = nullptr; + check(SUCCEEDED(SHGetKnownFolderPath(FOLDERID_LocalAppData, 0, nullptr, &p)) && p && std::wstring(p).rfind(L"Z:\\", 0) == 0, "LocalAppData is a Z:\\ path"); + CoTaskMemFree(p); + check(GetEnvironmentVariableW(L"LOCALAPPDATA", nullptr, 0) > 0, "%LOCALAPPDATA% has a value even when the environment has none"); + SetEnvironmentVariableW(L"WgLayerVar", L"v1"); + wchar_t b[16]{}; + check(GetEnvironmentVariableW(L"WGLAYERVAR", b, 16) == 2 && std::wstring(b) == L"v1", "environment names ignore case"); + SetEnvironmentVariableW(L"WGLAYERVAR", nullptr); + check(GetEnvironmentVariableW(L"WgLayerVar", b, 16) == 0 && GetLastError() == ERROR_ENVVAR_NOT_FOUND, "a variable removed: not found"); +} +// Attributes, times, deleting and truncating through a handle (what the core's PinnedFile does to the files it owns). +ULONGLONG Q(const FILETIME& f) { return ((ULONGLONG)f.dwHighDateTime << 32) | f.dwLowDateTime; } +ULONGLONG FileTimeOfUnix(long long sec) { return (ULONGLONG)(sec + 11644473600LL) * 10000000ull; } +bool Exists(const std::wstring& p) { return GetFileAttributesW(p.c_str()) != INVALID_FILE_ATTRIBUTES; } +HANDLE OpenFor(const std::wstring& p, DWORD access, DWORD share = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE) { + return CreateFileW(p.c_str(), access, share, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); +} +BOOL SetDisposition(HANDLE h, DWORD flags) { + FILE_DISPOSITION_INFO_EX ex{flags}; + return SetFileInformationByHandle(h, FileDispositionInfoEx, &ex, sizeof(ex)); +} + +void ErrorValues() { + static_assert(ERROR_TOO_MANY_LINKS == 1142 && ERROR_FILE_CORRUPT == 1392 && ERROR_READ_FAULT == 30, "the Win32 values"); + static_assert(FileBasicInfo == 0 && FileDispositionInfo == 4 && FileDispositionInfoEx == 21, "the FILE_INFO_BY_HANDLE_CLASS values"); + static_assert(sizeof(FILE_BASIC_INFO) == 40, "FILE_BASIC_INFO is four 8-byte times and the attributes, padded to 8"); + check(true, "constants"); +} + +void BasicInfo() { + const std::wstring p = In(L"basic.txt"); + Put(p, "x"); + HANDLE h = OpenFor(p, GENERIC_READ | FILE_WRITE_ATTRIBUTES); + FILE_BASIC_INFO b{}; + b.FileAttributes = FILE_ATTRIBUTE_READONLY; + check(h != INVALID_HANDLE_VALUE && SetFileInformationByHandle(h, FileBasicInfo, &b, sizeof(b)), "basic info: read-only set through a handle"); + check((GetFileAttributesW(p.c_str()) & FILE_ATTRIBUTE_READONLY) != 0, " and the name reports it"); + FILE_BASIC_INFO got{}; + check(GetFileInformationByHandleEx(h, FileBasicInfo, &got, sizeof(got)) && (got.FileAttributes & FILE_ATTRIBUTE_READONLY), " and so does the handle"); + b.FileAttributes = 0; // 0: the attributes are left as they are + check(SetFileInformationByHandle(h, FileBasicInfo, &b, sizeof(b)) && (GetFileAttributesW(p.c_str()) & FILE_ATTRIBUTE_READONLY), "attributes of 0 change nothing"); + b.FileAttributes = FILE_ATTRIBUTE_NORMAL; + check(SetFileInformationByHandle(h, FileBasicInfo, &b, sizeof(b)) && !(GetFileAttributesW(p.c_str()) & FILE_ATTRIBUTE_READONLY), "FILE_ATTRIBUTE_NORMAL clears read-only"); + check(GetFileInformationByHandleEx(h, FileBasicInfo, &got, sizeof(got)) && !(got.FileAttributes & FILE_ATTRIBUTE_READONLY), " the handle sees it clear"); + // times: set, then 0 leaves them + std::memset(&b, 0, sizeof(b)); + b.LastWriteTime.QuadPart = (LONGLONG)FileTimeOfUnix(1000000000); + b.LastAccessTime.QuadPart = (LONGLONG)FileTimeOfUnix(1000000500); + check(SetFileInformationByHandle(h, FileBasicInfo, &b, sizeof(b)), "basic info: times set"); + FILETIME ca{}, ac{}, wr{}; + check(GetFileTime(h, &ca, &ac, &wr) && Q(wr) == FileTimeOfUnix(1000000000) && Q(ac) == FileTimeOfUnix(1000000500), " the write and access times are what was set"); + check(GetFileInformationByHandleEx(h, FileBasicInfo, &got, sizeof(got)) && (ULONGLONG)got.LastWriteTime.QuadPart == FileTimeOfUnix(1000000000), " and basic info reads the write time back"); + std::memset(&b, 0, sizeof(b)); + b.LastWriteTime.QuadPart = (LONGLONG)FileTimeOfUnix(1000001000); // access time 0: unchanged + check(SetFileInformationByHandle(h, FileBasicInfo, &b, sizeof(b)) && GetFileTime(h, &ca, &ac, &wr) && Q(wr) == FileTimeOfUnix(1000001000) && Q(ac) == FileTimeOfUnix(1000000500), + "a time of 0 is left unchanged"); + std::memset(&b, 0, sizeof(b)); + check(SetFileInformationByHandle(h, FileBasicInfo, &b, sizeof(b)) && GetFileTime(h, &ca, &ac, &wr) && Q(wr) == FileTimeOfUnix(1000001000), "an all-zero basic info changes nothing"); + check(!GetFileInformationByHandleEx(h, FileBasicInfo, &got, sizeof(got) - 8) && GetLastError() == ERROR_INSUFFICIENT_BUFFER, "basic info into a buffer that is too small"); + CloseHandle(h); + check(!SetFileInformationByHandle(h, FileBasicInfo, &b, sizeof(b)) && GetLastError() == ERROR_INVALID_HANDLE, "a closed handle: invalid handle"); +} + +void Disposition() { + // classic: the name goes when the handle closes, not before + std::wstring p = In(L"classic.txt"); + Put(p, "abc"); + HANDLE h = OpenFor(p, GENERIC_READ | DELETE); + FILE_DISPOSITION_INFO d{TRUE}; + check(h != INVALID_HANDLE_VALUE && SetFileInformationByHandle(h, FileDispositionInfo, &d, sizeof(d)), "classic disposition set"); + check(Exists(p), " the file is still there while the handle is open"); + CloseHandle(h); + check(!Exists(p), " and gone once it is closed"); + Put(p, "abc"); + h = OpenFor(p, GENERIC_READ | DELETE); + SetFileInformationByHandle(h, FileDispositionInfo, &d, sizeof(d)); + d.DeleteFile = FALSE; + check(SetFileInformationByHandle(h, FileDispositionInfo, &d, sizeof(d)), "classic disposition taken back"); + CloseHandle(h); + check(Exists(p), " the file stays"); + h = OpenFor(p, GENERIC_READ); + d.DeleteFile = TRUE; + check(!SetFileInformationByHandle(h, FileDispositionInfo, &d, sizeof(d)) && GetLastError() == ERROR_ACCESS_DENIED, "a handle without DELETE access cannot ask for delete"); + CloseHandle(h); + SetFileAttributesW(p.c_str(), FILE_ATTRIBUTE_READONLY); + h = OpenFor(p, GENERIC_READ | DELETE); + check(!SetFileInformationByHandle(h, FileDispositionInfo, &d, sizeof(d)) && GetLastError() == ERROR_ACCESS_DENIED, "classic disposition on a read-only file: access denied"); + CloseHandle(h); + check(Exists(p), " and it stays"); + SetFileAttributesW(p.c_str(), FILE_ATTRIBUTE_NORMAL); + DeleteFileW(p.c_str()); + + // POSIX semantics: the name is free at once, the open handle still reads + p = In(L"posix.txt"); + Put(p, "abc"); + h = OpenFor(p, GENERIC_READ | DELETE, FILE_SHARE_READ); + check(h != INVALID_HANDLE_VALUE && SetDisposition(h, FILE_DISPOSITION_FLAG_DELETE | FILE_DISPOSITION_FLAG_POSIX_SEMANTICS), "POSIX disposition set"); + check(!Exists(p) && GetLastError() == ERROR_FILE_NOT_FOUND, " the name is gone at once"); + char buf[8]{}; DWORD got = 0; + check(ReadFile(h, buf, sizeof(buf), &got, nullptr) && got == 3 && std::string(buf, got) == "abc", " the handle still reads the file"); + check(Put(p, "new"), " the name can be used again"); + CloseHandle(h); + check(Slurp(p) == "new", " and closing the old handle leaves the new file alone"); + DeleteFileW(p.c_str()); + + // IGNORE_READONLY_ATTRIBUTE + p = In(L"posixro.txt"); + Put(p, "abc"); + SetFileAttributesW(p.c_str(), FILE_ATTRIBUTE_READONLY); + h = OpenFor(p, GENERIC_READ | DELETE); + check(!SetDisposition(h, FILE_DISPOSITION_FLAG_DELETE | FILE_DISPOSITION_FLAG_POSIX_SEMANTICS) && GetLastError() == ERROR_ACCESS_DENIED && Exists(p), + "POSIX disposition on a read-only file: access denied, file kept"); + check(SetDisposition(h, FILE_DISPOSITION_FLAG_DELETE | FILE_DISPOSITION_FLAG_POSIX_SEMANTICS | FILE_DISPOSITION_FLAG_IGNORE_READONLY_ATTRIBUTE) && !Exists(p), + " with IGNORE_READONLY_ATTRIBUTE the read-only file is deleted"); + CloseHandle(h); + + // Ex without POSIX semantics is the classic delete; without the DELETE flag it takes a request back + p = In(L"exclassic.txt"); + Put(p, "abc"); + h = OpenFor(p, GENERIC_READ | DELETE); + check(SetDisposition(h, FILE_DISPOSITION_FLAG_DELETE) && Exists(p), "Ex disposition without POSIX semantics: the file waits for the close"); + check(SetDisposition(h, FILE_DISPOSITION_FLAG_DO_NOT_DELETE), " flags 0 take the request back"); + CloseHandle(h); + check(Exists(p), " the file stays"); + DeleteFileW(p.c_str()); +} + +void EndOfFile() { + const std::wstring p = In(L"eof.txt"); + Put(p, "0123456789"); + HANDLE h = OpenFor(p, GENERIC_READ | GENERIC_WRITE); + LARGE_INTEGER pos{}, size{}; + pos.QuadPart = 4; + check(h != INVALID_HANDLE_VALUE && SetFilePointerEx(h, pos, nullptr, FILE_BEGIN) && SetEndOfFile(h) && GetFileSizeEx(h, &size) && size.QuadPart == 4, "SetEndOfFile at 4 cuts the file to 4 bytes"); + check(Slurp(p) == "0123", " and keeps the first four"); + pos.QuadPart = 10; + check(SetFilePointerEx(h, pos, nullptr, FILE_BEGIN) && SetEndOfFile(h) && GetFileSizeEx(h, &size) && size.QuadPart == 10, "SetEndOfFile at 10 extends the file to 10 bytes"); + check(Slurp(p) == std::string("0123\0\0\0\0\0\0", 10), " and the new bytes are zero"); + CloseHandle(h); + h = OpenFor(p, GENERIC_READ); + check(!SetEndOfFile(h) && GetLastError() == ERROR_ACCESS_DENIED, "SetEndOfFile on a handle opened for reading: access denied"); + CloseHandle(h); + check(!SetEndOfFile(h) && GetLastError() == ERROR_INVALID_HANDLE, "SetEndOfFile on a closed handle: invalid handle"); +} + +void PinnedPattern() { + // What PinnedFile::Open does: a probe with attribute access only and every sharing mode, then the real handle with + // read, delete and attribute access and FILE_SHARE_READ only, while the probe is still open. + for (const bool readOnly : {false, true}) { + const std::wstring p = In(L"pin.txt"); + Put(p, "pinned"); + if (readOnly) SetFileAttributesW(p.c_str(), FILE_ATTRIBUTE_READONLY); + HANDLE probe = CreateFileW(p.c_str(), FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, + FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, nullptr); + check(probe != INVALID_HANDLE_VALUE, "pinning: the probe opens, even on a read-only file"); + BY_HANDLE_FILE_INFORMATION pi{}, bi{}; + check(GetFileInformationByHandle(probe, &pi) && ((pi.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0) == readOnly, " the probe sees the read-only bit as it is"); + FILE_BASIC_INFO b{}; + b.FileAttributes = FILE_ATTRIBUTE_NORMAL; + check(SetFileInformationByHandle(probe, FileBasicInfo, &b, sizeof(b)), " the probe clears it (attribute access is enough)"); + HANDLE real = CreateFileW(p.c_str(), GENERIC_READ | DELETE | FILE_WRITE_ATTRIBUTES | GENERIC_WRITE, FILE_SHARE_READ, nullptr, OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OPEN_REPARSE_POINT, nullptr); + check(real != INVALID_HANDLE_VALUE, " the real handle opens while the probe is open (attribute access takes no part in sharing)"); + check(real != INVALID_HANDLE_VALUE && GetFileInformationByHandle(real, &bi) && bi.dwVolumeSerialNumber == pi.dwVolumeSerialNumber && bi.nFileIndexHigh == pi.nFileIndexHigh && + bi.nFileIndexLow == pi.nFileIndexLow && (pi.nFileIndexHigh | pi.nFileIndexLow) != 0, + " both handles name the same file (volume serial and index)"); + check(CreateFileW(p.c_str(), GENERIC_WRITE, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr) == INVALID_HANDLE_VALUE && GetLastError() == ERROR_SHARING_VIOLATION, + " but a writer is still kept out by FILE_SHARE_READ only"); + check(CreateFileW(p.c_str(), FILE_READ_ATTRIBUTES, 0, nullptr, OPEN_EXISTING, 0, nullptr) != INVALID_HANDLE_VALUE, " and an attribute-only open takes no part in sharing either"); + if (real != INVALID_HANDLE_VALUE) { + check(SetDisposition(real, FILE_DISPOSITION_FLAG_DELETE | FILE_DISPOSITION_FLAG_POSIX_SEMANTICS | FILE_DISPOSITION_FLAG_IGNORE_READONLY_ATTRIBUTE) && !Exists(p), " and it can delete the file"); + CloseHandle(real); + } + CloseHandle(probe); + } +} + +void LinksAndReparse() { + const std::wstring a = In(L"nl-a.txt"), l = In(L"nl-b.txt"), s = In(L"nl-sym.txt"); + Put(a, "linked"); + BY_HANDLE_FILE_INFORMATION bi{}; + HANDLE h = OpenFor(a, FILE_READ_ATTRIBUTES); + check(h != INVALID_HANDLE_VALUE && GetFileInformationByHandle(h, &bi) && bi.nNumberOfLinks == 1, "a file with one name reports 1 link"); + CloseHandle(h); + check(CreateHardLinkW(l.c_str(), a.c_str(), nullptr), "a hard link"); + h = OpenFor(a, FILE_READ_ATTRIBUTES); + check(h != INVALID_HANDLE_VALUE && GetFileInformationByHandle(h, &bi) && bi.nNumberOfLinks == 2, "a hard-linked file reports 2 links"); + CloseHandle(h); + h = OpenFor(l, FILE_READ_ATTRIBUTES); + check(h != INVALID_HANDLE_VALUE && GetFileInformationByHandle(h, &bi) && bi.nNumberOfLinks == 2, " by either name"); + CloseHandle(h); + check(CreateSymbolicLinkW(s.c_str(), a.c_str(), 0), "a symbolic link to a file"); + h = CreateFileW(s.c_str(), FILE_READ_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, nullptr); + check(h != INVALID_HANDLE_VALUE && GetFileInformationByHandle(h, &bi) && (bi.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT), "FILE_FLAG_OPEN_REPARSE_POINT: a symbolic link reports the reparse attribute"); + FILE_BASIC_INFO fb{}; + check(h != INVALID_HANDLE_VALUE && GetFileInformationByHandleEx(h, FileBasicInfo, &fb, sizeof(fb)) && (fb.FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT), " in basic info too"); + CloseHandle(h); + h = OpenFor(s, FILE_READ_ATTRIBUTES); + check(h != INVALID_HANDLE_VALUE && GetFileInformationByHandle(h, &bi) && !(bi.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) && bi.nNumberOfLinks == 2, + "without the flag the link is followed: the target's attributes, no reparse point"); + CloseHandle(h); + DeleteFileW(s.c_str()); DeleteFileW(l.c_str()); DeleteFileW(a.c_str()); +} + +void ProcessEnd() { + void* p = std::malloc(16); + check(GetProcessHeap() != nullptr && HeapFree(GetProcessHeap(), 0, p), "HeapFree frees what the process heap hands out"); + const pid_t pid = fork(); + if (pid == 0) ExitProcess(7); + int status = 0; + check(pid > 0 && waitpid(pid, &status, 0) == pid && WIFEXITED(status) && WEXITSTATUS(status) == 7, "ExitProcess(7) ends the process with exit code 7"); +} +} // namespace + +// ReplaceFileW: the replacement takes the name of the replaced file; documented failure codes (1175 to 1177 are the numbers Windows gives). +void ReplaceFile() { + check(ERROR_UNABLE_TO_REMOVE_REPLACED == 1175 && ERROR_UNABLE_TO_MOVE_REPLACEMENT == 1176 && ERROR_UNABLE_TO_MOVE_REPLACEMENT_2 == 1177, "the replace failure codes are 1175, 1176 and 1177"); + Put(In(L"live.ini"), "old"); Put(In(L"fresh.ini"), "new"); + check(ReplaceFileW(In(L"live.ini").c_str(), In(L"fresh.ini").c_str(), In(L"live.bak").c_str(), 0, nullptr, nullptr), "ReplaceFileW with a backup name"); + check(Slurp(In(L"live.ini")) == "new" && Slurp(In(L"live.bak")) == "old" && GetFileAttributesW(In(L"fresh.ini").c_str()) == INVALID_FILE_ATTRIBUTES, + "the replacement is at the old name, the old file at the backup name, the replacement's own name is free"); + Put(In(L"fresh2.ini"), "newer"); + check(ReplaceFileW(In(L"live.ini").c_str(), In(L"fresh2.ini").c_str(), In(L"live.bak").c_str(), REPLACEFILE_WRITE_THROUGH, nullptr, nullptr) && Slurp(In(L"live.bak")) == "new" && Slurp(In(L"live.ini")) == "newer", + "an existing backup is overwritten"); + Put(In(L"fresh3.ini"), "third"); + check(ReplaceFileW(In(L"live.ini").c_str(), In(L"fresh3.ini").c_str(), nullptr, 0, nullptr, nullptr) && Slurp(In(L"live.ini")) == "third" && GetFileAttributesW(In(L"fresh3.ini").c_str()) == INVALID_FILE_ATTRIBUTES, + "ReplaceFileW without a backup name"); + + check(!ReplaceFileW(In(L"absent.ini").c_str(), In(L"live.bak").c_str(), nullptr, 0, nullptr, nullptr) && GetLastError() == ERROR_FILE_NOT_FOUND && Slurp(In(L"live.bak")) == "new" , + "a replaced file that does not exist: file not found, the replacement stays"); + check(!ReplaceFileW(In(L"live.ini").c_str(), In(L"absent.ini").c_str(), nullptr, 0, nullptr, nullptr) && GetLastError() == ERROR_FILE_NOT_FOUND && Slurp(In(L"live.ini")) == "third", + "a replacement that does not exist: file not found, the replaced file stays"); + check(!ReplaceFileW(In(L"nope\\live.ini").c_str(), In(L"live.bak").c_str(), nullptr, 0, nullptr, nullptr) && GetLastError() == ERROR_PATH_NOT_FOUND, "a missing folder: path not found"); + int dummy = 0; + check(!ReplaceFileW(In(L"live.ini").c_str(), In(L"live.bak").c_str(), nullptr, 0, &dummy, nullptr) && GetLastError() == ERROR_INVALID_PARAMETER, "the reserved arguments must be null"); + + SetFileAttributesW(In(L"live.ini").c_str(), FILE_ATTRIBUTE_READONLY); + check(!ReplaceFileW(In(L"live.ini").c_str(), In(L"live.bak").c_str(), nullptr, 0, nullptr, nullptr) && GetLastError() == ERROR_ACCESS_DENIED && Slurp(In(L"live.ini")) == "third" && Slurp(In(L"live.bak")) == "new", + "a read-only replaced file: access denied, nothing moved"); + SetFileAttributesW(In(L"live.ini").c_str(), FILE_ATTRIBUTE_NORMAL); + + HANDLE held = CreateFileW(In(L"live.ini").c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr); + check(!ReplaceFileW(In(L"live.ini").c_str(), In(L"live.bak").c_str(), In(L"live.old").c_str(), 0, nullptr, nullptr) && GetLastError() == ERROR_UNABLE_TO_REMOVE_REPLACED + && Slurp(In(L"live.ini")) == "third" && Slurp(In(L"live.bak")) == "new" && GetFileAttributesW(In(L"live.old").c_str()) == INVALID_FILE_ATTRIBUTES, + "a replaced file held without delete sharing: 1175, both files keep their names"); + CloseHandle(held); + + held = CreateFileW(In(L"live.bak").c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr); + check(!ReplaceFileW(In(L"live.ini").c_str(), In(L"live.bak").c_str(), nullptr, 0, nullptr, nullptr) && GetLastError() == ERROR_SHARING_VIOLATION && Slurp(In(L"live.ini")) == "third", + "a replacement held without delete sharing: sharing violation"); + CloseHandle(held); + + SetFileAttributesW(In(L"live.bak").c_str(), FILE_ATTRIBUTE_READONLY); + check(ReplaceFileW(In(L"live.ini").c_str(), In(L"live.bak").c_str(), nullptr, 0, nullptr, nullptr) && Slurp(In(L"live.ini")) == "new" && (GetFileAttributesW(In(L"live.ini").c_str()) & FILE_ATTRIBUTE_READONLY) == 0, + "the replaced file's attributes stay on the new file (a read-only replacement does not make it read-only)"); + + Put(In(L"h-live.ini"), "a"); Put(In(L"h-fresh.ini"), "b"); + SetFileAttributesW(In(L"h-live.ini").c_str(), FILE_ATTRIBUTE_HIDDEN); + check((GetFileAttributesW(In(L"h-live.ini").c_str()) & FILE_ATTRIBUTE_HIDDEN) && ReplaceFileW(In(L"h-live.ini").c_str(), In(L"h-fresh.ini").c_str(), nullptr, 0, nullptr, nullptr) + && Slurp(In(L"h-live.ini")) == "b" && (GetFileAttributesW(In(L"h-live.ini").c_str()) & FILE_ATTRIBUTE_HIDDEN), + "the hidden attribute of the replaced file stays on the new file"); + SetFileAttributesW(In(L"h-live.ini").c_str(), FILE_ATTRIBUTE_NORMAL); + check((GetFileAttributesW(In(L"h-live.ini").c_str()) & FILE_ATTRIBUTE_HIDDEN) == 0, "a normal attribute clears hidden"); + + check(CreateDirectoryW(In(L"rd").c_str(), nullptr) && !ReplaceFileW(In(L"live.ini").c_str(), In(L"rd").c_str(), nullptr, 0, nullptr, nullptr) && GetLastError() == ERROR_ACCESS_DENIED, "a folder cannot replace a file"); + check(!ReplaceFileW(L"Z:\\no\\such\\a", L"Z:\\no\\such\\b", nullptr, 0, nullptr, nullptr) && GetLastError() == ERROR_PATH_NOT_FOUND, "Z:\\ paths are read as everywhere else"); +} + +// ---- 0.6.5's calls: the named mutex (the per-game state lock), events, rename by handle, the long path, security +// descriptors, the Restart Manager. The other processes are this program started again with a --child-* argument. +std::string SelfExe() { + char b[4096]; + const ssize_t n = readlink("/proc/self/exe", b, sizeof(b) - 1); + return n > 0 ? std::string(b, (size_t)n) : std::string(); +} +std::string PosixOf(const std::wstring& w) { // Tmp's Z:\ spelling as the POSIX path a child gets + std::string p(w.begin(), w.end()); + if (p.rfind("Z:", 0) == 0) p.erase(0, 2); + for (auto& c : p) if (c == '\\') c = '/'; + return p; +} +PROCESS_INFORMATION StartChild(const std::string& args) { + const std::string self = SelfExe(); + std::wstring cmd = L"\"" + std::wstring(self.begin(), self.end()) + L"\" "; + cmd += std::wstring(args.begin(), args.end()); + std::vector b(cmd.begin(), cmd.end()); + b.push_back(0); + STARTUPINFOW si{}; + si.cb = sizeof(si); + PROCESS_INFORMATION pi{}; + if (!CreateProcessW(nullptr, b.data(), nullptr, nullptr, FALSE, 0, nullptr, nullptr, &si, &pi)) pi.hProcess = nullptr; + return pi; +} +bool WaitReady(const std::string& file, int ms = 10000) { + for (int i = 0; i < ms / 5; ++i) { + if (access(file.c_str(), F_OK) == 0) return true; + Sleep(5); + } + return false; +} +void EndChild(PROCESS_INFORMATION& pi) { + if (!pi.hProcess) return; + if (WaitForSingleObject(pi.hProcess, 0) == WAIT_TIMEOUT) TerminateProcess(pi.hProcess, 1); + WaitForSingleObject(pi.hProcess, 5000); + CloseHandle(pi.hProcess); + CloseHandle(pi.hThread); +} +long long MsSince(std::chrono::steady_clock::time_point t) { + return std::chrono::duration_cast(std::chrono::steady_clock::now() - t).count(); +} +std::wstring Name(const char* base) { return L"Global\\wg-posix-test-" + std::to_wstring(GetCurrentProcessId()) + L"-" + std::wstring(base, base + std::strlen(base)); } +std::string Narrow(const std::wstring& w) { return std::string(w.begin(), w.end()); } + +// the children +int ChildMain(int argc, char** argv) { + const std::string mode = argv[1]; + auto ready = [](const char* f) { const int fd = open(f, O_CREAT | O_WRONLY | O_CLOEXEC, 0600); if (fd >= 0) close(fd); }; + if (mode == "--child-mutex" && argc == 6) { // release|die + const std::wstring name(argv[2], argv[2] + std::strlen(argv[2])); + HANDLE m = CreateMutexW(nullptr, FALSE, name.c_str()); + if (!m || WaitForSingleObject(m, 10000) != WAIT_OBJECT_0) return 2; + ready(argv[4]); + Sleep((DWORD)std::atoi(argv[3])); + if (std::string(argv[5]) == "die") _exit(3); // ends owning it + ReleaseMutex(m); + CloseHandle(m); + return 0; + } + if ((mode == "--child-open" || mode == "--child-map") && argc == 4) { // + const int fd = open(argv[2], O_RDONLY | O_CLOEXEC); + if (fd < 0) return 2; + if (mode == "--child-map") { // only the mapping holds it, as a Wine process holds a DLL it loaded + struct stat st; + fstat(fd, &st); + if (mmap(nullptr, (size_t)st.st_size, PROT_READ, MAP_PRIVATE, fd, 0) == MAP_FAILED) return 3; + close(fd); + } + ready(argv[3]); + Sleep(30000); + return 0; + } + if (mode == "--child-nodump" && argc == 3) { // its /proc fd and maps become closed to its own user + prctl(PR_SET_DUMPABLE, 0, 0, 0, 0); + ready(argv[2]); + Sleep(30000); + return 0; + } + return 9; +} + +void NamedMutex() { + const std::wstring a = Name("a"); + HANDLE m = CreateMutexW(nullptr, FALSE, a.c_str()); + check(m && GetLastError() == 0, "mutex: a new name: created, not ERROR_ALREADY_EXISTS"); + HANDLE m2 = CreateMutexW(nullptr, FALSE, a.c_str()); + check(m2 && GetLastError() == ERROR_ALREADY_EXISTS, "mutex: the same name again while a handle is open: ERROR_ALREADY_EXISTS"); + HANDLE o = OpenMutexW(SYNCHRONIZE | MUTEX_MODIFY_STATE, FALSE, a.c_str()); + check(o != nullptr, "mutex: OpenMutexW of an open name"); + check(!OpenMutexW(SYNCHRONIZE, FALSE, Name("never").c_str()) && GetLastError() == ERROR_FILE_NOT_FOUND, "mutex: OpenMutexW of a name nobody has open: ERROR_FILE_NOT_FOUND"); + check(!CreateMutexW(nullptr, FALSE, nullptr) && GetLastError() == ERROR_NOT_SUPPORTED, "mutex: an unnamed mutex: ERROR_NOT_SUPPORTED"); + check(!CreateMutexW(nullptr, FALSE, std::wstring(300, L'x').c_str()) && GetLastError() == ERROR_INVALID_NAME, "mutex: a name too long for a file: ERROR_INVALID_NAME"); + check(!ReleaseMutex(m) && GetLastError() == ERROR_NOT_OWNER, "mutex: ReleaseMutex of a mutex nobody owns: ERROR_NOT_OWNER"); + check(WaitForSingleObject(m, 0) == WAIT_OBJECT_0, "mutex: taken"); + check(WaitForSingleObject(m2, 0) == WAIT_OBJECT_0, "mutex: taken again by its owner through another handle (recursive, per thread)"); + std::atomic other{0}, otherRelease{0}, otherError{0}; + long long waited = 0; + std::thread t([&] { + const auto t0 = std::chrono::steady_clock::now(); + other = WaitForSingleObject(o, 150); + waited = MsSince(t0); + otherRelease = ReleaseMutex(o); + otherError = GetLastError(); + }); + t.join(); + check(other == WAIT_TIMEOUT && waited >= 140 && waited < 2000, "mutex: another thread of this process waits its timeout, then WAIT_TIMEOUT"); + check(!otherRelease && otherError == ERROR_NOT_OWNER, "mutex: another thread cannot release it (ERROR_NOT_OWNER)"); + check(ReleaseMutex(m2) && ReleaseMutex(m), "mutex: released as often as taken"); + check(!ReleaseMutex(m) && GetLastError() == ERROR_NOT_OWNER, "mutex: one release too many: ERROR_NOT_OWNER"); + std::thread t2([&] { other = WaitForSingleObject(o, 1000); ReleaseMutex(o); }); + t2.join(); + check(other == WAIT_OBJECT_0, "mutex: once released, another thread takes it"); + // a thread that waits while another holds it gets it when it is released, inside its wait + WaitForSingleObject(m, 0); + std::thread t3([&] { other = WaitForSingleObject(o, 3000); ReleaseMutex(o); }); + Sleep(100); + ReleaseMutex(m); + t3.join(); + check(other == WAIT_OBJECT_0, "mutex: a waiting thread gets it once the owner releases it"); + CloseHandle(m2); + CloseHandle(m); + HANDLE again = CreateMutexW(nullptr, FALSE, a.c_str()); + check(again && GetLastError() == ERROR_ALREADY_EXISTS, "mutex: kept by an opened handle: the creators' handles closed, it still exists"); + CloseHandle(again); + CloseHandle(o); + again = CreateMutexW(nullptr, FALSE, a.c_str()); + check(again && GetLastError() == 0, "mutex: every handle closed: the name is new again"); + CloseHandle(again); + + // between processes + const std::wstring b = Name("b"); + const std::string readyB = PosixOf(In(L"ready-b")); + PROCESS_INFORMATION pi = StartChild("--child-mutex " + Narrow(b) + " 800 " + readyB + " release"); + check(pi.hProcess && WaitReady(readyB), "mutex: (a child holds it)"); + HANDLE mb = CreateMutexW(nullptr, FALSE, b.c_str()); + check(mb && GetLastError() == ERROR_ALREADY_EXISTS, "mutex: another process's handle: ERROR_ALREADY_EXISTS here"); + auto t0 = std::chrono::steady_clock::now(); + const DWORD busy = WaitForSingleObject(mb, 200); + const long long ms = MsSince(t0); + check(busy == WAIT_TIMEOUT && ms >= 190 && ms < 2000, "mutex: held by another process: WAIT_TIMEOUT after the wait asked for"); + check(WaitForSingleObject(mb, 10000) == WAIT_OBJECT_0, "mutex: the other process releases it: taken (not abandoned)"); + ReleaseMutex(mb); + EndChild(pi); + CloseHandle(mb); + + // an owner that ends without releasing it: abandoned for whoever kept the object alive; a fresh object for a new creator + const std::wstring c = Name("c"); + const std::string readyC = PosixOf(In(L"ready-c")); + pi = StartChild("--child-mutex " + Narrow(c) + " 300 " + readyC + " die"); + check(pi.hProcess && WaitReady(readyC), "mutex: (a child holds it and will end owning it)"); + HANDLE keep = OpenMutexW(SYNCHRONIZE, FALSE, c.c_str()); + WaitForSingleObject(pi.hProcess, 5000); + check(keep && WaitForSingleObject(keep, 2000) == WAIT_ABANDONED, "mutex: its owner died, a handle kept it: WAIT_ABANDONED, and it is ours"); + check(ReleaseMutex(keep), "mutex: an abandoned mutex taken is released as usual"); + check(WaitForSingleObject(keep, 0) == WAIT_OBJECT_0 && ReleaseMutex(keep), "mutex: after that release it is a normal mutex again"); + CloseHandle(keep); + EndChild(pi); + const std::wstring d = Name("d"); + const std::string readyD = PosixOf(In(L"ready-d")); + pi = StartChild("--child-mutex " + Narrow(d) + " 100 " + readyD + " die"); + check(pi.hProcess && WaitReady(readyD), "mutex: (a child holds a second one and will end owning it)"); + WaitForSingleObject(pi.hProcess, 5000); + HANDLE fresh = CreateMutexW(nullptr, FALSE, d.c_str()); + check(fresh && GetLastError() == 0 && WaitForSingleObject(fresh, 0) == WAIT_OBJECT_0, "mutex: no handle kept it: a new mutex, not abandoned (as on Windows)"); + ReleaseMutex(fresh); + CloseHandle(fresh); + EndChild(pi); + + // a lock file this user may not open: access denied, not a timeout + const std::wstring e = Name("e"); + HANDLE me = CreateMutexW(nullptr, FALSE, e.c_str()); + const char* rt = getenv("XDG_RUNTIME_DIR"); + const std::string lockFile = std::string(rt && *rt ? rt : "") + "/wronggpu-mutex-Global%5C" + Narrow(e).substr(7) + ".lock"; + CloseHandle(me); + if (geteuid() == 0 || !rt || !*rt) { + std::printf("posix-layer: running as root or without XDG_RUNTIME_DIR: the lock-file permission check is skipped\n"); + } else { + check(access(lockFile.c_str(), F_OK) == 0, "mutex: (its lock file is in XDG_RUNTIME_DIR)"); + chmod(lockFile.c_str(), 0); + check(!CreateMutexW(nullptr, FALSE, e.c_str()) && GetLastError() == ERROR_ACCESS_DENIED, "mutex: a lock file this user may not open: CreateMutexW ERROR_ACCESS_DENIED"); + check(!OpenMutexW(SYNCHRONIZE, FALSE, e.c_str()) && GetLastError() == ERROR_ACCESS_DENIED, "mutex: and OpenMutexW ERROR_ACCESS_DENIED"); + chmod(lockFile.c_str(), 0600); + } + // this run's lock files (a product run keeps them: one per name in the runtime folder, which the session clears) + if (rt && *rt) + for (const char* n : {"a", "b", "c", "d", "e"}) unlink((std::string(rt) + "/wronggpu-mutex-Global%5C" + Narrow(Name(n)).substr(7) + ".lock").c_str()); +} + +void Events() { + HANDLE ev = CreateEventW(nullptr, TRUE, FALSE, nullptr); + check(ev && WaitForSingleObject(ev, 0) == WAIT_TIMEOUT, "event: manual reset, not set: WAIT_TIMEOUT"); + std::thread t([&] { Sleep(50); SetEvent(ev); }); + check(WaitForSingleObject(ev, 5000) == WAIT_OBJECT_0, "event: set by another thread inside the wait"); + t.join(); + check(WaitForSingleObject(ev, 0) == WAIT_OBJECT_0, "event: a manual-reset event stays set"); + CloseHandle(ev); + HANDLE au = CreateEventW(nullptr, FALSE, TRUE, nullptr); + check(au && WaitForSingleObject(au, 0) == WAIT_OBJECT_0 && WaitForSingleObject(au, 0) == WAIT_TIMEOUT, "event: an auto-reset event lets one wait through"); + CloseHandle(au); + check(!CreateEventW(nullptr, TRUE, FALSE, L"named") && GetLastError() == ERROR_NOT_SUPPORTED, "event: a named event: ERROR_NOT_SUPPORTED"); + check(!SetEvent(nullptr) && GetLastError() == ERROR_INVALID_HANDLE, "event: SetEvent of no handle: ERROR_INVALID_HANDLE"); + volatile LONG n = 0; + std::vector ts; + for (int i = 0; i < 4; ++i) ts.emplace_back([&] { for (int k = 0; k < 10000; ++k) InterlockedIncrement(&n); }); + for (auto& x : ts) x.join(); + check(n == 40000, "InterlockedIncrement: no increment lost between threads"); +} + +bool RenameTo(HANDLE h, const std::wstring& name, bool replace) { + std::vector buf(sizeof(FILE_RENAME_INFO) + name.size() * sizeof(wchar_t), 0); + FILE_RENAME_INFO* ri = reinterpret_cast(buf.data()); + ri->ReplaceIfExists = replace ? TRUE : FALSE; + ri->FileNameLength = (DWORD)(name.size() * sizeof(wchar_t)); + std::memcpy(ri->FileName, name.c_str(), name.size() * sizeof(wchar_t)); + return SetFileInformationByHandle(h, FileRenameInfo, ri, (DWORD)buf.size()) != 0; +} + +void RenameByHandle() { + const std::wstring a = In(L"rn-a.dll"), b = In(L"rn-b.dll"), c = In(L"rn-c.dll"); + Put(a, "old"); + HANDLE h = OpenFor(a, DELETE | GENERIC_READ | FILE_WRITE_DATA, FILE_SHARE_READ); // as the operation guard holds a binary + check(RenameTo(h, L"\\\\?\\" + b, false) && !Exists(a) && Slurp(b) == "old", "rename by handle: to a free name (\\\\?\\ form)"); + check(SetDisposition(h, FILE_DISPOSITION_FLAG_DELETE | FILE_DISPOSITION_FLAG_POSIX_SEMANTICS) && !Exists(b), " a delete through the handle then deletes the new name"); + CloseHandle(h); + Put(a, "old"); + h = OpenFor(a, DELETE | GENERIC_READ, FILE_SHARE_READ); + check(RenameTo(h, L"\\??\\" + b, false) && Slurp(b) == "old", "rename by handle: a name in the NT form (\\??\\Z:\\...)"); + Put(c, "taken"); + check(!RenameTo(h, c, false) && GetLastError() == ERROR_ALREADY_EXISTS && Slurp(b) == "old" && Slurp(c) == "taken", "rename by handle: onto a file without replace: ERROR_ALREADY_EXISTS, both as they were"); + HANDLE busy = OpenFor(c, GENERIC_READ, FILE_SHARE_READ); + check(!RenameTo(h, c, true) && GetLastError() == ERROR_ACCESS_DENIED && Slurp(c) == "taken" && Slurp(b) == "old", "rename by handle: replace over a file open without delete sharing: ERROR_ACCESS_DENIED, nothing moved"); + CloseHandle(busy); + SetFileAttributesW(c.c_str(), FILE_ATTRIBUTE_READONLY); + check(!RenameTo(h, c, true) && GetLastError() == ERROR_ACCESS_DENIED && Slurp(c) == "taken", "rename by handle: replace over a read-only file: ERROR_ACCESS_DENIED"); + SetFileAttributesW(c.c_str(), FILE_ATTRIBUTE_NORMAL); + check(RenameTo(h, c, true) && Slurp(c) == "old" && !Exists(b), "rename by handle: replace over a closed file: replaced"); + // renamed by someone else meanwhile (by name; it shares delete): the handle's rename still moves its own file + CloseHandle(h); + h = OpenFor(c, DELETE | GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE); + check(MoveFileExW(c.c_str(), b.c_str(), 0) && RenameTo(h, a, false) && Slurp(a) == "old" && !Exists(b) && !Exists(c), "rename by handle: after another rename by name, the file's current name is used"); + CloseHandle(h); + h = OpenFor(a, GENERIC_READ); + check(!RenameTo(h, b, false) && GetLastError() == ERROR_ACCESS_DENIED && Exists(a), "rename by handle: a handle without DELETE access: ERROR_ACCESS_DENIED"); + CloseHandle(h); + h = OpenFor(a, DELETE | GENERIC_READ); + std::vector buf(sizeof(FILE_RENAME_INFO) + 8, 0); + FILE_RENAME_INFO* ri = reinterpret_cast(buf.data()); + ri->RootDirectory = h; + ri->FileNameLength = sizeof(wchar_t); + ri->FileName[0] = L'x'; + check(!SetFileInformationByHandle(h, FileRenameInfo, ri, (DWORD)buf.size()) && GetLastError() == ERROR_INVALID_PARAMETER, "rename by handle: a name relative to a folder handle: ERROR_INVALID_PARAMETER"); + ri->RootDirectory = nullptr; + ri->FileNameLength = 400; + check(!SetFileInformationByHandle(h, FileRenameInfo, ri, (DWORD)buf.size()) && GetLastError() == ERROR_INVALID_PARAMETER, "rename by handle: a name longer than the buffer: ERROR_INVALID_PARAMETER"); + // a folder this user may not write: access denied, the file where it was + const std::wstring ro = In(L"rn-ro"); + CreateDirectoryW(ro.c_str(), nullptr); + if (geteuid() == 0) { + std::printf("posix-layer: running as root: the read-only folder rename check is skipped\n"); + } else { + chmod(PosixOf(ro).c_str(), 0555); + check(!RenameTo(h, ro + L"\\x.dll", false) && GetLastError() == ERROR_ACCESS_DENIED && Exists(a), "rename by handle: into a folder this user may not write: ERROR_ACCESS_DENIED"); + chmod(PosixOf(ro).c_str(), 0755); + } + check(!RenameTo(h, L"Z:\\no\\such\\folder\\x.dll", false) && GetLastError() == ERROR_PATH_NOT_FOUND && Exists(a), "rename by handle: into a folder that is not there: ERROR_PATH_NOT_FOUND"); + CloseHandle(h); + DeleteFileW(a.c_str()); +} + +void LongPathAndSecurity() { + Put(In(L"LongName.Txt"), "x"); + wchar_t out[MAX_PATH * 2]; + DWORD n = GetLongPathNameW(In(L"longname.txt").c_str(), out, MAX_PATH * 2); + check(n && std::wstring(out, n) == In(L"LongName.Txt"), "GetLongPathNameW: the path, its names as they are on disk"); + n = GetLongPathNameW((L"\\\\?\\" + In(L"LongName.Txt")).c_str(), out, MAX_PATH * 2); + check(n && std::wstring(out, n) == L"\\\\?\\" + In(L"LongName.Txt"), "GetLongPathNameW: a \\\\?\\ prefix stays"); + const DWORD need = GetLongPathNameW(In(L"LongName.Txt").c_str(), out, 3); + check(need == In(L"LongName.Txt").size() + 1, "GetLongPathNameW: a short buffer: the size needed, with the NUL"); + check(!GetLongPathNameW(In(L"none.txt").c_str(), out, MAX_PATH) && GetLastError() == ERROR_FILE_NOT_FOUND, "GetLongPathNameW: a missing file: ERROR_FILE_NOT_FOUND"); + check(!GetLongPathNameW(In(L"none\\x.txt").c_str(), out, MAX_PATH) && GetLastError() == ERROR_PATH_NOT_FOUND, "GetLongPathNameW: a missing folder: ERROR_PATH_NOT_FOUND"); + // through a symbolic link: the long form keeps the link's name, the final form is where it leads (what util.cpp compares) + CreateDirectoryW(In(L"lp-real").c_str(), nullptr); + Put(In(L"lp-real\\f.txt"), "x"); + if (symlink(PosixOf(In(L"lp-real")).c_str(), PosixOf(In(L"lp-link")).c_str()) == 0) { + n = GetLongPathNameW(In(L"lp-link\\f.txt").c_str(), out, MAX_PATH * 2); + HANDLE h = OpenFor(In(L"lp-link\\f.txt"), GENERIC_READ); + wchar_t fin[MAX_PATH * 2]; + const DWORD m = GetFinalPathNameByHandleW(h, fin, MAX_PATH * 2, 0); + CloseHandle(h); + check(n && std::wstring(out, n) == In(L"lp-link\\f.txt") && m && std::wstring(fin, m) == In(L"lp-real\\f.txt"), + "GetLongPathNameW: a link is not followed (its final path is the target's)"); + } + PSECURITY_DESCRIPTOR sd = reinterpret_cast(1); + check(!ConvertStringSecurityDescriptorToSecurityDescriptorW(L"D:(A;;GA;;;WD)", SDDL_REVISION_1, &sd, nullptr) && GetLastError() == ERROR_NOT_SUPPORTED && sd == nullptr, + "security descriptors: not available (FALSE, ERROR_NOT_SUPPORTED, no descriptor)"); +} + +UINT HoldersOf(const std::wstring& file, RM_PROCESS_INFO* info, UINT cap, DWORD* reasons, DWORD* rc = nullptr, UINT* needed = nullptr) { + DWORD s = 0; + WCHAR key[CCH_RM_SESSION_KEY + 1] = {}; + if (RmStartSession(&s, 0, key) != ERROR_SUCCESS) return 999; + LPCWSTR files[] = {file.c_str()}; + RmRegisterResources(s, 1, files, 0, nullptr, 0, nullptr); + UINT need = 0, n = cap; + const DWORD r = RmGetList(s, &need, &n, info, reasons); + RmEndSession(s); + if (rc) *rc = r; + if (needed) *needed = need; + return r == ERROR_SUCCESS ? n : 999; +} +bool Lists(const RM_PROCESS_INFO* info, UINT n, DWORD pid) { + for (UINT i = 0; i < n; ++i) if (info[i].Process.dwProcessId == pid) return true; + return false; +} + +void RestartManager() { + const std::wstring f = In(L"rm-held.dll"), g = In(L"rm-mapped.dll"), idle = In(L"rm-free.dll"); + Put(f, "MZ held"); + Put(g, "MZ mapped"); + Put(idle, "MZ free"); + RM_PROCESS_INFO info[16]; + DWORD reasons = 0; + check(HoldersOf(idle, info, 16, &reasons) == 0, "Restart Manager: a file nobody holds: none listed"); + HANDLE mine = OpenFor(f, GENERIC_READ); + UINT n = HoldersOf(f, info, 16, &reasons); + check(n != 999 && Lists(info, n, GetCurrentProcessId()), "Restart Manager: a file this process holds: this process listed"); + CloseHandle(mine); + const std::string r1 = PosixOf(In(L"ready-rm1")), r2 = PosixOf(In(L"ready-rm2")); + PROCESS_INFORMATION po = StartChild("--child-open " + PosixOf(f) + " " + r1); + PROCESS_INFORMATION pm = StartChild("--child-map " + PosixOf(g) + " " + r2); + check(po.hProcess && pm.hProcess && WaitReady(r1) && WaitReady(r2), "Restart Manager: (two children hold the files)"); + n = HoldersOf(f, info, 16, &reasons); + bool named = false; + for (UINT i = 0; i < n && n != 999; ++i) + if (info[i].Process.dwProcessId == po.dwProcessId) named = std::wstring(info[i].strAppName) == L"posix-layer-tests" && info[i].Process.ProcessStartTime.dwHighDateTime != 0; + check(n != 999 && Lists(info, n, po.dwProcessId) && !Lists(info, n, pm.dwProcessId), "Restart Manager: a file another process has open: that process listed (and not the other)"); + check(named, "Restart Manager: the holder's program name and start time"); + n = HoldersOf(g, info, 16, &reasons); + check(n != 999 && Lists(info, n, pm.dwProcessId), "Restart Manager: a file another process only has mapped (as Wine maps a DLL): listed"); + struct stat fs, is; + stat(PosixOf(f).c_str(), &fs); + stat(PosixOf(idle).c_str(), &is); + check(wgposix::RmScanProcess((int)po.dwProcessId, {{fs.st_dev, fs.st_ino}}) == 1 && wgposix::RmScanProcess((int)po.dwProcessId, {{is.st_dev, is.st_ino}}) == 0, + "Restart Manager: one process looked at: it holds the file it has open (1), not another (0)"); + DWORD rc = 0; + UINT needed = 0; + HoldersOf(f, info, 0, &reasons, &rc, &needed); + check(rc == ERROR_MORE_DATA && needed >= 1, "Restart Manager: no room in the list: ERROR_MORE_DATA and the count needed"); + EndChild(po); + EndChild(pm); + n = HoldersOf(f, info, 16, &reasons); + check(n != 999 && !Lists(info, n, po.dwProcessId), "Restart Manager: the holder ended: no longer listed"); + // a process of this user whose /proc entries are closed (not dumpable): unreadable (-1), and the reasons say not everything + // was seen (on most desktops other processes of the user, the compositor for one, are closed too, so the reason alone + // cannot single the child out: the scan of the child is checked first) + const std::string r3 = PosixOf(In(L"ready-rm3")); + PROCESS_INFORMATION pn = StartChild("--child-nodump " + r3); + check(pn.hProcess && WaitReady(r3), "Restart Manager: (a child that is not dumpable)"); + check(wgposix::RmScanProcess((int)pn.dwProcessId, {{is.st_dev, is.st_ino}}) == -1, "Restart Manager: a process of this user that cannot be read: unreadable (-1), not 'holds nothing'"); + reasons = 0; + n = HoldersOf(idle, info, 16, &reasons); + check(n == 0 && (reasons & RmRebootReasonPermissionDenied), "Restart Manager: ...and the list's reasons say RmRebootReasonPermissionDenied (none seen is not none)"); + EndChild(pn); + check(wgposix::RmScanProcess((int)pn.dwProcessId, {{is.st_dev, is.st_ino}}) == -2, "Restart Manager: a process that ended: not looked at (-2)"); + if (getuid() != 0) check(wgposix::RmScanProcess(1, {{is.st_dev, is.st_ino}}) == -2, "Restart Manager: another user's process (pid 1, root's): not looked at (-2)"); + DWORD s = 0; + check(RmStartSession(&s, 0, nullptr) == ERROR_SUCCESS && RmEndSession(s) == ERROR_SUCCESS && RmEndSession(s) == ERROR_INVALID_HANDLE, "Restart Manager: a session ends once"); + UINT z = 0, zn = 0; + check(RmGetList(s, &z, &zn, nullptr, &reasons) == ERROR_INVALID_HANDLE, "Restart Manager: an ended session: ERROR_INVALID_HANDLE"); + RM_UNIQUE_PROCESS app{}; + RmStartSession(&s, 0, nullptr); + check(RmRegisterResources(s, 0, nullptr, 1, &app, 0, nullptr) == ERROR_NOT_SUPPORTED, "Restart Manager: registering applications: ERROR_NOT_SUPPORTED"); + RmEndSession(s); +} + +// ---- a Windows program under Wine with a WrongGPU binary loaded: a write open is refused, as Windows refuses one of a +// loaded image (the operation guard's game check). The "game" is this program started again under a Windows program's name. +pid_t StartNamed(const char* argv0, const std::vector& args) { + const std::string self = SelfExe(); + std::vector argv{const_cast(argv0)}; + for (auto& a : args) argv.push_back(const_cast(a.c_str())); + argv.push_back(nullptr); + pid_t pid = 0; + return posix_spawn(&pid, self.c_str(), nullptr, nullptr, argv.data(), environ) == 0 ? pid : 0; +} +void StopNamed(pid_t pid) { + if (pid <= 0) return; + kill(pid, SIGKILL); + waitpid(pid, nullptr, 0); +} +DWORD WriteOpen(const std::wstring& p) { // the guard's open: 0, or the error + HANDLE h = CreateFileW(p.c_str(), DELETE | GENERIC_READ | FILE_WRITE_DATA, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + if (h == INVALID_HANDLE_VALUE) return GetLastError(); + CloseHandle(h); + return 0; +} +const char* kGame = "C:\\Games\\Some Game\\Game.exe"; // as Wine spells a Windows program's command line + +void GameImage() { + const std::wstring dir = In(L"img-game"), dll = dir + L"\\wronggpu_runtime.dll", ini = dir + L"\\wronggpu.ini"; + CreateDirectoryW(dir.c_str(), nullptr); + Put(dll, "MZ stand-in runtime"); + Put(ini, "[wronggpu]\r\n"); + check(WriteOpen(dll) == 0, "game check: nobody has the DLL loaded: the guard's write open works"); + // running: a Windows program under Wine has it mapped + const std::string ready = PosixOf(In(L"ready-img1")); + pid_t game = StartNamed(kGame, {"--child-map", PosixOf(dll), ready}); + check(game && WaitReady(ready), "game check: (a Windows program under Wine has the DLL mapped)"); + check(WriteOpen(dll) == ERROR_SHARING_VIOLATION, "game check: the game has it loaded: a write open fails with ERROR_SHARING_VIOLATION"); + HANDLE t = CreateFileW(dll.c_str(), GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + check(t == INVALID_HANDLE_VALUE && GetLastError() == ERROR_SHARING_VIOLATION && Slurp(dll) == "MZ stand-in runtime", "game check: ...a truncating open too, whatever it shares; the file as it was"); + if (t != INVALID_HANDLE_VALUE) CloseHandle(t); + HANDLE r = CreateFileW(dll.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + check(r != INVALID_HANDLE_VALUE, "game check: ...a read open still works (Windows lets a loaded image be read)"); + if (r != INVALID_HANDLE_VALUE) CloseHandle(r); + { + wgstate::OperationGuard g(Tmp, {dll, ini}, 500); + check(g.result() == wgstate::GuardResult::GameRunning && g.which() == dll && std::string(g.words()).find("Close the game") != std::string::npos, + "game check: the operation guard: GameRunning, the DLL named, the words say to close the game"); + } + StopNamed(game); + check(WriteOpen(dll) == 0, "game check: the game ended: the write open works again"); + { + wgstate::OperationGuard g(Tmp, {dll, ini}, 500); + check(g.ok(), "game check: the operation guard: Ok once the game ended"); + } + // not the game: a native program with the DLL mapped (a data mapping: Windows does not refuse that either), and a file that + // is not a Windows image mapped by the game + const std::string ready2 = PosixOf(In(L"ready-img2")), ready3 = PosixOf(In(L"ready-img3")); + pid_t native = StartNamed("/usr/bin/some-native-tool", {"--child-map", PosixOf(dll), ready2}); + check(native && WaitReady(ready2) && WriteOpen(dll) == 0, "game check: a native (not Wine) program has the DLL mapped: not the game, the write open works"); + StopNamed(native); + const std::string ready6 = PosixOf(In(L"ready-img6")); + pid_t loader = StartNamed("/opt/proton/files/bin/wine64-preloader", {"--child-map", PosixOf(dll), ready6}); + check(loader && WaitReady(ready6) && WriteOpen(dll) == ERROR_SHARING_VIOLATION, + "game check: a Wine process named without a Windows path (wine*, or start.exe as Wine names it) with the DLL mapped: refused too"); + StopNamed(loader); + game = StartNamed(kGame, {"--child-map", PosixOf(ini), ready3}); + check(game && WaitReady(ready3) && WriteOpen(ini) == 0, "game check: the game has a file mapped that is not a Windows image: the write open works"); + StopNamed(game); + // unreadable: a Wine process of this user whose maps cannot be read (not dumpable): it cannot be ruled out + const std::string ready4 = PosixOf(In(L"ready-img4")), ready5 = PosixOf(In(L"ready-img5")); + pid_t closed = StartNamed(kGame, {"--child-nodump", ready4}); + check(closed && WaitReady(ready4), "game check: (a Wine process whose maps cannot be read)"); + int who = 0; + struct stat st; + stat(PosixOf(dll).c_str(), &st); + check(wgposix::ImageInUse(st.st_dev, st.st_ino, &who) == -1 && who == closed, "game check: the scan says it cannot rule that process out (-1, its pid)"); + check(WriteOpen(dll) == ERROR_CANT_ACCESS_FILE, "game check: ...the write open fails with ERROR_CANT_ACCESS_FILE (could not tell), not a sharing violation"); + { + wgstate::OperationGuard g(Tmp, {dll, ini}, 500); + check(g.result() == wgstate::GuardResult::Unknown && std::string(g.words()).find("could not tell") != std::string::npos && + std::string(g.words()).find("close the game") != std::string::npos, + "game check: the operation guard: Unknown, the words say it could not tell and to close the game"); + } + StopNamed(closed); + pid_t closedNative = StartNamed("/usr/bin/some-native-tool", {"--child-nodump", ready5}); + check(closedNative && WaitReady(ready5) && WriteOpen(dll) == 0, "game check: an unreadable process that is not a Wine program: not counted, the write open works"); + StopNamed(closedNative); +} + +// ---- FileRenameInfo without replace on a file system that lacks RENAME_NOREPLACE: link, then unlink of the old name. When +// that unlink fails the new name goes again and the call fails, so the file keeps only its old name (review fix). +void RenameFallback() { + const auto realRename = wgposix::g_renameat2; + const auto realUnlink = wgposix::g_unlink; + wgposix::g_renameat2 = [](int, const char*, int, const char*, unsigned int) { errno = EINVAL; return -1; }; + const std::wstring src = In(L"fb-src"), dst = In(L"fb-dst"); + CreateDirectoryW(src.c_str(), nullptr); + CreateDirectoryW(dst.c_str(), nullptr); + Put(src + L"\\a.dll", "MZ a"); + Put(dst + L"\\taken.dll", "MZ taken"); + HANDLE h = OpenFor(src + L"\\a.dll", DELETE | GENERIC_READ, FILE_SHARE_READ); + check(!RenameTo(h, dst + L"\\taken.dll", false) && GetLastError() == ERROR_ALREADY_EXISTS && Slurp(dst + L"\\taken.dll") == "MZ taken", + "rename fallback (no RENAME_NOREPLACE): onto a file: ERROR_ALREADY_EXISTS, nothing replaced"); + check(RenameTo(h, dst + L"\\a.dll", false) && !Exists(src + L"\\a.dll") && Slurp(dst + L"\\a.dll") == "MZ a", + "rename fallback: link then unlink: the file has only its new name"); + CloseHandle(h); + // the source folder refuses the unlink (read-only), the target folder allows the link + Put(src + L"\\c.dll", "MZ c"); + h = OpenFor(src + L"\\c.dll", DELETE | GENERIC_READ, FILE_SHARE_READ); + if (geteuid() == 0) { + std::printf("posix-layer: running as root: the read-only source folder check is skipped\n"); + } else { + chmod(PosixOf(src).c_str(), 0555); + const bool ok = RenameTo(h, dst + L"\\c.dll", false); + const DWORD e = GetLastError(); + chmod(PosixOf(src).c_str(), 0755); + check(!ok && e == ERROR_ACCESS_DENIED && Exists(src + L"\\c.dll") && !Exists(dst + L"\\c.dll"), + "rename fallback: the old name cannot be removed: the call fails (access denied) and the file keeps only its old name"); + check(SetDisposition(h, FILE_DISPOSITION_FLAG_DELETE | FILE_DISPOSITION_FLAG_POSIX_SEMANTICS) && !Exists(src + L"\\c.dll"), + "rename fallback: ...the handle still names the old name (a delete through it removes that one)"); + } + CloseHandle(h); + // neither unlink works (the old name's nor the undo's): the call still fails; both names are left (said in win32_posix.h) + Put(src + L"\\d.dll", "MZ d"); + h = OpenFor(src + L"\\d.dll", DELETE | GENERIC_READ, FILE_SHARE_READ); + wgposix::g_unlink = [](const char*) { errno = EIO; return -1; }; + const bool ok = RenameTo(h, dst + L"\\d.dll", false); + wgposix::g_unlink = realUnlink; + check(!ok && Exists(src + L"\\d.dll") && Exists(dst + L"\\d.dll"), "rename fallback: the undo fails too: the call still fails, both names are left"); + CloseHandle(h); + wgposix::g_renameat2 = realRename; +} + +int main(int argc, char** argv) { + if (argc >= 2 && std::strncmp(argv[1], "--child-", 8) == 0) return ChildMain(argc, argv); + // a registry file of this run's own, and a folder of its own, both under TMPDIR + wchar_t t[MAX_PATH]{}; + GetTempPathW(MAX_PATH, t); + Tmp = std::wstring(t) + L"wg-posix-layer-" + std::to_wstring(GetCurrentProcessId()); + CreateDirectoryW(Tmp.c_str(), nullptr); + const std::string regFile = std::string(getenv("TMPDIR") ? getenv("TMPDIR") : "/tmp") + "/wg-posix-layer-" + std::to_string(GetCurrentProcessId()) + ".ini"; + setenv("WRONGGPU_REGISTRY_FILE", regFile.c_str(), 1); + Paths(); + Files(); + Times(); + Strings(); + Registry(); + Processes(); + ProcessImage(); + Suspended(); + SuspendedStart(); + CaseFolding(); + RegistryWrites(); + FinishedChildren(); + NotAvailable(); + GpuIdentity(); + AppImageIdentity(); + DownloadsOff(); + Folders(); + ErrorValues(); + BasicInfo(); + Disposition(); + EndOfFile(); + PinnedPattern(); + LinksAndReparse(); + ReplaceFile(); + ProcessEnd(); + NamedMutex(); + Events(); + RenameByHandle(); + LongPathAndSecurity(); + RestartManager(); + GameImage(); + RenameFallback(); + std::remove(regFile.c_str()); + std::error_code ec; + std::string posixTmp(Tmp.begin(), Tmp.end()); + posixTmp.erase(0, 2); // "Z:" goes, "\\" becomes "/" + for (auto& c : posixTmp) if (c == '\\') c = '/'; + std::filesystem::remove_all(posixTmp, ec); + std::printf("posix-layer: %d checks, %d failed\n", checks, failures); + return failures ? 1 : 0; +} diff --git a/clean/installer/src/platform/posix/tlhelp32.h b/clean/installer/src/platform/posix/tlhelp32.h new file mode 100644 index 00000000..b13ed666 --- /dev/null +++ b/clean/installer/src/platform/posix/tlhelp32.h @@ -0,0 +1,4 @@ +// SPDX-License-Identifier: MIT +// Linux: stands in for the Windows header of the same name (win32_posix.h). +#pragma once +#include "win32_posix.h" diff --git a/clean/installer/src/platform/posix/uxtheme.h b/clean/installer/src/platform/posix/uxtheme.h new file mode 100644 index 00000000..638cfb9a --- /dev/null +++ b/clean/installer/src/platform/posix/uxtheme.h @@ -0,0 +1,4 @@ +// SPDX-License-Identifier: MIT +// Linux: stands in for the Windows header of the same name (win32_window.h). +#pragma once +#include "win32_window.h" diff --git a/clean/installer/src/platform/posix/win32_posix.cpp b/clean/installer/src/platform/posix/win32_posix.cpp new file mode 100644 index 00000000..91694631 --- /dev/null +++ b/clean/installer/src/platform/posix/win32_posix.cpp @@ -0,0 +1,1516 @@ +// SPDX-License-Identifier: MIT +// Linux: Windows file, string, time, environment and shell calls on POSIX (see win32_posix.h). Registry and processes are in +// win32_posix_registry.cpp and win32_posix_process.cpp. +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "win32_posix_internal.h" + +extern char** environ; + +namespace wgposix { + +// ---- last error -------------------------------------------------------------------------------------------------------- +static thread_local DWORD g_lastError = 0; + +// ---- handle table ------------------------------------------------------------------------------------------------------ +static std::mutex g_handleLock; +// The tables here are never destroyed: the program's own globals (wg::app::App's Context cleans up in its destructor, which runs +// during exit) still call into this layer, and a table already destroyed by then is a crash at exit. +static auto& g_handles = *new std::unordered_set; +Handle* NewHandle(Kind k) { + Handle* h = new Handle(k); + std::lock_guard g(g_handleLock); + g_handles.insert(h); + return h; +} +Handle* Lookup(HANDLE hv, Kind k) { + Handle* h = static_cast(hv); + std::lock_guard g(g_handleLock); + if (!hv || hv == INVALID_HANDLE_VALUE || !g_handles.count(h) || h->kind != k) { g_lastError = ERROR_INVALID_HANDLE; return nullptr; } + return h; +} +static Handle* LookupAny(HANDLE hv) { + Handle* h = static_cast(hv); + std::lock_guard g(g_handleLock); + if (!hv || hv == INVALID_HANDLE_VALUE || !g_handles.count(h)) { g_lastError = ERROR_INVALID_HANDLE; return nullptr; } + return h; +} +void Forget(Handle* h) { + { + std::lock_guard g(g_handleLock); + g_handles.erase(h); + } + delete h; +} + +// ---- UTF-8 --------------------------------------------------------------------------------------------------------------- +std::string ToUtf8(const wchar_t* s, size_t n) { + std::string o; + o.reserve(n); + for (size_t i = 0; i < n; ++i) { + const uint32_t c = (uint32_t)s[i]; + if (c >= 0xDC80 && c <= 0xDCFF) o += (char)(c - 0xDC00); + else if (c < 0x80) o += (char)c; + else if (c < 0x800) { o += (char)(0xC0 | (c >> 6)); o += (char)(0x80 | (c & 0x3F)); } + else if ((c >= 0xD800 && c <= 0xDFFF) || c > 0x10FFFF) o += "\xEF\xBF\xBD"; + else if (c < 0x10000) { o += (char)(0xE0 | (c >> 12)); o += (char)(0x80 | ((c >> 6) & 0x3F)); o += (char)(0x80 | (c & 0x3F)); } + else { o += (char)(0xF0 | (c >> 18)); o += (char)(0x80 | ((c >> 12) & 0x3F)); o += (char)(0x80 | ((c >> 6) & 0x3F)); o += (char)(0x80 | (c & 0x3F)); } + } + return o; +} +// One sequence at s[i]: its length and code point, or 0 when the bytes there are not valid UTF-8. +static size_t DecodeOne(const unsigned char* s, size_t n, size_t i, uint32_t& cp) { + const unsigned char b = s[i]; + if (b < 0x80) { cp = b; return 1; } + size_t len = b >= 0xF0 && b <= 0xF4 ? 4 : b >= 0xE0 ? 3 : b >= 0xC2 && b < 0xE0 ? 2 : 0; + if (b >= 0xF5 || !len || i + len > n) return 0; + cp = b & (0xFF >> (len + 1)); + for (size_t k = 1; k < len; ++k) { + if ((s[i + k] & 0xC0) != 0x80) return 0; + cp = (cp << 6) | (s[i + k] & 0x3F); + } + if ((len == 3 && (cp < 0x800 || (cp >= 0xD800 && cp <= 0xDFFF))) || (len == 4 && (cp < 0x10000 || cp > 0x10FFFF))) return 0; + return len; +} +std::wstring FromUtf8(const char* s, size_t n) { + std::wstring w; + w.reserve(n); + const unsigned char* u = reinterpret_cast(s); + for (size_t i = 0; i < n;) { + uint32_t cp; + const size_t len = DecodeOne(u, n, i, cp); + if (!len) { w += (wchar_t)(0xDC00 + u[i]); ++i; } + else { w += (wchar_t)cp; i += len; } + } + return w; +} + +// Case folding for names: Unicode simple case mapping through a C.UTF-8 locale object of our own, so the process locale stays as +// it is; without that locale, whatever towlower does in the current one. +wint_t FoldChar(wint_t c) { + static const locale_t loc = newlocale(LC_CTYPE_MASK, "C.UTF-8", (locale_t)0); + return loc ? towlower_l(towupper_l(c, loc), loc) : towlower(towupper(c)); +} + +// ---- paths ------------------------------------------------------------------------------------------------------------- +std::string FixCase(const std::string& p) { + struct stat st; + if (p.empty() || lstat(p.c_str(), &st) == 0) return p; + std::string out; + size_t pos = 0; + bool broken = false; + if (p[0] == '/') { out = "/"; pos = 1; } + for (;;) { + size_t e = p.find('/', pos); + const bool last = e == std::string::npos; + if (last) e = p.size(); + std::string comp = p.substr(pos, e - pos); + if (!comp.empty() && comp != "." && comp != ".." && !broken && lstat((out + comp).c_str(), &st) != 0) { + bool found = false; + const std::wstring wcomp = FromUtf8(comp); + if (DIR* d = opendir(out.empty() ? "." : out.c_str())) { + while (dirent* ent = readdir(d)) { + if (_wcsicmp(FromUtf8(ent->d_name, std::strlen(ent->d_name)).c_str(), wcomp.c_str()) == 0) { comp = ent->d_name; found = true; break; } + } + closedir(d); + } + if (!found) broken = true; + } + out += comp; + if (last) break; + out += '/'; + pos = e + 1; + } + return out; +} +bool ToPosix(const wchar_t* w, std::string& out, DWORD& err) { + if (!w || !*w) { err = ERROR_PATH_NOT_FOUND; return false; } + std::wstring s(w); + if (s.rfind(L"\\\\?\\", 0) == 0 || s.rfind(L"//?/", 0) == 0) { + s.erase(0, 4); + if (s.size() >= 4 && _wcsnicmp(s.c_str(), L"UNC\\", 4) == 0) { err = ERROR_PATH_NOT_FOUND; return false; } + } else if (s.rfind(L"\\\\.\\", 0) == 0 || s.rfind(L"//./", 0) == 0) { + err = ERROR_PATH_NOT_FOUND; + return false; + } + if (s.size() >= 2 && s[1] == L':' && ((s[0] >= L'A' && s[0] <= L'Z') || (s[0] >= L'a' && s[0] <= L'z'))) { + if ((s[0] == L'Z' || s[0] == L'z') && (s.size() == 2 || s[2] == L'\\' || s[2] == L'/')) { s.erase(0, 2); if (s.empty()) s = L"/"; } + else { err = ERROR_PATH_NOT_FOUND; return false; } + } + // names Windows refuses (ERROR_INVALID_NAME), so the core's handling of them is the one it has there + if (s.find_first_of(L"<>\"|?*") != std::wstring::npos || std::any_of(s.begin(), s.end(), [](wchar_t c) { return c < 0x20; })) { err = ERROR_INVALID_NAME; return false; } + for (auto& c : s) if (c == L'\\') c = L'/'; + out = FixCase(ToUtf8(s)); + return true; +} +bool ToPosix(const wchar_t* w, std::string& out) { + DWORD e = 0; + if (ToPosix(w, out, e)) return true; + g_lastError = e; + return false; +} + +DWORD ErrorFromErrno(int e, const std::string& path) { + switch (e) { + case ENOENT: { + const size_t cut = path.find_last_of('/'); + struct stat st; + if (cut != std::string::npos && cut > 0 && stat(path.substr(0, cut).c_str(), &st) != 0) return ERROR_PATH_NOT_FOUND; + return ERROR_FILE_NOT_FOUND; + } + case ENOTDIR: return ERROR_PATH_NOT_FOUND; + case EACCES: case EPERM: case EROFS: case EISDIR: case EBADF: return ERROR_ACCESS_DENIED; + case EEXIST: return ERROR_ALREADY_EXISTS; + case ENOTEMPTY: return ERROR_DIR_NOT_EMPTY; + case ENOSPC: case EDQUOT: return ERROR_DISK_FULL; + case EXDEV: return ERROR_NOT_SAME_DEVICE; + case EBUSY: case ETXTBSY: return ERROR_SHARING_VIOLATION; + case EMFILE: case ENFILE: return ERROR_TOO_MANY_OPEN_FILES; + case ENAMETOOLONG: return ERROR_FILENAME_EXCED_RANGE; + case EFBIG: return ERROR_FILE_TOO_LARGE; + case EPIPE: return ERROR_BROKEN_PIPE; + case ENOMEM: return ERROR_NOT_ENOUGH_MEMORY; + case EINVAL: return ERROR_INVALID_PARAMETER; + case ENOEXEC: return ERROR_BAD_EXE_FORMAT; + default: return ERROR_GEN_FAILURE; + } +} +void SetErrorFromErrno(int e, const std::string& path) { g_lastError = ErrorFromErrno(e, path); } + +// The hidden attribute has no mode bit; it is kept as a user attribute of the file (a file system without them just never shows it). +static const char* const kHiddenXattr = "user.wronggpu.hidden"; +static bool IsHiddenPath(const std::string& path) { return lgetxattr(path.c_str(), kHiddenXattr, nullptr, 0) >= 0; } +static void SetHiddenPath(const std::string& path, bool hidden) { + if (hidden) lsetxattr(path.c_str(), kHiddenXattr, "1", 1, 0); + else lremovexattr(path.c_str(), kHiddenXattr); +} +DWORD AttributesOf(const struct stat& lst, const std::string& path) { + DWORD a = 0; + if (!S_ISLNK(lst.st_mode) && IsHiddenPath(path)) a |= FILE_ATTRIBUTE_HIDDEN; + if (S_ISLNK(lst.st_mode)) { + a |= FILE_ATTRIBUTE_REPARSE_POINT; + struct stat t; + if (stat(path.c_str(), &t) == 0 && S_ISDIR(t.st_mode)) a |= FILE_ATTRIBUTE_DIRECTORY; + } else if (S_ISDIR(lst.st_mode)) { + a |= FILE_ATTRIBUTE_DIRECTORY; + } else if (!(lst.st_mode & S_IWUSR)) { + a |= FILE_ATTRIBUTE_READONLY; + } + return a ? a : FILE_ATTRIBUTE_NORMAL; +} +// The read-only attribute as a mode: no write bit at all, or the owner's back. SetFileAttributesW and SetFileInformationByHandle share it. +static mode_t ModeWithReadOnly(mode_t mode, bool readOnly) { + const mode_t m = mode & 07777; + return readOnly ? (m & ~(mode_t)(S_IWUSR | S_IWGRP | S_IWOTH)) : (m | S_IWUSR); +} +FILETIME FileTimeOf(const struct timespec& t) { + const uint64_t v = ((uint64_t)((int64_t)t.tv_sec + 11644473600LL)) * 10000000ull + (uint64_t)t.tv_nsec / 100; + return FILETIME{(DWORD)(v & 0xFFFFFFFFu), (DWORD)(v >> 32)}; +} +struct timespec TimespecOf(const FILETIME& ft) { + const uint64_t v = ((uint64_t)ft.dwHighDateTime << 32) | ft.dwLowDateTime; + struct timespec t; + t.tv_sec = (time_t)((int64_t)(v / 10000000ull) - 11644473600LL); + t.tv_nsec = (long)((v % 10000000ull) * 100); + return t; +} +void FillFind(WIN32_FIND_DATAW& d, const struct stat& lst, const std::string& path, const std::string& name) { + std::memset(&d, 0, sizeof(d)); + d.dwFileAttributes = AttributesOf(lst, path); + d.ftCreationTime = FileTimeOf(lst.st_ctim); + d.ftLastAccessTime = FileTimeOf(lst.st_atim); + d.ftLastWriteTime = FileTimeOf(lst.st_mtim); + const uint64_t size = (d.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? 0 : (uint64_t)lst.st_size; + d.nFileSizeHigh = (DWORD)(size >> 32); + d.nFileSizeLow = (DWORD)(size & 0xFFFFFFFFu); + const std::wstring w = FromUtf8(name); + wcsncpy(d.cFileName, w.c_str(), MAX_PATH - 1); +} + +// ---- sharing (what Windows' share modes do between handles of this process) ------------------------------------------------ +static std::mutex g_shareLock; +static auto& g_shared = *new std::vector; +static bool Conflicts(dev_t dev, ino_t ino, bool wantR, bool wantW, bool wantD, DWORD share) { + for (Handle* e : g_shared) { + if (e->dev != dev || e->ino != ino) continue; + if ((wantR && !(e->share & FILE_SHARE_READ)) || (wantW && !(e->share & FILE_SHARE_WRITE)) || (wantD && !(e->share & FILE_SHARE_DELETE)) || + (e->read && !(share & FILE_SHARE_READ)) || (e->write && !(share & FILE_SHARE_WRITE)) || (e->del && !(share & FILE_SHARE_DELETE))) + return true; + } + return false; +} +bool ShareAllowsDelete(const struct stat& st) { + std::lock_guard g(g_shareLock); + return !Conflicts(st.st_dev, st.st_ino, false, false, true, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE); +} + +} // namespace wgposix + +using namespace wgposix; + +// The Windows spelling of an absolute POSIX path: drive Z:, backslashes (the core's path code, and FullPath's equality tests, +// are written for that form). Relative paths come back as they are. +std::wstring wgposix::WinPath(const std::string& posix) { + std::wstring w = FromUtf8(posix); + if (w.empty() || w[0] != L'/') return w; + for (auto& c : w) if (c == L'/') c = L'\\'; + return L"Z:" + w; +} + +DWORD GetLastError() { return g_lastError; } +void SetLastError(DWORD e) { g_lastError = e; } + +// ---- files ------------------------------------------------------------------------------------------------------------- +// A Windows program or DLL: its first bytes are "MZ" (what a Windows program under Wine loads as an image). +static bool IsWindowsImage(const std::string& p) { + const int fd = open(p.c_str(), O_RDONLY | O_CLOEXEC); + if (fd < 0) return false; + char mz[2] = {}; + const bool image = pread(fd, mz, 2, 0) == 2 && mz[0] == 'M' && mz[1] == 'Z'; + close(fd); + return image; +} +HANDLE CreateFileW(LPCWSTR name, DWORD access, DWORD share, LPSECURITY_ATTRIBUTES, DWORD disposition, DWORD flags, HANDLE) { + std::string p; + if (!ToPosix(name, p)) return INVALID_HANDLE_VALUE; + const bool wantR = access & (GENERIC_READ | GENERIC_ALL | FILE_READ_DATA); + const bool wantW = access & (GENERIC_WRITE | GENERIC_ALL | FILE_WRITE_DATA | FILE_APPEND_DATA); + const bool deleteOnClose = flags & FILE_FLAG_DELETE_ON_CLOSE; + const bool wantD = (access & (DELETE | GENERIC_ALL)) || deleteOnClose; + struct stat lst, st; + const bool exists = lstat(p.c_str(), &lst) == 0, linked = exists && S_ISLNK(lst.st_mode); + const bool target = exists && (!linked || stat(p.c_str(), &st) == 0); + if (target && !linked) st = lst; + if (target && S_ISDIR(st.st_mode)) { + if (!(flags & FILE_FLAG_BACKUP_SEMANTICS) || wantW || disposition == CREATE_ALWAYS || disposition == CREATE_NEW || disposition == TRUNCATE_EXISTING) { + SetLastError(disposition == CREATE_NEW ? ERROR_FILE_EXISTS : ERROR_ACCESS_DENIED); + return INVALID_HANDLE_VALUE; + } + } + if (disposition == CREATE_NEW && exists) { SetLastError(ERROR_FILE_EXISTS); return INVALID_HANDLE_VALUE; } + if ((disposition == OPEN_EXISTING || disposition == TRUNCATE_EXISTING) && !target) { + SetErrorFromErrno(ENOENT, p); + return INVALID_HANDLE_VALUE; + } + const bool truncate = disposition == CREATE_ALWAYS || disposition == TRUNCATE_EXISTING; + if (target && !S_ISDIR(st.st_mode) && (wantW || truncate) && !(st.st_mode & S_IWUSR)) { SetLastError(ERROR_ACCESS_DENIED); return INVALID_HANDLE_VALUE; } + if (target && S_ISREG(st.st_mode) && (wantW || truncate) && IsWindowsImage(p)) { // Windows' image check (win32_posix.h) + const int used = ImageInUse(st.st_dev, st.st_ino); + if (used) { SetLastError(used > 0 ? ERROR_SHARING_VIOLATION : ERROR_CANT_ACCESS_FILE); return INVALID_HANDLE_VALUE; } + } + int oflags = O_CLOEXEC | (wantR && wantW ? O_RDWR : wantW ? O_WRONLY : O_RDONLY); + if ((access & FILE_APPEND_DATA) && !(access & (GENERIC_WRITE | GENERIC_ALL | FILE_WRITE_DATA))) oflags |= O_APPEND; // append-only access + if (disposition == CREATE_NEW) oflags |= O_CREAT | O_EXCL; + else if (disposition == CREATE_ALWAYS || disposition == OPEN_ALWAYS) oflags |= O_CREAT; + if (linked && (flags & FILE_FLAG_OPEN_REPARSE_POINT)) oflags = O_CLOEXEC | O_PATH | O_NOFOLLOW; + const int fd = open(p.c_str(), oflags, (flags & FILE_ATTRIBUTE_READONLY) ? 0444 : 0666); + if (fd < 0) { + if (errno == EEXIST && disposition == CREATE_NEW) SetLastError(ERROR_FILE_EXISTS); + else SetErrorFromErrno(errno, p); + return INVALID_HANDLE_VALUE; + } + struct stat fs; + if (fstat(fd, &fs) != 0) { SetErrorFromErrno(errno, p); close(fd); return INVALID_HANDLE_VALUE; } + Handle* h = NewHandle(Kind::File); + h->fd = fd; h->path = p; h->dev = fs.st_dev; h->ino = fs.st_ino; + h->read = wantR; h->write = wantW; h->del = wantD; h->share = share; h->deleteOnClose = deleteOnClose; + if ((wantR || wantW || wantD) && !S_ISDIR(fs.st_mode)) { + std::lock_guard g(g_shareLock); + if (Conflicts(fs.st_dev, fs.st_ino, wantR, wantW, wantD, share)) { + close(fd); + Forget(h); + SetLastError(ERROR_SHARING_VIOLATION); + return INVALID_HANDLE_VALUE; + } + g_shared.push_back(h); + h->tracked = true; + } + if (truncate && exists && S_ISREG(fs.st_mode) && fs.st_size > 0 && ftruncate(fd, 0) != 0) { + SetErrorFromErrno(errno, p); + CloseHandle(h); + return INVALID_HANDLE_VALUE; + } + SetLastError(exists && (disposition == CREATE_ALWAYS || disposition == OPEN_ALWAYS) ? (DWORD)ERROR_ALREADY_EXISTS : 0u); + return h; +} + +BOOL ReadFile(HANDLE hv, LPVOID buf, DWORD n, LPDWORD got, OVERLAPPED*) { + Handle* h = LookupAny(hv); + if (!h || (h->kind != Kind::File && h->kind != Kind::Pipe)) return Fail(ERROR_INVALID_HANDLE); + ssize_t r; + do r = read(h->fd, buf, n); while (r < 0 && errno == EINTR); + if (r < 0) { SetErrorFromErrno(errno, ""); return FALSE; } + if (got) *got = (DWORD)r; + if (r == 0 && h->kind == Kind::Pipe && n) return Fail(ERROR_BROKEN_PIPE); + return TRUE; +} +BOOL WriteFile(HANDLE hv, LPCVOID buf, DWORD n, LPDWORD wrote, OVERLAPPED*) { + Handle* h = LookupAny(hv); + if (!h || (h->kind != Kind::File && h->kind != Kind::Pipe)) return Fail(ERROR_INVALID_HANDLE); + DWORD done = 0; + while (done < n) { + const ssize_t r = write(h->fd, static_cast(buf) + done, n - done); + if (r < 0) { + if (errno == EINTR) continue; + if (wrote) *wrote = done; + SetErrorFromErrno(errno, ""); + return FALSE; + } + done += (DWORD)r; + } + if (wrote) *wrote = done; + return TRUE; +} +BOOL CloseHandle(HANDLE hv) { + Handle* h = LookupAny(hv); + if (!h) return FALSE; + switch (h->kind) { + case Kind::File: + if (h->tracked) { + std::lock_guard g(g_shareLock); + g_shared.erase(std::remove(g_shared.begin(), g_shared.end(), h), g_shared.end()); + } + if (h->fd >= 0) close(h->fd); + if (h->deleteOnClose) { // the file this handle opened, not whatever was put under its name since + struct stat now; + if (lstat(h->path.c_str(), &now) == 0 && now.st_dev == h->dev && now.st_ino == h->ino) unlink(h->path.c_str()); + } + break; + case Kind::Mutex: CloseMutex(h); if (h->fd >= 0) close(h->fd); break; + case Kind::Pipe: case Kind::Map: if (h->fd >= 0 && !h->borrowed) close(h->fd); break; + case Kind::Job: ReleaseJob(h); break; + case Kind::Process: ReleaseProcess(h); break; + default: break; + } + Forget(h); + return TRUE; +} +BOOL FlushFileBuffers(HANDLE hv) { + Handle* h = Lookup(hv, Kind::File); + if (!h) return FALSE; + if (fsync(h->fd) != 0 && errno != EINVAL && errno != EROFS) { SetErrorFromErrno(errno, h->path); return FALSE; } + return TRUE; +} +BOOL GetFileSizeEx(HANDLE hv, LARGE_INTEGER* size) { + Handle* h = Lookup(hv, Kind::File); + struct stat st; + if (!h) return FALSE; + if (fstat(h->fd, &st) != 0) { SetErrorFromErrno(errno, h->path); return FALSE; } + size->QuadPart = S_ISDIR(st.st_mode) ? 0 : st.st_size; + return TRUE; +} +BOOL SetFilePointerEx(HANDLE hv, LARGE_INTEGER dist, LARGE_INTEGER* newPos, DWORD method) { + Handle* h = Lookup(hv, Kind::File); + if (!h) return FALSE; + const off_t r = lseek(h->fd, (off_t)dist.QuadPart, method == FILE_BEGIN ? SEEK_SET : method == FILE_CURRENT ? SEEK_CUR : SEEK_END); + if (r < 0) { SetErrorFromErrno(errno, h->path); return FALSE; } + if (newPos) newPos->QuadPart = r; + return TRUE; +} +BOOL GetFileTime(HANDLE hv, FILETIME* created, FILETIME* accessed, FILETIME* written) { + Handle* h = Lookup(hv, Kind::File); + struct stat st; + if (!h) return FALSE; + if (fstat(h->fd, &st) != 0) { SetErrorFromErrno(errno, h->path); return FALSE; } + if (created) *created = FileTimeOf(st.st_ctim); + if (accessed) *accessed = FileTimeOf(st.st_atim); + if (written) *written = FileTimeOf(st.st_mtim); + return TRUE; +} +BOOL SetFileTime(HANDLE hv, const FILETIME*, const FILETIME* accessed, const FILETIME* written) { + Handle* h = Lookup(hv, Kind::File); + if (!h) return FALSE; + struct timespec ts[2] = {{0, UTIME_OMIT}, {0, UTIME_OMIT}}; + if (accessed) ts[0] = TimespecOf(*accessed); + if (written) ts[1] = TimespecOf(*written); + if (futimens(h->fd, ts) != 0) { SetErrorFromErrno(errno, h->path); return FALSE; } + return TRUE; +} +BOOL GetFileInformationByHandle(HANDLE hv, BY_HANDLE_FILE_INFORMATION* info) { + Handle* h = Lookup(hv, Kind::File); + struct stat st; + if (!h) return FALSE; + if (fstat(h->fd, &st) != 0) { SetErrorFromErrno(errno, h->path); return FALSE; } + std::memset(info, 0, sizeof(*info)); + struct stat lst; + info->dwFileAttributes = lstat(h->path.c_str(), &lst) == 0 && lst.st_ino == st.st_ino ? AttributesOf(lst, h->path) : FILE_ATTRIBUTE_NORMAL; + info->ftCreationTime = FileTimeOf(st.st_ctim); + info->ftLastAccessTime = FileTimeOf(st.st_atim); + info->ftLastWriteTime = FileTimeOf(st.st_mtim); + info->dwVolumeSerialNumber = (DWORD)st.st_dev; + info->nFileSizeHigh = (DWORD)((uint64_t)st.st_size >> 32); + info->nFileSizeLow = (DWORD)((uint64_t)st.st_size & 0xFFFFFFFFu); + info->nNumberOfLinks = (DWORD)st.st_nlink; + info->nFileIndexHigh = (DWORD)((uint64_t)st.st_ino >> 32); + info->nFileIndexLow = (DWORD)((uint64_t)st.st_ino & 0xFFFFFFFFu); + return TRUE; +} +BOOL GetFileInformationByHandleEx(HANDLE hv, FILE_INFO_BY_HANDLE_CLASS cls, LPVOID info, DWORD size) { + Handle* h = Lookup(hv, Kind::File); + struct stat st; + if (!h) return FALSE; + if (cls != FileIdInfo && cls != FileBasicInfo) return Fail(ERROR_INVALID_PARAMETER); + if (size < (cls == FileIdInfo ? sizeof(FILE_ID_INFO) : sizeof(FILE_BASIC_INFO))) return Fail(ERROR_INSUFFICIENT_BUFFER); + if (fstat(h->fd, &st) != 0) { SetErrorFromErrno(errno, h->path); return FALSE; } + if (cls == FileBasicInfo) { + FILE_BASIC_INFO* bi = static_cast(info); + std::memset(bi, 0, sizeof(*bi)); + struct stat lst; + bi->FileAttributes = lstat(h->path.c_str(), &lst) == 0 && lst.st_ino == st.st_ino ? AttributesOf(lst, h->path) : FILE_ATTRIBUTE_NORMAL; + const FILETIME c = FileTimeOf(st.st_ctim), a = FileTimeOf(st.st_atim), w = FileTimeOf(st.st_mtim); + bi->CreationTime.QuadPart = (LONGLONG)(((uint64_t)c.dwHighDateTime << 32) | c.dwLowDateTime); // as GetFileTime: the status change time + bi->ChangeTime = bi->CreationTime; + bi->LastAccessTime.QuadPart = (LONGLONG)(((uint64_t)a.dwHighDateTime << 32) | a.dwLowDateTime); + bi->LastWriteTime.QuadPart = (LONGLONG)(((uint64_t)w.dwHighDateTime << 32) | w.dwLowDateTime); + return TRUE; + } + FILE_ID_INFO* fi = static_cast(info); + std::memset(fi, 0, sizeof(*fi)); + fi->VolumeSerialNumber = (ULONGLONG)st.st_dev; + const uint64_t ino = (uint64_t)st.st_ino; + std::memcpy(fi->FileId.Identifier, &ino, sizeof(ino)); + return TRUE; +} +int (*wgposix::g_renameat2)(int, const char*, int, const char*, unsigned int) = ::renameat2; +int (*wgposix::g_unlink)(const char*) = ::unlink; +// FileRenameInfo (win32_posix.h has what it guarantees). The handle's name now is the one /proc/self/fd gives (renames since +// the open included), used only while it still names the handle's file. +static BOOL RenameByHandle(Handle* h, const struct stat& st, const FILE_RENAME_INFO* ri, DWORD size) { + const size_t head = offsetof(FILE_RENAME_INFO, FileName); + if (size < head || ri->FileNameLength % sizeof(WCHAR) || size < head + ri->FileNameLength || !ri->FileNameLength) return Fail(ERROR_INVALID_PARAMETER); + if (ri->RootDirectory) return Fail(ERROR_INVALID_PARAMETER); // a name relative to a folder handle: no caller needs it + if (!h->del) return Fail(ERROR_ACCESS_DENIED); // renaming needs DELETE access + std::wstring name(ri->FileName, ri->FileNameLength / sizeof(WCHAR)); + if (name.rfind(L"\\??\\", 0) == 0) name.replace(0, 4, L"\\\\?\\"); // the NT form of a full path + std::string to, from = h->path; + if (!ToPosix(name.c_str(), to)) return FALSE; + char cur[4096]; + const ssize_t n = readlink(("/proc/self/fd/" + std::to_string(h->fd)).c_str(), cur, sizeof(cur) - 1); + if (n > 0) from.assign(cur, (size_t)n); + struct stat now, dest; + if (from.empty() || lstat(from.c_str(), &now) != 0 || now.st_dev != st.st_dev || now.st_ino != st.st_ino) return Fail(ERROR_FILE_NOT_FOUND); + if (lstat(to.c_str(), &dest) == 0) { + if (dest.st_dev == st.st_dev && dest.st_ino == st.st_ino) { h->path = to; return TRUE; } // it has that name already + if (!ri->ReplaceIfExists) return Fail(ERROR_ALREADY_EXISTS); + if (S_ISDIR(dest.st_mode) || (!S_ISLNK(dest.st_mode) && !(dest.st_mode & S_IWUSR))) return Fail(ERROR_ACCESS_DENIED); // a folder, a read-only file + if (!ShareAllowsDelete(dest)) return Fail(ERROR_ACCESS_DENIED); // a file open here without delete sharing (Windows: access denied) + } + int r; + if (ri->ReplaceIfExists) { + r = rename(from.c_str(), to.c_str()); + } else { + r = g_renameat2(AT_FDCWD, from.c_str(), AT_FDCWD, to.c_str(), RENAME_NOREPLACE); + if (r != 0 && (errno == EINVAL || errno == ENOSYS)) { // a file system without RENAME_NOREPLACE: a new link never replaces either + r = link(from.c_str(), to.c_str()); + if (r == 0 && g_unlink(from.c_str()) != 0) { // the old name cannot go: the new one goes again, the call fails + const int e = errno; + g_unlink(to.c_str()); // (if this fails too, both names are left; the failure is still the result) + errno = e; + r = -1; + } else if (r != 0 && (errno == EPERM || errno == EOPNOTSUPP)) { // nor hard links (FAT, exFAT, a folder): checked, then renamed + struct stat x; + if (lstat(to.c_str(), &x) == 0) { errno = EEXIST; r = -1; } + else r = rename(from.c_str(), to.c_str()); + } + } + } + if (r != 0) { + const int e = errno; + if (e == EEXIST || e == ENOTEMPTY) return Fail(ERROR_ALREADY_EXISTS); + SetErrorFromErrno(e, to); + return FALSE; + } + h->path = to; // a later delete through the handle, or its delete on close, goes to the new name + return TRUE; +} +// Attributes and times through a handle (a time of 0 and attributes of 0 stay as they are), a rename, and the two ways to delete through one. +BOOL SetFileInformationByHandle(HANDLE hv, FILE_INFO_BY_HANDLE_CLASS cls, LPVOID info, DWORD size) { + Handle* h = Lookup(hv, Kind::File); + if (!h) return FALSE; + struct stat st; + if (fstat(h->fd, &st) != 0) { SetErrorFromErrno(errno, h->path); return FALSE; } + if (cls == FileBasicInfo) { + if (size < sizeof(FILE_BASIC_INFO)) return Fail(ERROR_BAD_LENGTH); + const FILE_BASIC_INFO* b = static_cast(info); + // Only the access and write times can be set here: the creation time has no place on this file system, and the change time is the kernel's. + struct timespec ts[2] = {{0, UTIME_OMIT}, {0, UTIME_OMIT}}; + bool times = false; + if (b->LastAccessTime.QuadPart > 0) { ts[0] = TimespecOf(FILETIME{(DWORD)(b->LastAccessTime.QuadPart & 0xFFFFFFFFu), (DWORD)((uint64_t)b->LastAccessTime.QuadPart >> 32)}); times = true; } + if (b->LastWriteTime.QuadPart > 0) { ts[1] = TimespecOf(FILETIME{(DWORD)(b->LastWriteTime.QuadPart & 0xFFFFFFFFu), (DWORD)((uint64_t)b->LastWriteTime.QuadPart >> 32)}); times = true; } + if (b->FileAttributes && !h->path.empty()) SetHiddenPath(h->path, b->FileAttributes & FILE_ATTRIBUTE_HIDDEN); + if (b->FileAttributes && !S_ISDIR(st.st_mode)) { // (as SetFileAttributesW: a folder has no read-only bit here) + const mode_t m = ModeWithReadOnly(st.st_mode, b->FileAttributes & FILE_ATTRIBUTE_READONLY); + if (m != (st.st_mode & 07777) && fchmod(h->fd, m) != 0) { SetErrorFromErrno(errno, h->path); return FALSE; } + } + if (times && futimens(h->fd, ts) != 0) { SetErrorFromErrno(errno, h->path); return FALSE; } + return TRUE; + } + if (cls == FileRenameInfo) return RenameByHandle(h, st, static_cast(info), size); + if (cls != FileDispositionInfo && cls != FileDispositionInfoEx) return Fail(ERROR_INVALID_PARAMETER); + if (size < (cls == FileDispositionInfo ? sizeof(FILE_DISPOSITION_INFO) : sizeof(FILE_DISPOSITION_INFO_EX))) return Fail(ERROR_BAD_LENGTH); + bool del, posix = false, ignoreReadOnly = false; + if (cls == FileDispositionInfo) { + del = static_cast(info)->DeleteFile != 0; + } else { + const DWORD f = static_cast(info)->Flags; + del = f & FILE_DISPOSITION_FLAG_DELETE; + posix = f & FILE_DISPOSITION_FLAG_POSIX_SEMANTICS; + ignoreReadOnly = f & FILE_DISPOSITION_FLAG_IGNORE_READONLY_ATTRIBUTE; + } + if (!del) { h->deleteOnClose = false; return TRUE; } // "do not delete" takes back an earlier request + if (!h->del) return Fail(ERROR_ACCESS_DENIED); // deleting needs DELETE access + if (S_ISDIR(st.st_mode)) return Fail(ERROR_NOT_SUPPORTED); // (folders are removed by name here) + if (!ignoreReadOnly && !(st.st_mode & S_IWUSR)) return Fail(ERROR_ACCESS_DENIED); // a read-only file is not deleted unless told to + if (!posix) { h->deleteOnClose = true; return TRUE; } // classic: the name goes when the handle closes + struct stat now; + if (h->path.empty() || lstat(h->path.c_str(), &now) != 0 || now.st_dev != st.st_dev || now.st_ino != st.st_ino) return Fail(ERROR_FILE_NOT_FOUND); + if (unlink(h->path.c_str()) != 0) { SetErrorFromErrno(errno, h->path); return FALSE; } + h->deleteOnClose = false; + h->path.clear(); // the name is free; this handle no longer has one + return TRUE; +} +BOOL SetEndOfFile(HANDLE hv) { + Handle* h = Lookup(hv, Kind::File); + if (!h) return FALSE; + const int fl = fcntl(h->fd, F_GETFL); + if (fl < 0 || (fl & O_PATH) || (fl & O_ACCMODE) == O_RDONLY) return Fail(ERROR_ACCESS_DENIED); // truncating needs write access + const off_t pos = lseek(h->fd, 0, SEEK_CUR); + if (pos < 0) { SetErrorFromErrno(errno, h->path); return FALSE; } + if (ftruncate(h->fd, pos) != 0) { SetErrorFromErrno(errno, h->path); return FALSE; } + return TRUE; +} +DWORD GetFinalPathNameByHandleW(HANDLE hv, LPWSTR out, DWORD size, DWORD) { + Handle* h = Lookup(hv, Kind::File); + if (!h) return 0; + char link[4096]; + const ssize_t n = readlink(("/proc/self/fd/" + std::to_string(h->fd)).c_str(), link, sizeof(link) - 1); + if (n < 0) { SetErrorFromErrno(errno, h->path); return 0; } + const std::wstring w = WinPath(std::string(link, (size_t)n)); + if (!out || size < w.size() + 1) return (DWORD)w.size() + 1; + std::memcpy(out, w.c_str(), (w.size() + 1) * sizeof(wchar_t)); + return (DWORD)w.size(); +} +DWORD GetFileAttributesW(LPCWSTR name) { + std::string p; + struct stat st; + if (!ToPosix(name, p)) return INVALID_FILE_ATTRIBUTES; + if (lstat(p.c_str(), &st) != 0) { SetErrorFromErrno(errno, p); return INVALID_FILE_ATTRIBUTES; } + return AttributesOf(st, p); +} +BOOL GetFileAttributesExW(LPCWSTR name, GET_FILEEX_INFO_LEVELS, LPVOID data) { + std::string p; + struct stat st; + if (!ToPosix(name, p)) return FALSE; + if (lstat(p.c_str(), &st) != 0) { SetErrorFromErrno(errno, p); return FALSE; } + WIN32_FIND_DATAW f; + FillFind(f, st, p, "x"); + WIN32_FILE_ATTRIBUTE_DATA* d = static_cast(data); + d->dwFileAttributes = f.dwFileAttributes; + d->ftCreationTime = f.ftCreationTime; d->ftLastAccessTime = f.ftLastAccessTime; d->ftLastWriteTime = f.ftLastWriteTime; + d->nFileSizeHigh = f.nFileSizeHigh; d->nFileSizeLow = f.nFileSizeLow; + return TRUE; +} +BOOL SetFileAttributesW(LPCWSTR name, DWORD attrs) { + std::string p; + struct stat st; + if (!ToPosix(name, p)) return FALSE; + if (stat(p.c_str(), &st) != 0) { SetErrorFromErrno(errno, p); return FALSE; } + SetHiddenPath(p, attrs & FILE_ATTRIBUTE_HIDDEN); + if (S_ISDIR(st.st_mode)) return TRUE; // a read-only folder on Windows still takes files; chmod would not mean that + const mode_t m = ModeWithReadOnly(st.st_mode, attrs & FILE_ATTRIBUTE_READONLY); + if (m != (st.st_mode & 07777) && chmod(p.c_str(), m) != 0) { SetErrorFromErrno(errno, p); return FALSE; } + return TRUE; +} +BOOL DeleteFileW(LPCWSTR name) { + std::string p; + struct stat st; + if (!ToPosix(name, p)) return FALSE; + if (lstat(p.c_str(), &st) != 0) { SetErrorFromErrno(errno, p); return FALSE; } + if (S_ISDIR(st.st_mode)) return Fail(ERROR_ACCESS_DENIED); + if (!S_ISLNK(st.st_mode) && !(st.st_mode & S_IWUSR)) return Fail(ERROR_ACCESS_DENIED); + if (!ShareAllowsDelete(st)) return Fail(ERROR_SHARING_VIOLATION); + if (unlink(p.c_str()) != 0) { SetErrorFromErrno(errno, p); return FALSE; } + return TRUE; +} +static bool CopyData(const std::string& from, const std::string& to, mode_t keepMode, bool keepTimes, DWORD& err); +BOOL MoveFileExW(LPCWSTR from, LPCWSTR to, DWORD flags) { + std::string a, b; + struct stat sa, sb; + if (!ToPosix(from, a)) return FALSE; + if (flags & MOVEFILE_DELAY_UNTIL_REBOOT) return Fail(ERROR_CALL_NOT_IMPLEMENTED); + if (!to) return Fail(ERROR_CALL_NOT_IMPLEMENTED); + if (!ToPosix(to, b)) return FALSE; + if (lstat(a.c_str(), &sa) != 0) { SetErrorFromErrno(errno, a); return FALSE; } + const bool destExists = lstat(b.c_str(), &sb) == 0; + if (!ShareAllowsDelete(sa)) return Fail(ERROR_SHARING_VIOLATION); + if (destExists) { + if (sa.st_dev == sb.st_dev && sa.st_ino == sb.st_ino && !S_ISLNK(sa.st_mode)) return TRUE; + if (!(flags & MOVEFILE_REPLACE_EXISTING)) return Fail(ERROR_ALREADY_EXISTS); + if (S_ISDIR(sb.st_mode) || S_ISDIR(sa.st_mode)) return Fail(ERROR_ACCESS_DENIED); + if (!S_ISLNK(sb.st_mode) && !(sb.st_mode & S_IWUSR)) return Fail(ERROR_ACCESS_DENIED); + if (!ShareAllowsDelete(sb)) return Fail(ERROR_SHARING_VIOLATION); + } + if (rename(a.c_str(), b.c_str()) != 0) { + const int e = errno; + if (e == EXDEV && (flags & MOVEFILE_COPY_ALLOWED) && S_ISREG(sa.st_mode)) { + DWORD err = 0; + if (!CopyData(a, b, sa.st_mode, true, err)) return Fail(err); + unlink(a.c_str()); + return TRUE; + } + SetErrorFromErrno(e, e == ENOENT ? b : a); + return FALSE; + } + if (flags & MOVEFILE_WRITE_THROUGH) { + const int fd = open(b.c_str(), O_RDONLY | O_CLOEXEC); + if (fd >= 0) { fsync(fd); close(fd); } + const size_t cut = b.find_last_of('/'); + const std::string dir = cut == std::string::npos ? "." : cut == 0 ? "/" : b.substr(0, cut); + const int dfd = open(dir.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC); + if (dfd >= 0) { fsync(dfd); close(dfd); } + } + return TRUE; +} +// The replacement takes the replaced file's name in one rename, and the replaced file (if a backup name is given) takes the backup name. +// The failure codes say what is left: 1175, nothing moved; 1177, the replaced file is at the backup name and the replacement is +// still under its own. (Windows' 1176, the replaced file gone and the replacement not moved, cannot arise here.) +BOOL ReplaceFileW(LPCWSTR replaced, LPCWSTR replacement, LPCWSTR backup, DWORD flags, LPVOID exclude, LPVOID reserved) { + std::string a, b, bak; + struct stat sa, sb; + if (exclude || reserved) return Fail(ERROR_INVALID_PARAMETER); + if (!ToPosix(replaced, a) || !ToPosix(replacement, b)) return FALSE; + if (backup && !ToPosix(backup, bak)) return FALSE; + if (lstat(a.c_str(), &sa) != 0) { SetErrorFromErrno(errno, a); return FALSE; } + if (lstat(b.c_str(), &sb) != 0) { SetErrorFromErrno(errno, b); return FALSE; } + if (S_ISDIR(sa.st_mode) || S_ISDIR(sb.st_mode)) return Fail(ERROR_ACCESS_DENIED); + if (!S_ISLNK(sa.st_mode) && !(sa.st_mode & S_IWUSR)) return Fail(ERROR_ACCESS_DENIED); // a read-only file is not replaced + if (!ShareAllowsDelete(sb)) return Fail(ERROR_SHARING_VIOLATION); + if (!ShareAllowsDelete(sa)) return Fail(ERROR_UNABLE_TO_REMOVE_REPLACED); + if (sa.st_dev == sb.st_dev && sa.st_ino == sb.st_ino) return Fail(ERROR_UNABLE_TO_REMOVE_REPLACED); + if (!S_ISLNK(sa.st_mode)) { // the replaced file's attributes stay (as Windows keeps them) + chmod(b.c_str(), sa.st_mode & 07777); + SetHiddenPath(b, IsHiddenPath(a)); + } + // without a backup name one rename does it all (the name never goes missing); when it fails nothing has moved + if (backup && rename(a.c_str(), bak.c_str()) != 0) return Fail(ERROR_UNABLE_TO_REMOVE_REPLACED); + if (rename(b.c_str(), a.c_str()) != 0) return Fail(backup ? ERROR_UNABLE_TO_MOVE_REPLACEMENT_2 : ERROR_UNABLE_TO_REMOVE_REPLACED); + if (flags & REPLACEFILE_WRITE_THROUGH) { + const size_t cut = a.find_last_of('/'); + const std::string dir = cut == std::string::npos ? "." : cut == 0 ? "/" : a.substr(0, cut); + const int dfd = open(dir.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC); + if (dfd >= 0) { fsync(dfd); close(dfd); } + } + return TRUE; +} +static bool CopyData(const std::string& from, const std::string& to, mode_t keepMode, bool keepTimes, DWORD& err) { + const int in = open(from.c_str(), O_RDONLY | O_CLOEXEC); + if (in < 0) { err = ErrorFromErrno(errno, from); return false; } + struct stat st; + fstat(in, &st); + const int out = open(to.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0666); + if (out < 0) { err = ErrorFromErrno(errno, to); close(in); return false; } + char buf[1 << 16]; + bool ok = true; + for (;;) { + const ssize_t r = read(in, buf, sizeof(buf)); + if (r < 0) { if (errno == EINTR) continue; err = ErrorFromErrno(errno, from); ok = false; break; } + if (r == 0) break; + for (ssize_t done = 0; done < r;) { + const ssize_t w = write(out, buf + done, (size_t)(r - done)); + if (w < 0) { if (errno == EINTR) continue; err = ErrorFromErrno(errno, to); ok = false; break; } + done += w; + } + if (!ok) break; + } + if (ok && keepTimes) { struct timespec ts[2] = {st.st_atim, st.st_mtim}; futimens(out, ts); } + if (ok) fchmod(out, keepMode & 07777); + close(in); + if (close(out) != 0 && ok) { err = ErrorFromErrno(errno, to); ok = false; } + if (!ok) unlink(to.c_str()); + return ok; +} +BOOL CopyFileW(LPCWSTR from, LPCWSTR to, BOOL failIfExists) { + std::string a, b; + struct stat sa, sb; + if (!ToPosix(from, a) || !ToPosix(to, b)) return FALSE; + if (stat(a.c_str(), &sa) != 0) { SetErrorFromErrno(errno, a); return FALSE; } + if (S_ISDIR(sa.st_mode)) return Fail(ERROR_ACCESS_DENIED); + if (stat(b.c_str(), &sb) == 0) { + if (failIfExists) return Fail(ERROR_FILE_EXISTS); + if (S_ISDIR(sb.st_mode) || !(sb.st_mode & S_IWUSR)) return Fail(ERROR_ACCESS_DENIED); + if (sa.st_dev == sb.st_dev && sa.st_ino == sb.st_ino) return Fail(ERROR_SHARING_VIOLATION); + std::lock_guard g(g_shareLock); + if (Conflicts(sb.st_dev, sb.st_ino, false, true, false, 0)) return Fail(ERROR_SHARING_VIOLATION); + } + { + std::lock_guard g(g_shareLock); + for (Handle* e : g_shared) // the source is read with FILE_SHARE_READ: a writer that denies readers blocks the copy + if (e->dev == sa.st_dev && e->ino == sa.st_ino && !(e->share & FILE_SHARE_READ)) return Fail(ERROR_SHARING_VIOLATION); + } + DWORD err = 0; + if (!CopyData(a, b, sa.st_mode, true, err)) return Fail(err); + return TRUE; +} +BOOL CreateDirectoryW(LPCWSTR name, LPSECURITY_ATTRIBUTES) { + std::string p; + if (!ToPosix(name, p)) return FALSE; + if (mkdir(p.c_str(), 0777) != 0) { SetErrorFromErrno(errno, p); return FALSE; } + return TRUE; +} +BOOL RemoveDirectoryW(LPCWSTR name) { + std::string p; + struct stat st; + if (!ToPosix(name, p)) return FALSE; + if (lstat(p.c_str(), &st) != 0) { SetErrorFromErrno(errno, p); return FALSE; } + if (S_ISLNK(st.st_mode)) { // a junction or directory symbolic link goes without touching its target + struct stat t; + if (stat(p.c_str(), &t) == 0 && !S_ISDIR(t.st_mode)) return Fail(ERROR_DIRECTORY); + if (unlink(p.c_str()) != 0) { SetErrorFromErrno(errno, p); return FALSE; } + return TRUE; + } + if (!S_ISDIR(st.st_mode)) return Fail(ERROR_DIRECTORY); + if (rmdir(p.c_str()) != 0) { SetErrorFromErrno(errno, p); return FALSE; } + return TRUE; +} +BOOL CreateHardLinkW(LPCWSTR link, LPCWSTR existing, LPSECURITY_ATTRIBUTES) { + std::string a, b; + if (!ToPosix(link, a) || !ToPosix(existing, b)) return FALSE; + if (::link(b.c_str(), a.c_str()) != 0) { SetErrorFromErrno(errno, errno == ENOENT ? b : a); return FALSE; } + return TRUE; +} +BOOL CreateSymbolicLinkW(LPCWSTR link, LPCWSTR target, DWORD) { + std::string a, b; + if (!ToPosix(link, a)) return FALSE; + if (!target || !*target) return Fail(ERROR_INVALID_PARAMETER); + std::wstring t = target; + for (auto& c : t) if (c == L'\\') c = L'/'; + if (t.size() >= 2 && t[1] == L':') { if (!ToPosix(target, b)) return FALSE; } // a drive-lettered target maps the same way + else b = ToUtf8(t); + if (::symlink(b.c_str(), a.c_str()) != 0) { SetErrorFromErrno(errno, a); return FALSE; } + return TRUE; +} +// There is no cmd.exe: every command "fails" (1), except `mklink /J "link" "folder"`, which the tests use to make a junction. A +// junction becomes a symbolic link to the folder: the nearest thing here (a reparse point that RemoveTree must not follow). +int _wsystem(const wchar_t* cmd) { + const std::wstring c = cmd ? cmd : L""; + const size_t at = c.find(L"mklink /J "); + if (at == std::wstring::npos) return 1; + std::vector q; // the quoted arguments + for (size_t i = at; i < c.size();) { + const size_t a = c.find(L'"', i), b = a == std::wstring::npos ? a : c.find(L'"', a + 1); + if (b == std::wstring::npos) break; + q.push_back(c.substr(a + 1, b - a - 1)); + i = b + 1; + } + if (q.size() != 2 || (GetFileAttributesW(q[1].c_str()) & FILE_ATTRIBUTE_DIRECTORY) == 0) return 1; + return CreateSymbolicLinkW(q[0].c_str(), q[1].c_str(), SYMBOLIC_LINK_FLAG_DIRECTORY) ? 0 : 1; +} +BOOL CopyFileExW(LPCWSTR from, LPCWSTR to, void*, LPVOID, BOOL*, DWORD flags) { + std::string a, b; + struct stat sa, sb; + if ((flags & COPY_FILE_COPY_SYMLINK) && ToPosix(from, a) && lstat(a.c_str(), &sa) == 0 && S_ISLNK(sa.st_mode)) { + if (!ToPosix(to, b)) return FALSE; + char target[4096]; + const ssize_t n = readlink(a.c_str(), target, sizeof(target) - 1); + if (n < 0) { SetErrorFromErrno(errno, a); return FALSE; } + target[n] = 0; + if (lstat(b.c_str(), &sb) == 0) { + if (flags & COPY_FILE_FAIL_IF_EXISTS) return Fail(ERROR_FILE_EXISTS); + if (S_ISDIR(sb.st_mode) || unlink(b.c_str()) != 0) return Fail(ERROR_ACCESS_DENIED); + } + if (::symlink(target, b.c_str()) != 0) { SetErrorFromErrno(errno, b); return FALSE; } + return TRUE; + } + return CopyFileW(from, to, (flags & COPY_FILE_FAIL_IF_EXISTS) != 0); +} +DWORD GetFileType(HANDLE hv) { + Handle* h = LookupAny(hv); + struct stat st; + if (!h || (h->kind != Kind::File && h->kind != Kind::Pipe) || fstat(h->fd, &st) != 0) return FILE_TYPE_UNKNOWN; + return S_ISREG(st.st_mode) || S_ISDIR(st.st_mode) || S_ISBLK(st.st_mode) ? FILE_TYPE_DISK : S_ISCHR(st.st_mode) ? FILE_TYPE_CHAR : FILE_TYPE_PIPE; +} +BOOL SetThreadErrorMode(DWORD, LPDWORD old) { if (old) *old = 0; return TRUE; } // no error dialogs exist +DWORD GetLogicalDrives() { return 1u << ('Z' - 'A'); } +FILE* _wfopen(const wchar_t* path, const wchar_t* mode) { + std::string p; + if (!ToPosix(path, p)) { errno = ENOENT; return nullptr; } + return std::fopen(p.c_str(), ToUtf8(mode, wcslen(mode)).c_str()); +} +// stdin, stdout and stderr as handles ReadFile and WriteFile take; their descriptors stay open +HANDLE GetStdHandle(DWORD which) { + static Handle* std3[3] = {}; + static std::once_flag once; + std::call_once(once, [] { for (int i = 0; i < 3; ++i) { std3[i] = NewHandle(Kind::Pipe); std3[i]->fd = i; std3[i]->borrowed = true; } }); + const int n = which == STD_INPUT_HANDLE ? 0 : which == STD_OUTPUT_HANDLE ? 1 : which == STD_ERROR_HANDLE ? 2 : -1; + if (n < 0) { SetLastError(ERROR_INVALID_HANDLE); return INVALID_HANDLE_VALUE; } + return std3[n]; +} + +// FindFirstFileW: the folder's entries are read at once, matched against the wildcard and sorted as NTFS lists them. +static bool WildMatch(const wchar_t* p, const wchar_t* s) { + if (!*p) return !*s; + if (*p == L'*') { + while (*p == L'*') ++p; + if (!*p) return true; + for (; *s; ++s) if (WildMatch(p, s)) return true; + return WildMatch(p, s); + } + if (!*s) return false; + return (*p == L'?' || FoldChar((wint_t)*p) == FoldChar((wint_t)*s)) && WildMatch(p + 1, s + 1); +} +HANDLE FindFirstFileW(LPCWSTR pattern, WIN32_FIND_DATAW* data) { + if (!pattern || !*pattern) { SetLastError(ERROR_PATH_NOT_FOUND); return INVALID_HANDLE_VALUE; } + std::wstring w = pattern; + for (auto& c : w) if (c == L'\\') c = L'/'; + const size_t cut = w.find_last_of(L'/'); + const std::wstring dirW = cut == std::wstring::npos ? L"." : cut == 0 ? L"/" : w.substr(0, cut), pat = cut == std::wstring::npos ? w : w.substr(cut + 1); + std::string dir; + if (!ToPosix(dirW.c_str(), dir)) return INVALID_HANDLE_VALUE; + struct stat st; + if (stat(dir.c_str(), &st) != 0 || !S_ISDIR(st.st_mode)) { SetLastError(ERROR_PATH_NOT_FOUND); return INVALID_HANDLE_VALUE; } + DIR* d = opendir(dir.c_str()); + if (!d) { SetErrorFromErrno(errno, dir); return INVALID_HANDLE_VALUE; } + std::vector found; + const bool wild = pat.find_first_of(L"*?") != std::wstring::npos; + while (dirent* ent = readdir(d)) { + const std::wstring name = FromUtf8(ent->d_name, std::strlen(ent->d_name)); + if (!WildMatch(pat == L"*.*" ? L"*" : pat.c_str(), name.c_str())) continue; + if (!wild && std::strcmp(ent->d_name, ".") != 0 && std::strcmp(ent->d_name, "..") != 0 && name.size() != pat.size()) continue; + struct stat lst; + const std::string full = (dir == "/" ? std::string() : dir) + "/" + ent->d_name; + if (lstat(full.c_str(), &lst) != 0) continue; + WIN32_FIND_DATAW f; + FillFind(f, lst, full, ent->d_name); + found.push_back(f); + } + closedir(d); + std::sort(found.begin(), found.end(), [](const WIN32_FIND_DATAW& a, const WIN32_FIND_DATAW& b) { + const bool da = !wcscmp(a.cFileName, L".") || !wcscmp(a.cFileName, L".."), db = !wcscmp(b.cFileName, L".") || !wcscmp(b.cFileName, L".."); + if (da != db) return da; + return _wcsicmp(a.cFileName, b.cFileName) < 0; + }); + if (found.empty()) { SetLastError(ERROR_FILE_NOT_FOUND); return INVALID_HANDLE_VALUE; } + Handle* h = NewHandle(Kind::Find); + h->found = std::move(found); + *data = h->found[0]; + h->next = 1; + return h; +} +HANDLE FindFirstFileExW(LPCWSTR pattern, FINDEX_INFO_LEVELS, LPVOID data, FINDEX_SEARCH_OPS, LPVOID, DWORD) { + return FindFirstFileW(pattern, static_cast(data)); +} +BOOL FindNextFileW(HANDLE hv, WIN32_FIND_DATAW* data) { + Handle* h = Lookup(hv, Kind::Find); + if (!h) return FALSE; + if (h->next >= h->found.size()) return Fail(ERROR_NO_MORE_FILES); + *data = h->found[h->next++]; + return TRUE; +} +BOOL FindClose(HANDLE hv) { + Handle* h = Lookup(hv, Kind::Find); + if (!h) return FALSE; + Forget(h); + return TRUE; +} + +// "C:\a\.\b\..\c" is "C:\a\c": "." and ".." fold, separators become backslashes, a relative path gets the current folder (Z:) in +// front. A drive other than Z is only spelled, never looked at. Nothing needs to exist. +DWORD GetLongPathNameW(LPCWSTR shortPath, LPWSTR out, DWORD size) { + std::string p; + struct stat st; + if (!ToPosix(shortPath, p)) return 0; + if (lstat(p.c_str(), &st) != 0) { SetErrorFromErrno(errno, p); return 0; } + const std::wstring w = (std::wstring(shortPath).rfind(L"\\\\?\\", 0) == 0 ? L"\\\\?\\" : L"") + WinPath(p); + if (!out || size < w.size() + 1) return (DWORD)w.size() + 1; + std::memcpy(out, w.c_str(), (w.size() + 1) * sizeof(wchar_t)); + return (DWORD)w.size(); +} +DWORD GetFullPathNameW(LPCWSTR name, DWORD size, LPWSTR out, LPWSTR* filePart) { + if (!name || !*name) { SetLastError(ERROR_PATH_NOT_FOUND); return 0; } + std::wstring raw = name, drive; + if (raw.rfind(L"\\\\?\\", 0) == 0) raw.erase(0, 4); + if (raw.size() >= 2 && raw[1] == L':' && iswalpha((wint_t)raw[0])) { drive = raw.substr(0, 2); raw.erase(0, 2); } + const bool rooted = !raw.empty() && (raw[0] == L'/' || raw[0] == L'\\'); + if (!rooted && !drive.empty() && towupper((wint_t)drive[0]) != L'Z') { SetLastError(ERROR_PATH_NOT_FOUND); return 0; } + if (!rooted) { + char cwd[4096]; + if (!getcwd(cwd, sizeof(cwd))) { SetErrorFromErrno(errno, ""); return 0; } + raw = FromUtf8(cwd, std::strlen(cwd)) + L"/" + raw; + if (drive.empty()) drive = L"Z:"; + } + if (drive.empty()) drive = L"Z:"; + std::vector parts; + size_t i = 0; + while (i <= raw.size()) { + size_t j = raw.find_first_of(L"/\\", i); + if (j == std::wstring::npos) j = raw.size(); + const std::wstring c = raw.substr(i, j - i); + if (c == L"..") { if (!parts.empty()) parts.pop_back(); } + else if (!c.empty() && c != L".") parts.push_back(c); + i = j + 1; + } + std::wstring w = drive; + for (auto& c : parts) { w += L'\\'; w += c; } + if (parts.empty() || raw.back() == L'/' || raw.back() == L'\\') w += L'\\'; + if (size < w.size() + 1) return (DWORD)w.size() + 1; + std::memcpy(out, w.c_str(), (w.size() + 1) * sizeof(wchar_t)); + if (filePart) { + const size_t slash = w.find_last_of(L'\\'); + *filePart = (slash == std::wstring::npos || slash + 1 >= w.size()) ? nullptr : out + slash + 1; + } + return (DWORD)w.size(); +} +static DWORD CopyOut(const std::wstring& w, LPWSTR out, DWORD size) { + if (!out || size < w.size() + 1) return (DWORD)w.size() + 1; + std::memcpy(out, w.c_str(), (w.size() + 1) * sizeof(wchar_t)); + return (DWORD)w.size(); +} +DWORD GetTempPathW(DWORD size, LPWSTR out) { + const char* t = getenv("TMPDIR"); + std::string d = t && *t ? t : "/tmp"; + if (d.back() != '/') d += '/'; + return CopyOut(WinPath(d), out, size); +} +DWORD GetCurrentDirectoryW(DWORD size, LPWSTR out) { + char cwd[4096]; + if (!getcwd(cwd, sizeof(cwd))) { SetErrorFromErrno(errno, ""); return 0; } + return CopyOut(WinPath(cwd), out, size); +} +BOOL SetCurrentDirectoryW(LPCWSTR dir) { + std::string p; + if (!ToPosix(dir, p)) return FALSE; + if (chdir(p.c_str()) != 0) { SetErrorFromErrno(errno, p); return FALSE; } + return TRUE; +} +// There is no System32. This folder exists and holds no cmd.exe, no PING.EXE and no Windows DLL, so what the core +// builds from it fails to start or to load (cleanly). +DWORD GetSystemDirectoryW(LPWSTR out, DWORD size) { return CopyOut(L"Z:\\usr\\bin", out, size); } +DWORD GetModuleFileNameW(HMODULE m, LPWSTR out, DWORD size) { + if (m) { SetLastError(ERROR_MOD_NOT_FOUND); return 0; } + char b[4096]; + const ssize_t n = readlink("/proc/self/exe", b, sizeof(b) - 1); + if (n < 0) { SetErrorFromErrno(errno, ""); return 0; } + const std::wstring w = WinPath(std::string(b, (size_t)n)); + if (size == 0) return 0; + const size_t k = std::min(w.size(), size - 1); + std::memcpy(out, w.c_str(), k * sizeof(wchar_t)); + out[k] = 0; + if (k < w.size()) { SetLastError(ERROR_INSUFFICIENT_BUFFER); return size; } + return (DWORD)k; +} +BOOL GetDiskFreeSpaceExW(LPCWSTR dir, ULARGE_INTEGER* available, ULARGE_INTEGER* total, ULARGE_INTEGER* freeBytes) { + std::string p; + struct statvfs vs; + if (!ToPosix(dir, p)) return FALSE; + if (statvfs(p.c_str(), &vs) != 0) { SetErrorFromErrno(errno, p); return FALSE; } + if (available) available->QuadPart = (ULONGLONG)vs.f_bavail * vs.f_frsize; + if (total) total->QuadPart = (ULONGLONG)vs.f_blocks * vs.f_frsize; + if (freeBytes) freeBytes->QuadPart = (ULONGLONG)vs.f_bfree * vs.f_frsize; + return TRUE; +} + +// memory-mapped files +static std::mutex g_viewLock; +static auto& g_views = *new std::map; +HANDLE CreateFileMappingW(HANDLE file, LPSECURITY_ATTRIBUTES, DWORD protect, DWORD sizeHigh, DWORD sizeLow, LPCWSTR) { + Handle* f = Lookup(file, Kind::File); + struct stat st; + if (!f) return nullptr; + if (fstat(f->fd, &st) != 0) { SetErrorFromErrno(errno, f->path); return nullptr; } + const uint64_t asked = ((uint64_t)sizeHigh << 32) | sizeLow, size = asked ? asked : (uint64_t)st.st_size; + if (!size) { SetLastError(ERROR_FILE_INVALID); return nullptr; } + if ((!f->read && !f->write) || (protect != PAGE_READONLY && !f->write)) { SetLastError(ERROR_ACCESS_DENIED); return nullptr; } + Handle* m = NewHandle(Kind::Map); + m->fd = fcntl(f->fd, F_DUPFD_CLOEXEC, 0); + m->mapSize = size; + m->mapProtect = protect; + if (m->fd < 0) { SetErrorFromErrno(errno, f->path); Forget(m); return nullptr; } + return m; +} +LPVOID MapViewOfFile(HANDLE map, DWORD access, DWORD offsetHigh, DWORD offsetLow, SIZE_T bytes) { + Handle* m = Lookup(map, Kind::Map); + if (!m) return nullptr; + const uint64_t off = ((uint64_t)offsetHigh << 32) | offsetLow; + if (off >= m->mapSize) { SetLastError(ERROR_INVALID_PARAMETER); return nullptr; } + const size_t len = bytes ? bytes : (size_t)(m->mapSize - off); + int prot = PROT_READ, mode = MAP_SHARED; + if (access & FILE_MAP_WRITE) { if (m->mapProtect != PAGE_READWRITE) { SetLastError(ERROR_ACCESS_DENIED); return nullptr; } prot |= PROT_WRITE; } + if (access & FILE_MAP_COPY) { mode = MAP_PRIVATE; prot |= PROT_WRITE; } + void* v = mmap(nullptr, len, prot, mode, m->fd, (off_t)off); + if (v == MAP_FAILED) { SetErrorFromErrno(errno, ""); return nullptr; } + std::lock_guard g(g_viewLock); + g_views[v] = len; + return v; +} +BOOL UnmapViewOfFile(LPCVOID base) { + size_t len = 0; + { + std::lock_guard g(g_viewLock); + auto it = g_views.find(base); + if (it == g_views.end()) return Fail(ERROR_INVALID_PARAMETER); + len = it->second; + g_views.erase(it); + } + munmap(const_cast(base), len); + return TRUE; +} + +// ---- strings ----------------------------------------------------------------------------------------------------------- +int MultiByteToWideChar(UINT, DWORD flags, const char* s, int n, wchar_t* out, int outN) { + if (!s || n == 0) { SetLastError(ERROR_INVALID_PARAMETER); return 0; } + const size_t len = n < 0 ? std::strlen(s) + 1 : (size_t)n; + if (flags & MB_ERR_INVALID_CHARS) { + const unsigned char* u = reinterpret_cast(s); + for (size_t i = 0; i < len;) { uint32_t cp; const size_t k = DecodeOne(u, len, i, cp); if (!k) { SetLastError(ERROR_NO_UNICODE_TRANSLATION); return 0; } i += k; } + } + std::wstring w = FromUtf8(s, len); + for (auto& c : w) if ((uint32_t)c >= 0xDC80 && (uint32_t)c <= 0xDCFF) c = 0xFFFD; + if (outN == 0) return (int)w.size(); + if ((size_t)outN < w.size()) { SetLastError(ERROR_INSUFFICIENT_BUFFER); return 0; } + std::memcpy(out, w.data(), w.size() * sizeof(wchar_t)); + return (int)w.size(); +} +int WideCharToMultiByte(UINT, DWORD, const wchar_t* s, int n, char* out, int outN, const char*, BOOL* used) { + if (used) *used = FALSE; + if (!s || n == 0) { SetLastError(ERROR_INVALID_PARAMETER); return 0; } + const size_t len = n < 0 ? wcslen(s) + 1 : (size_t)n; + const std::string u = ToUtf8(s, len); + if (outN == 0) return (int)u.size(); + if ((size_t)outN < u.size()) { SetLastError(ERROR_INSUFFICIENT_BUFFER); return 0; } + std::memcpy(out, u.data(), u.size()); + return (int)u.size(); +} +int _wcsicmp(const wchar_t* a, const wchar_t* b) { + for (;; ++a, ++b) { + const wint_t x = FoldChar((wint_t)*a), y = FoldChar((wint_t)*b); + if (x != y) return x < y ? -1 : 1; + if (!x) return 0; + } +} +int _wcsnicmp(const wchar_t* a, const wchar_t* b, size_t n) { + for (; n; --n, ++a, ++b) { + const wint_t x = FoldChar((wint_t)*a), y = FoldChar((wint_t)*b); + if (x != y) return x < y ? -1 : 1; + if (!x) return 0; + } + return 0; +} +int CompareStringOrdinal(const wchar_t* a, int an, const wchar_t* b, int bn, BOOL ignoreCase) { + const size_t x = an < 0 ? wcslen(a) : (size_t)an, y = bn < 0 ? wcslen(b) : (size_t)bn; + for (size_t i = 0; i < x && i < y; ++i) { + const wint_t p = ignoreCase ? FoldChar((wint_t)a[i]) : (wint_t)a[i], q = ignoreCase ? FoldChar((wint_t)b[i]) : (wint_t)b[i]; + if (p != q) return p < q ? CSTR_LESS_THAN : CSTR_GREATER_THAN; + } + return x == y ? CSTR_EQUAL : x < y ? CSTR_LESS_THAN : CSTR_GREATER_THAN; +} +// Positions the conversions of fmt take pointers for; the size after %s, %c or %[ is not one. +int sscanf_s(const char* s, const char* fmt, ...) { + void* ptr[8] = {}; + int n = 0; + va_list ap; + va_start(ap, fmt); + for (const char* f = fmt; *f; ++f) { + if (*f != '%') continue; + ++f; + if (*f == '%') continue; + const bool skip = *f == '*'; + while (*f && std::strchr("*0123456789hlLzjtI", *f)) ++f; + if (!*f) break; + if (skip) continue; + if (n < 8) ptr[n++] = va_arg(ap, void*); + if (*f == 's' || *f == 'c' || *f == '[') (void)va_arg(ap, unsigned); + } + va_end(ap); + return sscanf(s, fmt, ptr[0], ptr[1], ptr[2], ptr[3], ptr[4], ptr[5], ptr[6], ptr[7]); +} +int _stricmp(const char* a, const char* b) { return strcasecmp(a, b); } +int _wtoi(const wchar_t* s) { return (int)wcstol(s, nullptr, 10); } +long long _wtoi64(const wchar_t* s) { return wcstoll(s, nullptr, 10); } + +DWORD FormatMessageW(DWORD flags, LPCVOID, DWORD id, DWORD, LPWSTR buf, DWORD size, void*) { + static const struct { DWORD id; const wchar_t* text; } kText[] = { + {ERROR_FILE_NOT_FOUND, L"The system cannot find the file specified."}, {ERROR_PATH_NOT_FOUND, L"The system cannot find the path specified."}, + {ERROR_ACCESS_DENIED, L"Access is denied."}, {ERROR_INVALID_HANDLE, L"The handle is invalid."}, {ERROR_NOT_ENOUGH_MEMORY, L"Not enough memory resources are available to process this command."}, + {ERROR_SHARING_VIOLATION, L"The process cannot access the file because it is being used by another process."}, + {ERROR_CANT_ACCESS_FILE, L"The file cannot be accessed by the system."}, + {ERROR_LOCK_VIOLATION, L"The process cannot access the file because another process has locked a portion of the file."}, + {ERROR_NOT_SUPPORTED, L"The request is not supported."}, {ERROR_FILE_EXISTS, L"The file exists."}, {ERROR_INVALID_PARAMETER, L"The parameter is incorrect."}, + {ERROR_BROKEN_PIPE, L"The pipe has been ended."}, {ERROR_DISK_FULL, L"There is not enough space on the disk."}, + {ERROR_CALL_NOT_IMPLEMENTED, L"This function is not supported on this system."}, {ERROR_DIR_NOT_EMPTY, L"The directory is not empty."}, + {ERROR_ALREADY_EXISTS, L"Cannot create a file when that file already exists."}, {ERROR_NOT_SAME_DEVICE, L"The system cannot move the file to a different disk drive."}, + {ERROR_MOD_NOT_FOUND, L"The specified module could not be found."}, {ERROR_PROC_NOT_FOUND, L"The specified procedure could not be found."}, + {ERROR_DIRECTORY, L"The directory name is invalid."}, {ERROR_INVALID_NAME, L"The filename, directory name, or volume label syntax is incorrect."}, {ERROR_CANCELLED, L"The operation was canceled by the user."}, + }; + const wchar_t* text = nullptr; + for (auto& t : kText) if (t.id == id) text = t.text; + if (!text || !(flags & FORMAT_MESSAGE_FROM_SYSTEM)) { SetLastError(ERROR_RESOURCE_LANG_NOT_FOUND); return 0; } + const size_t n = wcslen(text); + if (flags & FORMAT_MESSAGE_ALLOCATE_BUFFER) { + wchar_t* m = static_cast(std::malloc((n + 3) * sizeof(wchar_t))); + if (!m) return 0; + std::memcpy(m, text, n * sizeof(wchar_t)); + m[n] = L'\r'; m[n + 1] = L'\n'; m[n + 2] = 0; + *reinterpret_cast(buf) = m; + return (DWORD)n + 2; + } + if (size < n + 3) { SetLastError(ERROR_INSUFFICIENT_BUFFER); return 0; } + std::memcpy(buf, text, n * sizeof(wchar_t)); + buf[n] = L'\r'; buf[n + 1] = L'\n'; buf[n + 2] = 0; + return (DWORD)n + 2; +} +HLOCAL LocalFree(HLOCAL p) { std::free(p); return nullptr; } +BOOL ConvertStringSecurityDescriptorToSecurityDescriptorW(LPCWSTR, DWORD, PSECURITY_DESCRIPTOR* sd, ULONG* size) { + if (sd) *sd = nullptr; + if (size) *size = 0; + return Fail(ERROR_NOT_SUPPORTED); +} +// One heap here: the C one. What Windows code frees with HeapFree(GetProcessHeap(), ...) came from malloc. +HANDLE GetProcessHeap() { static char heap; return &heap; } +BOOL HeapFree(HANDLE, DWORD, LPVOID p) { std::free(p); return TRUE; } +// Like a kill, not like exit(): no static destructors run while other threads still use the layer's tables. +void ExitProcess(UINT code) { std::fflush(nullptr); _exit((int)code); } + +// ---- environment ------------------------------------------------------------------------------------------------------- +// Windows names ignore case; a name the environment lacks but Windows always has is filled in from the user's folders. +static bool EnvLookup(const std::string& name, std::string& value) { + if (const char* v = getenv(name.c_str())) { value = v; return true; } + for (char** e = environ; e && *e; ++e) { + const char* eq = std::strchr(*e, '='); + if (eq && (size_t)(eq - *e) == name.size() && strncasecmp(*e, name.c_str(), name.size()) == 0) { value = eq + 1; return true; } + } + if (strcasecmp(name.c_str(), "LOCALAPPDATA") == 0) { value = ToUtf8(WinPath(XdgDataHome())); return true; } + if (strcasecmp(name.c_str(), "APPDATA") == 0) { value = ToUtf8(WinPath(XdgConfigHome())); return true; } + if (strcasecmp(name.c_str(), "USERPROFILE") == 0) { value = ToUtf8(WinPath(HomeDir())); return true; } + if (strcasecmp(name.c_str(), "TEMP") == 0 || strcasecmp(name.c_str(), "TMP") == 0) { + const char* t = getenv("TMPDIR"); + value = ToUtf8(WinPath(t && *t ? t : "/tmp")); + return true; + } + return false; +} +DWORD GetEnvironmentVariableW(LPCWSTR name, LPWSTR out, DWORD size) { + std::string v; + if (!name || !*name || !EnvLookup(ToUtf8(name, wcslen(name)), v)) { SetLastError(ERROR_ENVVAR_NOT_FOUND); return 0; } + return CopyOut(FromUtf8(v), out, size); +} +BOOL SetEnvironmentVariableW(LPCWSTR name, LPCWSTR value) { + if (!name || !*name || wcschr(name, L'=')) return Fail(ERROR_INVALID_PARAMETER); + const std::string n = ToUtf8(name, wcslen(name)); + for (char** e = environ; e && *e;) { // a variant of the name in another case is the same variable on Windows + const char* eq = std::strchr(*e, '='); + if (eq && (size_t)(eq - *e) == n.size() && strncasecmp(*e, n.c_str(), n.size()) == 0 && strncmp(*e, n.c_str(), n.size()) != 0) { + unsetenv(std::string(*e, (size_t)(eq - *e)).c_str()); + e = environ; + } else ++e; + } + if (!value) unsetenv(n.c_str()); + else setenv(n.c_str(), ToUtf8(value, wcslen(value)).c_str(), 1); + return TRUE; +} +LPWCH GetEnvironmentStringsW() { + std::wstring block; + for (char** e = environ; e && *e; ++e) { block += FromUtf8(*e, std::strlen(*e)); block += L'\0'; } + block += L'\0'; + wchar_t* m = static_cast(std::malloc(block.size() * sizeof(wchar_t))); + if (m) std::memcpy(m, block.data(), block.size() * sizeof(wchar_t)); + return m; +} +BOOL FreeEnvironmentStringsW(LPWCH block) { std::free(block); return TRUE; } + +// ---- time -------------------------------------------------------------------------------------------------------------- +ULONGLONG GetTickCount64() { + struct timespec t; + clock_gettime(CLOCK_BOOTTIME, &t); + return (ULONGLONG)t.tv_sec * 1000 + (ULONGLONG)t.tv_nsec / 1000000; +} +static void ToSystemTime(const struct tm& tm, long ms, SYSTEMTIME* t) { + t->wYear = (WORD)(tm.tm_year + 1900); t->wMonth = (WORD)(tm.tm_mon + 1); t->wDayOfWeek = (WORD)tm.tm_wday; t->wDay = (WORD)tm.tm_mday; + t->wHour = (WORD)tm.tm_hour; t->wMinute = (WORD)tm.tm_min; t->wSecond = (WORD)tm.tm_sec; t->wMilliseconds = (WORD)ms; +} +void GetLocalTime(SYSTEMTIME* t) { + struct timespec ts; struct tm tm; + clock_gettime(CLOCK_REALTIME, &ts); + localtime_r(&ts.tv_sec, &tm); + ToSystemTime(tm, ts.tv_nsec / 1000000, t); +} +BOOL FileTimeToSystemTime(const FILETIME* ft, SYSTEMTIME* st) { + const uint64_t v = ((uint64_t)ft->dwHighDateTime << 32) | ft->dwLowDateTime; + const struct timespec ts = TimespecOf(*ft); + struct tm tm; + if (!gmtime_r(&ts.tv_sec, &tm)) return Fail(ERROR_INVALID_PARAMETER); + ToSystemTime(tm, (long)((v / 10000) % 1000), st); + return TRUE; +} +BOOL SystemTimeToFileTime(const SYSTEMTIME* st, FILETIME* ft) { + struct tm tm{}; + tm.tm_year = st->wYear - 1900; tm.tm_mon = st->wMonth - 1; tm.tm_mday = st->wDay; + tm.tm_hour = st->wHour; tm.tm_min = st->wMinute; tm.tm_sec = st->wSecond; + if (st->wMonth < 1 || st->wMonth > 12 || st->wDay < 1 || st->wDay > 31) return Fail(ERROR_INVALID_PARAMETER); + struct timespec ts{timegm(&tm), (long)st->wMilliseconds * 1000000}; + *ft = FileTimeOf(ts); + return TRUE; +} +BOOL FileTimeToLocalFileTime(const FILETIME* ft, FILETIME* local) { + const struct timespec ts = TimespecOf(*ft); + struct tm tm; + if (!localtime_r(&ts.tv_sec, &tm)) return Fail(ERROR_INVALID_PARAMETER); + const uint64_t v = (((uint64_t)ft->dwHighDateTime << 32) | ft->dwLowDateTime) + (uint64_t)((int64_t)tm.tm_gmtoff * 10000000); + local->dwLowDateTime = (DWORD)(v & 0xFFFFFFFFu); + local->dwHighDateTime = (DWORD)(v >> 32); + return TRUE; +} +BOOL LocalFileTimeToFileTime(const FILETIME* local, FILETIME* ft) { + const struct timespec ts = TimespecOf(*local); + struct tm tm; + gmtime_r(&ts.tv_sec, &tm); + tm.tm_isdst = -1; + const time_t asLocal = mktime(&tm); // the local clock reading `local` shows, as an instant + const int64_t shift = (int64_t)asLocal - (int64_t)ts.tv_sec; + const uint64_t v = (((uint64_t)local->dwHighDateTime << 32) | local->dwLowDateTime) + (uint64_t)(shift * 10000000); + ft->dwLowDateTime = (DWORD)(v & 0xFFFFFFFFu); + ft->dwHighDateTime = (DWORD)(v >> 32); + return TRUE; +} +LONG CompareFileTime(const FILETIME* a, const FILETIME* b) { + const uint64_t x = ((uint64_t)a->dwHighDateTime << 32) | a->dwLowDateTime, y = ((uint64_t)b->dwHighDateTime << 32) | b->dwLowDateTime; + return x < y ? -1 : x > y ? 1 : 0; +} +void Sleep(DWORD ms) { + struct timespec t{(time_t)(ms / 1000), (long)(ms % 1000) * 1000000}; + while (nanosleep(&t, &t) != 0 && errno == EINTR) {} +} +DWORD GetCurrentProcessId() { return (DWORD)getpid(); } +BOOL QueryPerformanceCounter(LARGE_INTEGER* v) { + struct timespec t; + clock_gettime(CLOCK_MONOTONIC, &t); + v->QuadPart = (LONGLONG)t.tv_sec * 1000000000LL + t.tv_nsec; + return TRUE; +} +BOOL QueryPerformanceFrequency(LARGE_INTEGER* v) { v->QuadPart = 1000000000LL; return TRUE; } + +// ---- user folders ------------------------------------------------------------------------------------------------------ +namespace wgposix { +std::string HomeDir() { + if (const char* h = getenv("HOME")) if (*h) return h; + if (passwd* pw = getpwuid(getuid())) return pw->pw_dir; + return "/"; +} +std::string XdgDataHome() { + const char* x = getenv("XDG_DATA_HOME"); + return x && *x ? x : HomeDir() + "/.local/share"; +} +std::string XdgConfigHome() { + const char* x = getenv("XDG_CONFIG_HOME"); + return x && *x ? x : HomeDir() + "/.config"; +} +std::string SteamRoot() { + for (const std::string& c : {HomeDir() + "/.local/share/Steam", HomeDir() + "/.steam/steam", HomeDir() + "/.steam/root"}) { + struct stat st; + if (stat(c.c_str(), &st) == 0 && S_ISDIR(st.st_mode)) return c; + } + return ""; +} +} // namespace wgposix +// user-dirs.dirs holds lines like XDG_DESKTOP_DIR="$HOME/Desktop" +static std::string XdgUserDir(const char* key, const char* fallback) { + const std::string home = HomeDir(); + std::string found; + if (FILE* f = std::fopen((XdgConfigHome() + "/user-dirs.dirs").c_str(), "r")) { + char line[2048]; + const std::string want = std::string(key) + "="; + while (std::fgets(line, sizeof(line), f)) { + std::string l = line; + if (l.compare(0, want.size(), want) != 0) continue; + l = l.substr(want.size()); + while (!l.empty() && (l.back() == '\n' || l.back() == '\r')) l.pop_back(); + if (l.size() >= 2 && l.front() == '"' && l.back() == '"') l = l.substr(1, l.size() - 2); + if (l.compare(0, 5, "$HOME") == 0) l = home + l.substr(5); + found = l; + } + std::fclose(f); + } + return found.empty() ? home + "/" + fallback : found; +} + +#define WG_GUID(name, a, b, c, d0, d1, d2, d3, d4, d5, d6, d7) const GUID name = {a, b, c, {d0, d1, d2, d3, d4, d5, d6, d7}} +WG_GUID(FOLDERID_LocalAppData, 0xF1B32785, 0x6FBA, 0x4FCF, 0x9D, 0x55, 0x7B, 0x8E, 0x7F, 0x15, 0x70, 0x91); +WG_GUID(FOLDERID_RoamingAppData, 0x3EB685DB, 0x65F9, 0x4CF6, 0xA0, 0x3A, 0xE3, 0xEF, 0x65, 0x72, 0x9F, 0x3D); +WG_GUID(FOLDERID_Desktop, 0xB4BFCC3A, 0xDB2C, 0x424C, 0xB0, 0x29, 0x7F, 0xE9, 0x9A, 0x87, 0xC6, 0x41); +WG_GUID(FOLDERID_Documents, 0xFDD39AD0, 0x238F, 0x46AF, 0xAD, 0xB4, 0x6C, 0x85, 0x48, 0x03, 0x69, 0xC7); +WG_GUID(FOLDERID_Programs, 0xA77F5D77, 0x2E2B, 0x44C3, 0xA6, 0xA2, 0xAB, 0xA6, 0x01, 0x05, 0x4A, 0x51); +WG_GUID(FOLDERID_ProgramData, 0x62AB5D82, 0xFDC1, 0x4DC3, 0xA9, 0xDD, 0x07, 0x0D, 0x1D, 0x49, 0x5D, 0x97); +WG_GUID(FOLDERID_Profile, 0x5E6C858F, 0x0E22, 0x4760, 0x9A, 0xFE, 0xEA, 0x33, 0x17, 0xB6, 0x71, 0x73); +WG_GUID(FOLDERID_StartMenu, 0x625B53C3, 0xAB48, 0x4EC1, 0xBA, 0x1F, 0xA1, 0xEF, 0x41, 0x46, 0xFC, 0x19); +WG_GUID(FOLDERID_ProgramFiles, 0x905E63B6, 0xC1BF, 0x494E, 0xB2, 0x9C, 0x65, 0xB7, 0x32, 0xD3, 0xD2, 0x1A); +WG_GUID(FOLDERID_ProgramFilesX86, 0x7C5A40EF, 0xA0FB, 0x4BFC, 0x87, 0x4A, 0xC0, 0xF2, 0xE0, 0xB9, 0xFA, 0x8E); +WG_GUID(FOLDERID_Downloads, 0x374DE290, 0x123F, 0x4565, 0x91, 0x64, 0x39, 0xC4, 0x92, 0x5E, 0x46, 0x7B); +WG_GUID(CLSID_ShellLink, 0x00021401, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46); +WG_GUID(IID_IShellLinkW, 0x000214F9, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46); +WG_GUID(IID_IPersistFile, 0x0000010B, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46); +static const GUID kDxgiFactory1 = {0x770aae78, 0xf26f, 0x4dba, {0xa8, 0x29, 0x25, 0x3c, 0x83, 0xd1, 0xb3, 0x87}}; +static const GUID kDxgiAdapter1 = {0x29038f61, 0x3839, 0x4626, {0x91, 0xfd, 0x08, 0x68, 0x79, 0x01, 0x1a, 0x05}}; +static const GUID kDxgiDevice = {0x54ec77fa, 0x1377, 0x44e6, {0x8c, 0x32, 0x88, 0xfd, 0x5f, 0x44, 0xc8, 0x4c}}; +template <> const GUID& wg_posix_uuidof() { return kDxgiFactory1; } +template <> const GUID& wg_posix_uuidof() { return kDxgiAdapter1; } +template <> const GUID& wg_posix_uuidof() { return kDxgiDevice; } + +HRESULT SHGetKnownFolderPath(REFKNOWNFOLDERID id, DWORD, HANDLE, PWSTR* out) { + *out = nullptr; + std::string p; + auto is = [&](const GUID& g) { return std::memcmp(&id, &g, sizeof(GUID)) == 0; }; + if (is(FOLDERID_LocalAppData)) p = XdgDataHome(); + else if (is(FOLDERID_RoamingAppData)) p = XdgConfigHome(); + else if (is(FOLDERID_Desktop)) p = XdgUserDir("XDG_DESKTOP_DIR", "Desktop"); + else if (is(FOLDERID_Documents)) p = XdgUserDir("XDG_DOCUMENTS_DIR", "Documents"); + else if (is(FOLDERID_Downloads)) p = XdgUserDir("XDG_DOWNLOAD_DIR", "Downloads"); + else if (is(FOLDERID_Programs) || is(FOLDERID_StartMenu)) p = XdgDataHome() + "/applications"; + else if (is(FOLDERID_Profile)) p = HomeDir(); + else if (is(FOLDERID_ProgramData)) p = "/var/lib"; + else return HRESULT_ERROR_FILE_NOT_FOUND; // Program Files and the like have no counterpart + const std::wstring w = WinPath(p); + wchar_t* m = static_cast(CoTaskMemAlloc((w.size() + 1) * sizeof(wchar_t))); + if (!m) return E_OUTOFMEMORY; + std::memcpy(m, w.c_str(), (w.size() + 1) * sizeof(wchar_t)); + *out = m; + return S_OK; +} +void CoTaskMemFree(LPVOID p) { std::free(p); } +LPVOID CoTaskMemAlloc(SIZE_T n) { return std::malloc(n); } +HRESULT CoInitializeEx(LPVOID, DWORD) { return S_OK; } +void CoUninitialize() {} +HRESULT CoCreateInstance(REFCLSID, IUnknown*, DWORD, REFIID, LPVOID* out) { + if (out) *out = nullptr; + return REGDB_E_CLASSNOTREG; // no shell link object, so no shortcut +} + +// ---- modules: no Windows DLL loads, so every GetProcAddress user takes its "not available" branch ------------------------ +HMODULE LoadLibraryExW(LPCWSTR, HANDLE, DWORD) { SetLastError(ERROR_MOD_NOT_FOUND); return nullptr; } +// ntdll's RtlGetVersion is the one export that answers: Proton prefixes report Windows 10, and the launcher's Windows check +// would refuse every Linux install on "unknown" otherwise. A stand-in module handle names it. +static char g_ntdll; +static LONG WINAPI RtlGetVersionStandIn(OSVERSIONINFOW* v) { + if (!v || v->dwOSVersionInfoSize < sizeof(DWORD) * 5) return -1; + v->dwMajorVersion = 10; v->dwMinorVersion = 0; v->dwBuildNumber = 19045; v->dwPlatformId = 2; + return 0; +} +HMODULE GetModuleHandleW(LPCWSTR name) { + if (name && _wcsicmp(name, L"ntdll.dll") == 0) return &g_ntdll; + SetLastError(ERROR_MOD_NOT_FOUND); + return nullptr; +} +FARPROC GetProcAddress(HMODULE m, LPCSTR name) { + if (m == &g_ntdll && name && std::strcmp(name, "RtlGetVersion") == 0) return reinterpret_cast(&RtlGetVersionStandIn); + // wg::NativeLinux(): the one name only this layer's ntdll exports (Windows' and Wine's ntdll never do) + if (m == &g_ntdll && name && std::strcmp(name, "wronggpu_native_posix") == 0) return reinterpret_cast(&RtlGetVersionStandIn); + SetLastError(ERROR_PROC_NOT_FOUND); + return nullptr; +} + +// wg::FsPath (wg_core/util.h): the converter takes host paths, the core holds Windows-style ones +namespace wg { +std::filesystem::path FsPath(const std::wstring& p) { + std::string host; + return ToPosix(p.c_str(), host) ? std::filesystem::path(host) : std::filesystem::path(ToUtf8(p)); +} +} // namespace wg + +// ---- resources: the table tools/make_payload.py writes into resources.S (RCDATA only; a build without it embeds none) --------- +struct WgResource { unsigned id, type; const unsigned char* data; unsigned long long size; }; +extern "C" const WgResource wg_resource_table[] __attribute__((weak)); // weak: the unit-test programs link no payload + +HRSRC FindResourceW(HMODULE, LPCWSTR name, LPCWSTR type) { + // MAKEINTRESOURCE values are small integers; anything above 16 bits is a name, which no resource here has + const uintptr_t id = reinterpret_cast(name), ty = reinterpret_cast(type); + if (wg_resource_table && id <= 0xFFFF && ty <= 0xFFFF) + for (const WgResource* r = wg_resource_table; r->id; ++r) + if (r->id == id && r->type == ty) return const_cast(r); + SetLastError(ERROR_RESOURCE_DATA_NOT_FOUND); + return nullptr; +} +HGLOBAL LoadResource(HMODULE, HRSRC r) { + if (!r) { SetLastError(ERROR_INVALID_HANDLE); return nullptr; } + return const_cast(static_cast(r)->data); +} +DWORD SizeofResource(HMODULE, HRSRC r) { + if (!r) { SetLastError(ERROR_INVALID_HANDLE); return 0; } + return static_cast(static_cast(r)->size); +} +LPVOID LockResource(HGLOBAL h) { return h; } + +// ---- WinHTTP ----------------------------------------------------------------------------------------------------------- +HINTERNET WinHttpOpen(LPCWSTR, DWORD, LPCWSTR, LPCWSTR, DWORD) { SetLastError(ERROR_NOT_SUPPORTED); return nullptr; } +BOOL WinHttpSetTimeouts(HINTERNET, int, int, int, int) { return Fail(ERROR_INVALID_HANDLE); } +BOOL WinHttpSetOption(HINTERNET, DWORD, LPVOID, DWORD) { return Fail(ERROR_INVALID_HANDLE); } +HINTERNET WinHttpConnect(HINTERNET, LPCWSTR, INTERNET_PORT, DWORD) { SetLastError(ERROR_INVALID_HANDLE); return nullptr; } +HINTERNET WinHttpOpenRequest(HINTERNET, LPCWSTR, LPCWSTR, LPCWSTR, LPCWSTR, LPCWSTR*, DWORD) { SetLastError(ERROR_INVALID_HANDLE); return nullptr; } +BOOL WinHttpSendRequest(HINTERNET, LPCWSTR, DWORD, LPVOID, DWORD, DWORD, DWORD_PTR) { return Fail(ERROR_INVALID_HANDLE); } +BOOL WinHttpReceiveResponse(HINTERNET, LPVOID) { return Fail(ERROR_INVALID_HANDLE); } +BOOL WinHttpQueryHeaders(HINTERNET, DWORD, LPCWSTR, LPVOID, LPDWORD, LPDWORD) { return Fail(ERROR_INVALID_HANDLE); } +BOOL WinHttpReadData(HINTERNET, LPVOID, DWORD, LPDWORD) { return Fail(ERROR_INVALID_HANDLE); } +BOOL WinHttpCloseHandle(HINTERNET) { return Fail(ERROR_INVALID_HANDLE); } +// Parsing needs no network: the core validates an address with it before it opens a session. +BOOL WinHttpCrackUrl(LPCWSTR url, DWORD length, DWORD, LPURL_COMPONENTS uc) { + if (!url || !uc || uc->dwStructSize != sizeof(URL_COMPONENTS)) return Fail(ERROR_INVALID_PARAMETER); + const std::wstring u = length ? std::wstring(url, length) : std::wstring(url); + const size_t sep = u.find(L"://"); + if (sep == std::wstring::npos) return Fail(ERROR_WINHTTP_UNRECOGNIZED_SCHEME); + const std::wstring scheme = u.substr(0, sep); + if (_wcsicmp(scheme.c_str(), L"http") == 0) uc->nScheme = INTERNET_SCHEME_HTTP; + else if (_wcsicmp(scheme.c_str(), L"https") == 0) uc->nScheme = INTERNET_SCHEME_HTTPS; + else return Fail(ERROR_WINHTTP_UNRECOGNIZED_SCHEME); + const size_t hostFrom = sep + 3, pathAt = u.find_first_of(L"/?#", hostFrom); + std::wstring auth = u.substr(hostFrom, pathAt == std::wstring::npos ? std::wstring::npos : pathAt - hostFrom); + const size_t at = auth.rfind(L'@'); + std::wstring user, pass; + if (at != std::wstring::npos) { + const std::wstring cred = auth.substr(0, at); + const size_t colon = cred.find(L':'); + user = cred.substr(0, colon); + if (colon != std::wstring::npos) pass = cred.substr(colon + 1); + auth.erase(0, at + 1); + } + std::wstring host = auth; + unsigned port = uc->nScheme == INTERNET_SCHEME_HTTPS ? 443 : 80; + const size_t colon = auth.rfind(L':'); + if (colon != std::wstring::npos && auth.find(L']', colon) == std::wstring::npos) { + host = auth.substr(0, colon); + port = (unsigned)wcstoul(auth.c_str() + colon + 1, nullptr, 10); + } + if (host.empty() || port > 65535) return Fail(ERROR_WINHTTP_INVALID_URL); + uc->nPort = (INTERNET_PORT)port; + const std::wstring rest = pathAt == std::wstring::npos ? L"" : u.substr(pathAt); + const size_t extraAt = rest.find_first_of(L"?#"); + const std::wstring path = rest.substr(0, extraAt), extra = extraAt == std::wstring::npos ? L"" : rest.substr(extraAt); + // a requested component goes into the caller's buffer, or (no buffer, a length) is pointed at inside the address + auto give = [&](LPWSTR& ptr, DWORD& len, const std::wstring& v, size_t at) -> bool { + if (!ptr && !len) return true; + if (ptr) { + if (len < v.size() + 1) { len = (DWORD)v.size() + 1; return false; } + std::memcpy(ptr, v.c_str(), (v.size() + 1) * sizeof(wchar_t)); + } else { + ptr = const_cast(url) + at; + } + len = (DWORD)v.size(); + return true; + }; + bool ok = give(uc->lpszScheme, uc->dwSchemeLength, scheme, 0) && give(uc->lpszHostName, uc->dwHostNameLength, host, hostFrom + (at == std::wstring::npos ? 0 : u.find(L'@', hostFrom) + 1 - hostFrom)) && + give(uc->lpszUserName, uc->dwUserNameLength, user, hostFrom) && give(uc->lpszPassword, uc->dwPasswordLength, pass, hostFrom) && + give(uc->lpszUrlPath, uc->dwUrlPathLength, path, pathAt == std::wstring::npos ? u.size() : pathAt) && + give(uc->lpszExtraInfo, uc->dwExtraInfoLength, extra, pathAt == std::wstring::npos ? u.size() : pathAt + path.size()); + if (!ok) return Fail(ERROR_INSUFFICIENT_BUFFER); + return TRUE; +} diff --git a/clean/installer/src/platform/posix/win32_posix.h b/clean/installer/src/platform/posix/win32_posix.h new file mode 100644 index 00000000..a50b5bc5 --- /dev/null +++ b/clean/installer/src/platform/posix/win32_posix.h @@ -0,0 +1,684 @@ +// SPDX-License-Identifier: MIT +// Linux: the Windows names wg_core and its tests use, declared the way Windows declares them, implemented on POSIX in +// win32_posix*.cpp. The core stays Windows-style source: a Windows call this layer lacks fails the Linux build at that line. +// +// Conventions (README-linux.md has the long form): +// - Strings: wchar_t is 4 bytes here. Paths and names cross to the OS as UTF-8 (bytes that are not UTF-8 travel as U+DC80..U+DCFF +// and come back unchanged); '\' becomes '/', a "\\?\" prefix goes, "Z:\" is "/", any other drive letter is ERROR_PATH_NOT_FOUND. +// - REG_SZ sizes: callers write (length + 1) * 2 bytes (UTF-16); the store reads that as length + 1 wide characters. +// On read the size is in sizeof(wchar_t) units, as the callers' own buffers are. +// - Not available (fail cleanly): WinHTTP, COM objects, DXGI, the event log, LoadLibrary of any DLL, WinVerifyTrust. +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// ---- types ------------------------------------------------------------------------------------------------------------- +typedef uint32_t DWORD; +typedef int32_t LONG; +typedef uint32_t ULONG; +typedef int64_t LONGLONG; +typedef uint64_t ULONGLONG; +typedef uint64_t DWORD64; +typedef int BOOL; +typedef uint8_t BYTE; +typedef unsigned char BOOLEAN; +typedef uint16_t WORD; +typedef unsigned int UINT; +typedef uint32_t UINT32; +typedef uint64_t UINT64; +typedef intptr_t INT_PTR; +typedef uintptr_t ULONG_PTR; +typedef uintptr_t DWORD_PTR; +typedef size_t SIZE_T; +typedef int32_t HRESULT; +typedef LONG LSTATUS; +typedef LONG NTSTATUS; +typedef void* HANDLE; +typedef void* PVOID; +typedef void* LPVOID; +typedef const void* LPCVOID; +typedef HANDLE HMODULE; +typedef HANDLE HWND; +typedef HANDLE HINSTANCE; +typedef HANDLE HINTERNET; +typedef HANDLE HLOCAL; +typedef HANDLE EVT_HANDLE; +typedef BYTE* LPBYTE; +typedef DWORD* PDWORD; +typedef DWORD* LPDWORD; +typedef wchar_t WCHAR; +typedef wchar_t* LPWSTR; +typedef wchar_t* PWSTR; +typedef wchar_t* LPWCH; +typedef const wchar_t* LPCWSTR; +typedef const wchar_t* PCWSTR; +typedef const char* LPCSTR; +typedef char* LPSTR; +typedef INT_PTR (*FARPROC)(); +typedef DWORD REGSAM; +typedef struct HKEY__* HKEY; +typedef HKEY* PHKEY; + +#define WINAPI +#define CDECL +#define CALLBACK +#define APIENTRY +#define CONST const +#define TRUE 1 +#define FALSE 0 +#define MAX_PATH 260 +#define MAKELONG(a, b) ((LONG)(((WORD)(a)) | ((DWORD)((WORD)(b))) << 16)) +#define LOWORD(l) ((WORD)(((DWORD_PTR)(l)) & 0xffff)) +#define HIWORD(l) ((WORD)((((DWORD_PTR)(l)) >> 16) & 0xffff)) +#define INVALID_HANDLE_VALUE ((HANDLE)(intptr_t)-1) +#define SUCCEEDED(hr) (((HRESULT)(hr)) >= 0) +#define FAILED(hr) (((HRESULT)(hr)) < 0) +#define _countof(a) (sizeof(a) / sizeof((a)[0])) +#define ARRAYSIZE(a) _countof(a) +#define UNREFERENCED_PARAMETER(p) ((void)(p)) + +__extension__ typedef union _LARGE_INTEGER { + struct { DWORD LowPart; LONG HighPart; }; + struct { DWORD LowPart; LONG HighPart; } u; + LONGLONG QuadPart; +} LARGE_INTEGER; +__extension__ typedef union _ULARGE_INTEGER { + struct { DWORD LowPart; DWORD HighPart; }; + struct { DWORD LowPart; DWORD HighPart; } u; + ULONGLONG QuadPart; +} ULARGE_INTEGER; +typedef struct _FILETIME { DWORD dwLowDateTime, dwHighDateTime; } FILETIME; +typedef struct _SYSTEMTIME { WORD wYear, wMonth, wDayOfWeek, wDay, wHour, wMinute, wSecond, wMilliseconds; } SYSTEMTIME; +typedef struct _GUID { uint32_t Data1; uint16_t Data2, Data3; uint8_t Data4[8]; } GUID; +typedef GUID IID; +typedef GUID CLSID; +typedef GUID KNOWNFOLDERID; +typedef const GUID& REFIID; +typedef const GUID& REFCLSID; +typedef const GUID& REFKNOWNFOLDERID; +typedef struct _SECURITY_ATTRIBUTES { DWORD nLength; LPVOID lpSecurityDescriptor; BOOL bInheritHandle; } SECURITY_ATTRIBUTES, *LPSECURITY_ATTRIBUTES; +typedef PVOID PSECURITY_DESCRIPTOR; +typedef struct _OVERLAPPED OVERLAPPED; + +// ---- errors, HRESULTs -------------------------------------------------------------------------------------------------- +constexpr DWORD ERROR_SUCCESS = 0; +constexpr DWORD ERROR_INVALID_FUNCTION = 1; +constexpr DWORD ERROR_WRITE_PROTECT = 19; +constexpr DWORD ERROR_BAD_LENGTH = 24; +constexpr DWORD ERROR_READ_FAULT = 30; +constexpr DWORD ERROR_WRITE_FAULT = 29; +constexpr DWORD ERROR_GEN_FAILURE = 31; +constexpr DWORD ERROR_BAD_EXE_FORMAT = 193; +constexpr DWORD ERROR_ENVVAR_NOT_FOUND = 203; +constexpr DWORD ERROR_FILE_INVALID = 1006; +constexpr DWORD ERROR_NO_UNICODE_TRANSLATION = 1113; +constexpr DWORD ERROR_UNSUPPORTED_TYPE = 1630; +constexpr DWORD ERROR_RESOURCE_LANG_NOT_FOUND = 1815; +constexpr DWORD ERROR_RESOURCE_DATA_NOT_FOUND = 1812; +constexpr DWORD ERROR_FILE_NOT_FOUND = 2; +constexpr DWORD ERROR_PATH_NOT_FOUND = 3; +constexpr DWORD ERROR_TOO_MANY_OPEN_FILES = 4; +constexpr DWORD ERROR_ACCESS_DENIED = 5; +constexpr DWORD ERROR_INVALID_HANDLE = 6; +constexpr DWORD ERROR_NOT_ENOUGH_MEMORY = 8; +constexpr DWORD ERROR_INVALID_DATA = 13; +constexpr DWORD ERROR_OUTOFMEMORY = 14; +constexpr DWORD ERROR_NOT_SAME_DEVICE = 17; +constexpr DWORD ERROR_NO_MORE_FILES = 18; +constexpr DWORD ERROR_SHARING_VIOLATION = 32; +constexpr DWORD ERROR_LOCK_VIOLATION = 33; +constexpr DWORD ERROR_NOT_SUPPORTED = 50; +constexpr DWORD ERROR_FILE_EXISTS = 80; +constexpr DWORD ERROR_INVALID_PARAMETER = 87; +constexpr DWORD ERROR_BROKEN_PIPE = 109; +constexpr DWORD ERROR_DISK_FULL = 112; +constexpr DWORD ERROR_CALL_NOT_IMPLEMENTED = 120; +constexpr DWORD ERROR_INSUFFICIENT_BUFFER = 122; +constexpr DWORD ERROR_INVALID_NAME = 123; +constexpr DWORD ERROR_DIR_NOT_EMPTY = 145; +constexpr DWORD ERROR_ALREADY_EXISTS = 183; +constexpr DWORD ERROR_UNABLE_TO_REMOVE_REPLACED = 1175; +constexpr DWORD ERROR_UNABLE_TO_MOVE_REPLACEMENT = 1176; +constexpr DWORD ERROR_UNABLE_TO_MOVE_REPLACEMENT_2 = 1177; +constexpr DWORD ERROR_MORE_DATA = 234; +constexpr DWORD ERROR_NO_MORE_ITEMS = 259; +constexpr DWORD ERROR_DIRECTORY = 267; +constexpr DWORD ERROR_CANCELLED = 1223; +constexpr DWORD ERROR_TOO_MANY_LINKS = 1142; +constexpr DWORD ERROR_FILE_CORRUPT = 1392; +constexpr DWORD ERROR_PROC_NOT_FOUND = 127; +constexpr DWORD ERROR_MOD_NOT_FOUND = 126; +constexpr DWORD ERROR_NOT_FOUND = 1168; +constexpr DWORD ERROR_NO_ASSOCIATION = 1155; +constexpr DWORD ERROR_TIMEOUT = 1460; +constexpr DWORD ERROR_BAD_PATHNAME = 161; +constexpr DWORD ERROR_FILENAME_EXCED_RANGE = 206; +constexpr DWORD ERROR_FILE_TOO_LARGE = 223; +constexpr DWORD ERROR_NOT_ENOUGH_QUOTA = 1816; +constexpr DWORD ERROR_CANT_ACCESS_FILE = 1920; +constexpr DWORD ERROR_OPERATION_ABORTED = 995; +constexpr DWORD ERROR_IO_PENDING = 997; +constexpr DWORD ERROR_INTERNET_CANNOT_CONNECT = 12029; +constexpr DWORD ERROR_WINHTTP_CANNOT_CONNECT = 12029; +constexpr DWORD ERROR_WINHTTP_TIMEOUT = 12002; +constexpr DWORD ERROR_WINHTTP_INVALID_URL = 12005; +constexpr DWORD ERROR_WINHTTP_UNRECOGNIZED_SCHEME = 12006; +constexpr DWORD ERROR_WINHTTP_NAME_NOT_RESOLVED = 12007; +constexpr DWORD ERROR_WINHTTP_CONNECTION_ERROR = 12030; +constexpr DWORD ERROR_PRIVILEGE_NOT_HELD = 1314; +constexpr DWORD RPC_E_CHANGED_MODE = 0x80010106u; +constexpr DWORD ERROR_ELEVATION_REQUIRED = 740; +constexpr HRESULT S_OK = 0; +constexpr HRESULT S_FALSE = 1; +constexpr HRESULT E_FAIL = (HRESULT)0x80004005; +constexpr HRESULT E_NOTIMPL = (HRESULT)0x80004001; +constexpr HRESULT E_NOINTERFACE = (HRESULT)0x80004002; +constexpr HRESULT E_POINTER = (HRESULT)0x80004003; +constexpr HRESULT E_OUTOFMEMORY = (HRESULT)0x8007000E; +constexpr HRESULT E_INVALIDARG = (HRESULT)0x80070057; +constexpr HRESULT E_ACCESSDENIED = (HRESULT)0x80070005; +constexpr HRESULT REGDB_E_CLASSNOTREG = (HRESULT)0x80040154; +constexpr HRESULT DXGI_ERROR_NOT_FOUND = (HRESULT)0x887A0002; +constexpr HRESULT DXGI_ERROR_UNSUPPORTED = (HRESULT)0x887A0004; +constexpr HRESULT HRESULT_ERROR_FILE_NOT_FOUND = (HRESULT)0x80070002; +DWORD GetLastError(); +void SetLastError(DWORD e); + +// ---- files ------------------------------------------------------------------------------------------------------------- +constexpr DWORD GENERIC_READ = 0x80000000u; +constexpr DWORD GENERIC_WRITE = 0x40000000u; +constexpr DWORD GENERIC_EXECUTE = 0x20000000u; +constexpr DWORD GENERIC_ALL = 0x10000000u; +constexpr DWORD DELETE = 0x00010000; +constexpr DWORD FILE_READ_DATA = 1; +constexpr DWORD FILE_WRITE_DATA = 2; +constexpr DWORD FILE_APPEND_DATA = 4; +constexpr DWORD FILE_READ_ATTRIBUTES = 0x80; +constexpr DWORD FILE_WRITE_ATTRIBUTES = 0x100; +constexpr DWORD SYNCHRONIZE = 0x00100000; +constexpr DWORD FILE_GENERIC_READ = 0x00120089; +constexpr DWORD FILE_GENERIC_WRITE = 0x00120116; +constexpr DWORD FILE_SHARE_READ = 1; +constexpr DWORD FILE_SHARE_WRITE = 2; +constexpr DWORD FILE_SHARE_DELETE = 4; +constexpr DWORD CREATE_NEW = 1; +constexpr DWORD CREATE_ALWAYS = 2; +constexpr DWORD OPEN_EXISTING = 3; +constexpr DWORD OPEN_ALWAYS = 4; +constexpr DWORD TRUNCATE_EXISTING = 5; +constexpr DWORD FILE_ATTRIBUTE_READONLY = 0x1; +constexpr DWORD FILE_ATTRIBUTE_HIDDEN = 0x2; +constexpr DWORD FILE_ATTRIBUTE_SYSTEM = 0x4; +constexpr DWORD FILE_ATTRIBUTE_DIRECTORY = 0x10; +constexpr DWORD FILE_ATTRIBUTE_ARCHIVE = 0x20; +constexpr DWORD FILE_ATTRIBUTE_NORMAL = 0x80; +constexpr DWORD FILE_ATTRIBUTE_TEMPORARY = 0x100; +constexpr DWORD FILE_ATTRIBUTE_REPARSE_POINT = 0x400; +constexpr DWORD FILE_FLAG_WRITE_THROUGH = 0x80000000u; +constexpr DWORD FILE_FLAG_OVERLAPPED = 0x40000000; +constexpr DWORD FILE_FLAG_SEQUENTIAL_SCAN = 0x08000000; +constexpr DWORD FILE_FLAG_RANDOM_ACCESS = 0x10000000; +constexpr DWORD FILE_FLAG_DELETE_ON_CLOSE = 0x04000000; +constexpr DWORD FILE_FLAG_BACKUP_SEMANTICS = 0x02000000; +constexpr DWORD FILE_FLAG_OPEN_REPARSE_POINT = 0x00200000; +constexpr DWORD FILE_BEGIN = 0; +constexpr DWORD FILE_CURRENT = 1; +constexpr DWORD FILE_END = 2; +constexpr DWORD INVALID_FILE_ATTRIBUTES = 0xFFFFFFFFu; +constexpr DWORD INVALID_SET_FILE_POINTER = 0xFFFFFFFFu; +constexpr DWORD MOVEFILE_REPLACE_EXISTING = 1; +constexpr DWORD MOVEFILE_COPY_ALLOWED = 2; +constexpr DWORD MOVEFILE_DELAY_UNTIL_REBOOT = 4; +constexpr DWORD MOVEFILE_WRITE_THROUGH = 8; +constexpr DWORD REPLACEFILE_WRITE_THROUGH = 1; +constexpr DWORD REPLACEFILE_IGNORE_MERGE_ERRORS = 2; +constexpr DWORD REPLACEFILE_IGNORE_ACL_ERRORS = 4; +constexpr DWORD PAGE_READONLY = 0x02; +constexpr DWORD PAGE_READWRITE = 0x04; +constexpr DWORD PAGE_WRITECOPY = 0x08; +constexpr DWORD FILE_MAP_COPY = 1; +constexpr DWORD FILE_MAP_WRITE = 2; +constexpr DWORD FILE_MAP_READ = 4; +constexpr DWORD SYMBOLIC_LINK_FLAG_DIRECTORY = 1; +constexpr DWORD SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE = 2; +constexpr DWORD FILE_NAME_NORMALIZED = 0; +constexpr DWORD FILE_NAME_OPENED = 8; +constexpr DWORD VOLUME_NAME_DOS = 0; +constexpr DWORD VOLUME_NAME_NONE = 4; +constexpr DWORD FIND_FIRST_EX_LARGE_FETCH = 2; +typedef enum _GET_FILEEX_INFO_LEVELS { GetFileExInfoStandard = 0 } GET_FILEEX_INFO_LEVELS; +typedef enum _FINDEX_INFO_LEVELS { FindExInfoStandard = 0, FindExInfoBasic = 1 } FINDEX_INFO_LEVELS; +typedef enum _FINDEX_SEARCH_OPS { FindExSearchNameMatch = 0 } FINDEX_SEARCH_OPS; +typedef enum _FILE_INFO_BY_HANDLE_CLASS { FileBasicInfo = 0, FileRenameInfo = 3, FileDispositionInfo = 4, FileIdInfo = 18, FileDispositionInfoEx = 21 } FILE_INFO_BY_HANDLE_CLASS; +typedef struct _FILE_BASIC_INFO { + LARGE_INTEGER CreationTime, LastAccessTime, LastWriteTime, ChangeTime; + DWORD FileAttributes; +} FILE_BASIC_INFO; +typedef struct _FILE_DISPOSITION_INFO { BOOLEAN DeleteFile; } FILE_DISPOSITION_INFO; +// FileRenameInfo: the file of the handle (opened with DELETE access) takes the name FileName (FileNameLength bytes, no NUL; a +// full path, also in the NT form \??\Z:\...). Linux: rename(2) of the name /proc/self/fd gives for the handle, so the file +// renamed is the handle's own unless another process renames it in that instant; ReplaceIfExists off is renameat2's +// RENAME_NOREPLACE (a file system without it: link and unlink, the new link removed again and the call failed when the old +// name cannot be unlinked; else a check before the rename). RootDirectory must be null. +typedef struct _FILE_RENAME_INFO { + union { BOOLEAN ReplaceIfExists; DWORD Flags; }; + HANDLE RootDirectory; + DWORD FileNameLength; + WCHAR FileName[1]; +} FILE_RENAME_INFO; +typedef struct _FILE_DISPOSITION_INFO_EX { DWORD Flags; } FILE_DISPOSITION_INFO_EX; +constexpr DWORD FILE_DISPOSITION_FLAG_DO_NOT_DELETE = 0x0; +constexpr DWORD FILE_DISPOSITION_FLAG_DELETE = 0x1; +constexpr DWORD FILE_DISPOSITION_FLAG_POSIX_SEMANTICS = 0x2; +constexpr DWORD FILE_DISPOSITION_FLAG_IGNORE_READONLY_ATTRIBUTE = 0x10; +typedef struct _WIN32_FILE_ATTRIBUTE_DATA { + DWORD dwFileAttributes; FILETIME ftCreationTime, ftLastAccessTime, ftLastWriteTime; DWORD nFileSizeHigh, nFileSizeLow; +} WIN32_FILE_ATTRIBUTE_DATA; +typedef struct _WIN32_FIND_DATAW { + DWORD dwFileAttributes; FILETIME ftCreationTime, ftLastAccessTime, ftLastWriteTime; DWORD nFileSizeHigh, nFileSizeLow; + DWORD dwReserved0, dwReserved1; wchar_t cFileName[MAX_PATH]; wchar_t cAlternateFileName[14]; +} WIN32_FIND_DATAW; +typedef struct _BY_HANDLE_FILE_INFORMATION { + DWORD dwFileAttributes; FILETIME ftCreationTime, ftLastAccessTime, ftLastWriteTime; + DWORD dwVolumeSerialNumber, nFileSizeHigh, nFileSizeLow, nNumberOfLinks, nFileIndexHigh, nFileIndexLow; +} BY_HANDLE_FILE_INFORMATION; +typedef struct _FILE_ID_128 { BYTE Identifier[16]; } FILE_ID_128; +typedef struct _FILE_ID_INFO { ULONGLONG VolumeSerialNumber; FILE_ID_128 FileId; } FILE_ID_INFO; + +// Sharing rules between handles of this process as Windows has them. Between processes only Windows' image rule: an open that +// would write (write or append data, or a truncating disposition) to a Windows program or DLL ("MZ") that a Windows program +// under Wine has loaded fails with ERROR_SHARING_VIOLATION, as Windows refuses a write open of a loaded image (what the +// operation guard relies on to see a running game). Looked at: this user's Wine processes (command line a Windows path, an +// .exe, or wine*), their /proc//maps. One of them whose maps cannot be read: ERROR_CANT_ACCESS_FILE ("could not tell"). +// Not seen: another user's processes; a file another program merely has open (its share mode is not known here); a game +// that loads the file after the open succeeded (Windows refuses that load while the write handle is open; Linux cannot). +HANDLE CreateFileW(LPCWSTR name, DWORD access, DWORD share, LPSECURITY_ATTRIBUTES sa, DWORD disposition, DWORD flags, HANDLE templ); +BOOL ReadFile(HANDLE h, LPVOID buf, DWORD n, LPDWORD got, OVERLAPPED* ov); +BOOL WriteFile(HANDLE h, LPCVOID buf, DWORD n, LPDWORD wrote, OVERLAPPED* ov); +BOOL CloseHandle(HANDLE h); +BOOL FlushFileBuffers(HANDLE h); +BOOL GetFileSizeEx(HANDLE h, LARGE_INTEGER* size); +BOOL SetFilePointerEx(HANDLE h, LARGE_INTEGER dist, LARGE_INTEGER* newPos, DWORD method); +BOOL GetFileTime(HANDLE h, FILETIME* created, FILETIME* accessed, FILETIME* written); +BOOL SetFileTime(HANDLE h, const FILETIME* created, const FILETIME* accessed, const FILETIME* written); +BOOL GetFileInformationByHandle(HANDLE h, BY_HANDLE_FILE_INFORMATION* info); +BOOL GetFileInformationByHandleEx(HANDLE h, FILE_INFO_BY_HANDLE_CLASS cls, LPVOID info, DWORD size); +BOOL SetFileInformationByHandle(HANDLE h, FILE_INFO_BY_HANDLE_CLASS cls, LPVOID info, DWORD size); +BOOL SetEndOfFile(HANDLE h); +DWORD GetFinalPathNameByHandleW(HANDLE h, LPWSTR out, DWORD size, DWORD flags); +DWORD GetFileAttributesW(LPCWSTR name); +BOOL GetFileAttributesExW(LPCWSTR name, GET_FILEEX_INFO_LEVELS level, LPVOID data); +BOOL SetFileAttributesW(LPCWSTR name, DWORD attrs); +BOOL DeleteFileW(LPCWSTR name); +BOOL MoveFileExW(LPCWSTR from, LPCWSTR to, DWORD flags); +BOOL ReplaceFileW(LPCWSTR replaced, LPCWSTR replacement, LPCWSTR backup, DWORD flags, LPVOID exclude, LPVOID reserved); +BOOL CopyFileW(LPCWSTR from, LPCWSTR to, BOOL failIfExists); +BOOL CreateDirectoryW(LPCWSTR name, LPSECURITY_ATTRIBUTES sa); +BOOL RemoveDirectoryW(LPCWSTR name); +BOOL CreateHardLinkW(LPCWSTR link, LPCWSTR existing, LPSECURITY_ATTRIBUTES sa); +HANDLE FindFirstFileW(LPCWSTR pattern, WIN32_FIND_DATAW* data); +HANDLE FindFirstFileExW(LPCWSTR pattern, FINDEX_INFO_LEVELS info, LPVOID data, FINDEX_SEARCH_OPS op, LPVOID filter, DWORD flags); +BOOL FindNextFileW(HANDLE h, WIN32_FIND_DATAW* data); +BOOL FindClose(HANDLE h); +DWORD GetFullPathNameW(LPCWSTR name, DWORD size, LPWSTR out, LPWSTR* filePart); +// no 8.3 names here: the path as it is, its names in their case on disk (no link followed); fails as Windows does when it is not there +DWORD GetLongPathNameW(LPCWSTR shortPath, LPWSTR out, DWORD size); +DWORD GetTempPathW(DWORD size, LPWSTR out); +DWORD GetCurrentDirectoryW(DWORD size, LPWSTR out); +BOOL SetCurrentDirectoryW(LPCWSTR dir); +DWORD GetSystemDirectoryW(LPWSTR out, DWORD size); +DWORD GetModuleFileNameW(HMODULE m, LPWSTR out, DWORD size); +BOOL GetDiskFreeSpaceExW(LPCWSTR dir, ULARGE_INTEGER* available, ULARGE_INTEGER* total, ULARGE_INTEGER* freeBytes); +HANDLE CreateFileMappingW(HANDLE file, LPSECURITY_ATTRIBUTES sa, DWORD protect, DWORD sizeHigh, DWORD sizeLow, LPCWSTR name); +LPVOID MapViewOfFile(HANDLE map, DWORD access, DWORD offsetHigh, DWORD offsetLow, SIZE_T bytes); +BOOL UnmapViewOfFile(LPCVOID base); +BOOL CreateSymbolicLinkW(LPCWSTR link, LPCWSTR target, DWORD flags); +int _wsystem(const wchar_t* cmd); +constexpr DWORD COPY_FILE_FAIL_IF_EXISTS = 1; +constexpr DWORD COPY_FILE_COPY_SYMLINK = 0x800; +constexpr DWORD FILE_TYPE_UNKNOWN = 0; +constexpr DWORD FILE_TYPE_DISK = 1; +constexpr DWORD FILE_TYPE_CHAR = 2; +constexpr DWORD FILE_TYPE_PIPE = 3; +constexpr DWORD ERROR_MODE_SEM_FAILCRITICALERRORS = 1; +constexpr UINT SEM_FAILCRITICALERRORS = 1; +constexpr UINT SEM_NOOPENFILEERRORBOX = 0x8000; +BOOL CopyFileExW(LPCWSTR from, LPCWSTR to, void* progress, LPVOID data, BOOL* cancel, DWORD flags); +DWORD GetFileType(HANDLE h); +BOOL SetThreadErrorMode(DWORD mode, LPDWORD old); +#define STD_INPUT_HANDLE ((DWORD)-10) +#define STD_OUTPUT_HANDLE ((DWORD)-11) +#define STD_ERROR_HANDLE ((DWORD)-12) +HANDLE GetStdHandle(DWORD which); +DWORD GetLogicalDrives(); // only Z: exists, and it is / +FILE* _wfopen(const wchar_t* path, const wchar_t* mode); + +// ---- strings ----------------------------------------------------------------------------------------------------------- +constexpr UINT CP_ACP = 0; +constexpr UINT CP_UTF8 = 65001; +constexpr DWORD MB_ERR_INVALID_CHARS = 8; +constexpr DWORD WC_ERR_INVALID_CHARS = 0x80; +int MultiByteToWideChar(UINT cp, DWORD flags, const char* s, int n, wchar_t* out, int outN); +int WideCharToMultiByte(UINT cp, DWORD flags, const wchar_t* s, int n, char* out, int outN, const char* def, BOOL* used); +int _wcsicmp(const wchar_t* a, const wchar_t* b); +inline LPWSTR lstrcatW(LPWSTR a, LPCWSTR b) { return wcscat(a, b); } +int _wcsnicmp(const wchar_t* a, const wchar_t* b, size_t n); +int _stricmp(const char* a, const char* b); +constexpr int CSTR_LESS_THAN = 1; +constexpr int CSTR_EQUAL = 2; +constexpr int CSTR_GREATER_THAN = 3; +int CompareStringOrdinal(const wchar_t* a, int an, const wchar_t* b, int bn, BOOL ignoreCase); +int sscanf_s(const char* s, const char* fmt, ...); // the size argument after each %s, %c and %[ is read and dropped +int _wtoi(const wchar_t* s); +long long _wtoi64(const wchar_t* s); +#define wcsicmp _wcsicmp +#define stricmp _stricmp +constexpr DWORD FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x100; +constexpr DWORD FORMAT_MESSAGE_IGNORE_INSERTS = 0x200; +constexpr DWORD FORMAT_MESSAGE_FROM_SYSTEM = 0x1000; +DWORD FormatMessageW(DWORD flags, LPCVOID src, DWORD id, DWORD lang, LPWSTR buf, DWORD size, void* args); +HLOCAL LocalFree(HLOCAL p); +// Security descriptors do not exist here: always FALSE (ERROR_NOT_SUPPORTED), *sd null. Callers that go on without one get +// the POSIX permissions instead (a named mutex: its lock file is the user's own, mode 0600). +constexpr DWORD SDDL_REVISION_1 = 1; +BOOL ConvertStringSecurityDescriptorToSecurityDescriptorW(LPCWSTR sddl, DWORD revision, PSECURITY_DESCRIPTOR* sd, ULONG* size); +HANDLE GetProcessHeap(); +BOOL HeapFree(HANDLE heap, DWORD flags, LPVOID p); +[[noreturn]] void ExitProcess(UINT code); +DWORD GetEnvironmentVariableW(LPCWSTR name, LPWSTR out, DWORD size); +BOOL SetEnvironmentVariableW(LPCWSTR name, LPCWSTR value); +LPWCH GetEnvironmentStringsW(); +BOOL FreeEnvironmentStringsW(LPWCH block); + +// ---- time, sleep, ids ---------------------------------------------------------------------------------------------------- +ULONGLONG GetTickCount64(); +void GetLocalTime(SYSTEMTIME* t); +BOOL FileTimeToSystemTime(const FILETIME* ft, SYSTEMTIME* st); +BOOL SystemTimeToFileTime(const SYSTEMTIME* st, FILETIME* ft); +BOOL FileTimeToLocalFileTime(const FILETIME* ft, FILETIME* local); +BOOL LocalFileTimeToFileTime(const FILETIME* local, FILETIME* ft); +LONG CompareFileTime(const FILETIME* a, const FILETIME* b); +void Sleep(DWORD ms); +DWORD GetCurrentProcessId(); +BOOL QueryPerformanceCounter(LARGE_INTEGER* v); +BOOL QueryPerformanceFrequency(LARGE_INTEGER* v); + +// ---- processes, pipes, jobs ---------------------------------------------------------------------------------------------- +constexpr DWORD CREATE_SUSPENDED = 0x4; +constexpr DWORD CREATE_NEW_CONSOLE = 0x10; +constexpr DWORD CREATE_NEW_PROCESS_GROUP = 0x200; +constexpr DWORD CREATE_UNICODE_ENVIRONMENT = 0x400; +constexpr DWORD CREATE_DEFAULT_ERROR_MODE = 0x04000000; +constexpr DWORD CREATE_NO_WINDOW = 0x08000000; +constexpr DWORD DETACHED_PROCESS = 0x8; +constexpr DWORD CREATE_BREAKAWAY_FROM_JOB = 0x01000000; +constexpr DWORD BELOW_NORMAL_PRIORITY_CLASS = 0x4000; +constexpr DWORD IDLE_PRIORITY_CLASS = 0x40; +constexpr DWORD NORMAL_PRIORITY_CLASS = 0x20; +constexpr DWORD ABOVE_NORMAL_PRIORITY_CLASS = 0x8000; +constexpr DWORD STARTF_USESHOWWINDOW = 1; +constexpr DWORD STARTF_USESTDHANDLES = 0x100; +constexpr DWORD HANDLE_FLAG_INHERIT = 1; +constexpr DWORD INFINITE = 0xFFFFFFFFu; +constexpr DWORD WAIT_OBJECT_0 = 0; +constexpr DWORD WAIT_TIMEOUT = 258; +constexpr DWORD WAIT_FAILED = 0xFFFFFFFFu; +constexpr DWORD WAIT_ABANDONED = 0x80; +constexpr DWORD STILL_ACTIVE = 259; +constexpr DWORD PROCESS_TERMINATE = 1; +constexpr DWORD PROCESS_QUERY_LIMITED_INFORMATION = 0x1000; +constexpr DWORD PROCESS_QUERY_INFORMATION = 0x400; +constexpr DWORD SYNCHRONIZE_ACCESS_UNUSED = 0; +constexpr DWORD TH32CS_SNAPPROCESS = 2; +constexpr DWORD JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x2000; +constexpr DWORD TOKEN_QUERY = 8; +constexpr DWORD SW_HIDE = 0; +constexpr DWORD SW_SHOWNORMAL = 1; +constexpr DWORD SW_SHOW = 5; +constexpr DWORD SW_SHOWNOACTIVATE = 4; +constexpr DWORD SW_SHOWMINNOACTIVE = 7; +constexpr DWORD SEE_MASK_NOCLOSEPROCESS = 0x40; +constexpr DWORD SEE_MASK_FLAG_NO_UI = 0x400; +constexpr DWORD SEE_MASK_NOASYNC = 0x100; +constexpr DWORD SEE_MASK_FLAG_DDEWAIT = 0x100; +constexpr DWORD COINIT_APARTMENTTHREADED = 2; +constexpr DWORD COINIT_MULTITHREADED = 0; +constexpr DWORD COINIT_DISABLE_OLE1DDE = 4; +constexpr DWORD CLSCTX_INPROC_SERVER = 1; +typedef struct _STARTUPINFOW { + DWORD cb; LPWSTR lpReserved, lpDesktop, lpTitle; DWORD dwX, dwY, dwXSize, dwYSize, dwXCountChars, dwYCountChars, dwFillAttribute, dwFlags; + WORD wShowWindow, cbReserved2; LPBYTE lpReserved2; HANDLE hStdInput, hStdOutput, hStdError; +} STARTUPINFOW; +typedef struct _PROCESS_INFORMATION { HANDLE hProcess, hThread; DWORD dwProcessId, dwThreadId; } PROCESS_INFORMATION; +typedef struct tagPROCESSENTRY32W { + DWORD dwSize, cntUsage, th32ProcessID; ULONG_PTR th32DefaultHeapID; DWORD th32ModuleID, cntThreads, th32ParentProcessID; + LONG pcPriClassBase; DWORD dwFlags; wchar_t szExeFile[MAX_PATH]; +} PROCESSENTRY32W; +typedef enum _JOBOBJECTINFOCLASS { JobObjectBasicAccountingInformation = 1, JobObjectExtendedLimitInformation = 9 } JOBOBJECTINFOCLASS; +typedef struct _JOBOBJECT_BASIC_LIMIT_INFORMATION { + LARGE_INTEGER PerProcessUserTimeLimit, PerJobUserTimeLimit; DWORD LimitFlags; SIZE_T MinimumWorkingSetSize, MaximumWorkingSetSize; + DWORD ActiveProcessLimit; ULONG_PTR Affinity; DWORD PriorityClass, SchedulingClass; +} JOBOBJECT_BASIC_LIMIT_INFORMATION; +typedef struct _IO_COUNTERS { ULONGLONG ReadOperationCount, WriteOperationCount, OtherOperationCount, ReadTransferCount, WriteTransferCount, OtherTransferCount; } IO_COUNTERS; +typedef struct _JOBOBJECT_EXTENDED_LIMIT_INFORMATION { + JOBOBJECT_BASIC_LIMIT_INFORMATION BasicLimitInformation; IO_COUNTERS IoInfo; + SIZE_T ProcessMemoryLimit, JobMemoryLimit, PeakProcessMemoryUsed, PeakJobMemoryUsed; +} JOBOBJECT_EXTENDED_LIMIT_INFORMATION; +typedef struct _JOBOBJECT_BASIC_ACCOUNTING_INFORMATION { + LARGE_INTEGER TotalUserTime, TotalKernelTime, ThisPeriodTotalUserTime, ThisPeriodTotalKernelTime; + DWORD TotalPageFaultCount, TotalProcesses, ActiveProcesses, TotalTerminatedProcesses; +} JOBOBJECT_BASIC_ACCOUNTING_INFORMATION; + +BOOL CreateProcessW(LPCWSTR app, LPWSTR cmdline, LPSECURITY_ATTRIBUTES pa, LPSECURITY_ATTRIBUTES ta, BOOL inherit, DWORD flags, + LPVOID env, LPCWSTR dir, STARTUPINFOW* si, PROCESS_INFORMATION* pi); +DWORD WaitForSingleObject(HANDLE h, DWORD ms); // a process, a mutex or an event + +// ---- synchronization ----------------------------------------------------------------------------------------------------- +// Named mutexes (win32_posix_sync.cpp): a lock file per name in this user's runtime folder ($XDG_RUNTIME_DIR, else the +// XDG data folder), with Linux open file description locks (fcntl F_OFD_SETLK) on two bytes: byte 0 read-locked by every +// handle (the object exists while one is open: ERROR_ALREADY_EXISTS, OpenMutexW), byte 1 write-locked by the owner. The kernel +// drops both when a process ends, so a dead owner never keeps it: the next owner gets WAIT_ABANDONED (the file's first bytes +// say "owned" until a ReleaseMutex). Owned by a thread and recursive for it, as on Windows; WaitForSingleObject's timeout is +// kept by polling (1 to 20 ms). Global\ and Local\ are the same per-user folder: two Linux accounts do not see each other's +// names, and a Windows program under Wine has its own (wineserver's) names. Unnamed mutexes are not supported. A thread that +// ends while it owns one keeps it until its process ends or closes every handle of it (Windows abandons it at the thread's end). +constexpr DWORD MUTEX_MODIFY_STATE = 0x0001; +constexpr DWORD ERROR_NOT_OWNER = 288; +HANDLE CreateMutexW(LPSECURITY_ATTRIBUTES sa, BOOL initialOwner, LPCWSTR name); +HANDLE OpenMutexW(DWORD access, BOOL inherit, LPCWSTR name); // ERROR_FILE_NOT_FOUND when no handle of that name is open +BOOL ReleaseMutex(HANDLE h); // ERROR_NOT_OWNER from a thread that does not own it +// Events: unnamed only, within this process (a name: ERROR_NOT_SUPPORTED). +HANDLE CreateEventW(LPSECURITY_ATTRIBUTES sa, BOOL manualReset, BOOL initialState, LPCWSTR name); +BOOL SetEvent(HANDLE h); +inline LONG InterlockedIncrement(volatile LONG* p) { return __atomic_add_fetch(p, 1, __ATOMIC_SEQ_CST); } +BOOL GetExitCodeProcess(HANDLE h, LPDWORD code); +BOOL TerminateProcess(HANDLE h, UINT code); +DWORD ResumeThread(HANDLE h); +HANDLE GetCurrentProcess(); +BOOL CreatePipe(HANDLE* read, HANDLE* write, LPSECURITY_ATTRIBUTES sa, DWORD size); +BOOL PeekNamedPipe(HANDLE h, LPVOID buf, DWORD size, LPDWORD read, LPDWORD available, LPDWORD left); +BOOL SetHandleInformation(HANDLE h, DWORD mask, DWORD flags); +HANDLE CreateJobObjectW(LPSECURITY_ATTRIBUTES sa, LPCWSTR name); +BOOL SetInformationJobObject(HANDLE job, JOBOBJECTINFOCLASS cls, LPVOID info, DWORD size); +BOOL QueryInformationJobObject(HANDLE job, JOBOBJECTINFOCLASS cls, LPVOID info, DWORD size, LPDWORD returned); +BOOL AssignProcessToJobObject(HANDLE job, HANDLE process); +BOOL TerminateJobObject(HANDLE job, UINT code); +HANDLE CreateToolhelp32Snapshot(DWORD flags, DWORD pid); +BOOL Process32FirstW(HANDLE snap, PROCESSENTRY32W* pe); +BOOL Process32NextW(HANDLE snap, PROCESSENTRY32W* pe); +BOOL OpenProcessToken(HANDLE process, DWORD access, HANDLE* token); +HANDLE OpenProcess(DWORD access, BOOL inherit, DWORD pid); + +// tokens and SIDs: this process's user is real (uid), "elevated" means root +typedef enum _TOKEN_INFORMATION_CLASS { TokenUser = 1, TokenElevation = 20 } TOKEN_INFORMATION_CLASS; +typedef struct _SID_PLACEHOLDER { uint32_t uid; } SID, *PSID; +typedef struct _SID_AND_ATTRIBUTES { PSID Sid; DWORD Attributes; } SID_AND_ATTRIBUTES; +typedef struct _TOKEN_USER { SID_AND_ATTRIBUTES User; } TOKEN_USER; +typedef struct _TOKEN_ELEVATION { DWORD TokenIsElevated; } TOKEN_ELEVATION; +BOOL GetTokenInformation(HANDLE token, TOKEN_INFORMATION_CLASS cls, LPVOID info, DWORD size, LPDWORD needed); +BOOL ConvertSidToStringSidW(PSID sid, LPWSTR* out); + +// ---- modules (no Windows DLL exists here) ------------------------------------------------------------------------------- +constexpr DWORD LOAD_LIBRARY_SEARCH_SYSTEM32 = 0x800; +constexpr DWORD LOAD_LIBRARY_SEARCH_DEFAULT_DIRS = 0x1000; +constexpr DWORD LOAD_LIBRARY_SEARCH_APPLICATION_DIR = 0x200; +constexpr DWORD LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR = 0x100; +constexpr DWORD LOAD_WITH_ALTERED_SEARCH_PATH = 8; +HMODULE LoadLibraryExW(LPCWSTR name, HANDLE file, DWORD flags); +HMODULE GetModuleHandleW(LPCWSTR name); +FARPROC GetProcAddress(HMODULE m, LPCSTR name); + +// ---- registry ---------------------------------------------------------------------------------------------------------- +#define HKEY_CLASSES_ROOT ((HKEY)(ULONG_PTR)(LONG)0x80000000) +#define HKEY_CURRENT_USER ((HKEY)(ULONG_PTR)(LONG)0x80000001) +#define HKEY_LOCAL_MACHINE ((HKEY)(ULONG_PTR)(LONG)0x80000002) +#define HKEY_USERS ((HKEY)(ULONG_PTR)(LONG)0x80000003) +constexpr DWORD REG_NONE = 0; +constexpr DWORD REG_SZ = 1; +constexpr DWORD REG_EXPAND_SZ = 2; +constexpr DWORD REG_BINARY = 3; +constexpr DWORD REG_DWORD = 4; +constexpr DWORD REG_MULTI_SZ = 7; +constexpr DWORD REG_QWORD = 11; +constexpr DWORD KEY_QUERY_VALUE = 1; +constexpr DWORD KEY_SET_VALUE = 2; +constexpr DWORD KEY_CREATE_SUB_KEY = 4; +constexpr DWORD KEY_ENUMERATE_SUB_KEYS = 8; +constexpr DWORD KEY_NOTIFY = 0x10; +constexpr DWORD KEY_READ = 0x20019; +constexpr DWORD KEY_WRITE = 0x20006; +constexpr DWORD KEY_ALL_ACCESS = 0xF003F; +constexpr DWORD KEY_WOW64_32KEY = 0x200; +constexpr DWORD KEY_WOW64_64KEY = 0x100; +constexpr DWORD REG_OPTION_NON_VOLATILE = 0; +constexpr DWORD REG_OPTION_VOLATILE = 1; +constexpr DWORD REG_CREATED_NEW_KEY = 1; +constexpr DWORD REG_OPENED_EXISTING_KEY = 2; +constexpr DWORD RRF_RT_REG_SZ = 2; +constexpr DWORD RRF_RT_REG_DWORD = 0x10; +constexpr DWORD RRF_RT_ANY = 0xFFFF; +LSTATUS RegOpenKeyExW(HKEY key, LPCWSTR sub, DWORD options, REGSAM sam, PHKEY out); +LSTATUS RegCreateKeyExW(HKEY key, LPCWSTR sub, DWORD reserved, LPWSTR cls, DWORD options, REGSAM sam, LPSECURITY_ATTRIBUTES sa, PHKEY out, LPDWORD disposition); +LSTATUS RegCloseKey(HKEY key); +LSTATUS RegQueryValueExW(HKEY key, LPCWSTR name, LPDWORD reserved, LPDWORD type, LPBYTE data, LPDWORD size); +LSTATUS RegGetValueW(HKEY key, LPCWSTR sub, LPCWSTR name, DWORD flags, LPDWORD type, PVOID data, LPDWORD size); +LSTATUS RegSetValueExW(HKEY key, LPCWSTR name, DWORD reserved, DWORD type, const BYTE* data, DWORD size); +LSTATUS RegDeleteKeyW(HKEY key, LPCWSTR sub); +LSTATUS RegEnumKeyExW(HKEY key, DWORD index, LPWSTR name, LPDWORD nameLen, LPDWORD reserved, LPWSTR cls, LPDWORD classLen, FILETIME* written); +LSTATUS RegLoadAppKeyW(LPCWSTR file, PHKEY out, REGSAM sam, DWORD options, DWORD reserved); + +// ---- shell ------------------------------------------------------------------------------------------------------------- +extern const GUID FOLDERID_LocalAppData, FOLDERID_Desktop, FOLDERID_Documents, FOLDERID_Programs, FOLDERID_RoamingAppData, + FOLDERID_ProgramData, FOLDERID_Profile, FOLDERID_StartMenu, FOLDERID_ProgramFiles, FOLDERID_ProgramFilesX86, FOLDERID_Downloads; +constexpr DWORD KF_FLAG_DEFAULT = 0; +constexpr DWORD KF_FLAG_CREATE = 0x8000; +constexpr DWORD KF_FLAG_DONT_VERIFY = 0x4000; +HRESULT SHGetKnownFolderPath(REFKNOWNFOLDERID id, DWORD flags, HANDLE token, PWSTR* out); +void CoTaskMemFree(LPVOID p); +LPVOID CoTaskMemAlloc(SIZE_T n); +HRESULT CoInitializeEx(LPVOID reserved, DWORD model); +void CoUninitialize(); +typedef struct _SHELLEXECUTEINFOW { + DWORD cbSize, fMask; HWND hwnd; LPCWSTR lpVerb, lpFile, lpParameters, lpDirectory; int nShow; HINSTANCE hInstApp; + LPVOID lpIDList; LPCWSTR lpClass; HKEY hkeyClass; DWORD dwHotKey; HANDLE hIcon; HANDLE hProcess; +} SHELLEXECUTEINFOW; +BOOL ShellExecuteExW(SHELLEXECUTEINFOW* sei); + +// COM interfaces the core names. Objects cannot be created (CoCreateInstance fails), so they are declarations only. +struct IUnknown { + virtual HRESULT QueryInterface(REFIID id, void** out) = 0; + virtual ULONG AddRef() = 0; + virtual ULONG Release() = 0; +}; +struct IPersistFile : IUnknown { virtual HRESULT Save(LPCWSTR file, BOOL remember) = 0; }; +struct IShellLinkW : IUnknown { + virtual HRESULT SetPath(LPCWSTR path) = 0; + virtual HRESULT SetWorkingDirectory(LPCWSTR dir) = 0; + virtual HRESULT SetDescription(LPCWSTR text) = 0; + virtual HRESULT SetIconLocation(LPCWSTR path, int index) = 0; + virtual HRESULT SetArguments(LPCWSTR args) = 0; +}; +extern const GUID CLSID_ShellLink, IID_IShellLinkW, IID_IPersistFile; +HRESULT CoCreateInstance(REFCLSID cls, IUnknown* outer, DWORD context, REFIID iid, LPVOID* out); + +// DXGI: interfaces only; CreateDXGIFactory1 is reached through GetProcAddress of a DLL that does not load here +struct IDXGIObject : IUnknown {}; +struct IDXGIDevice : IDXGIObject {}; +constexpr UINT DXGI_ADAPTER_FLAG_NONE = 0; +constexpr UINT DXGI_ADAPTER_FLAG_REMOTE = 1; +constexpr UINT DXGI_ADAPTER_FLAG_SOFTWARE = 2; +typedef struct _LUID { DWORD LowPart; LONG HighPart; } LUID; +typedef struct DXGI_ADAPTER_DESC1 { + wchar_t Description[128]; UINT VendorId, DeviceId, SubSysId, Revision; SIZE_T DedicatedVideoMemory, DedicatedSystemMemory, SharedSystemMemory; + LUID AdapterLuid; UINT Flags; +} DXGI_ADAPTER_DESC1; +struct IDXGIAdapter1 : IDXGIObject { + virtual HRESULT CheckInterfaceSupport(REFIID id, LARGE_INTEGER* umd) = 0; + virtual HRESULT GetDesc1(DXGI_ADAPTER_DESC1* desc) = 0; +}; +struct IDXGIFactory1 : IDXGIObject { virtual HRESULT EnumAdapters1(UINT index, IDXGIAdapter1** out) = 0; }; +template const GUID& wg_posix_uuidof(); +#define __uuidof(T) (::wg_posix_uuidof()) + +// event log (wevtapi): types for the function pointers the core casts GetProcAddress results to +constexpr DWORD EvtQueryChannelPath = 1; +constexpr DWORD EvtQueryReverseDirection = 0x200; +constexpr DWORD EvtRenderEventXml = 1; + +// ---- WinHTTP: no network access in this build; every call that would start one fails ---------------------------------- +constexpr DWORD WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY = 4; +constexpr DWORD WINHTTP_FLAG_SECURE = 0x00800000; +constexpr DWORD WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2 = 0x00000800; +constexpr DWORD WINHTTP_OPTION_SECURE_PROTOCOLS = 84; +constexpr DWORD WINHTTP_QUERY_STATUS_CODE = 19; +constexpr DWORD WINHTTP_QUERY_FLAG_NUMBER = 0x20000000; +constexpr DWORD ICU_ESCAPE = 0x80000000; +typedef WORD INTERNET_PORT; +typedef enum { INTERNET_SCHEME_HTTP = 1, INTERNET_SCHEME_HTTPS = 2 } INTERNET_SCHEME; +typedef struct _URL_COMPONENTS { + DWORD dwStructSize; LPWSTR lpszScheme; DWORD dwSchemeLength; INTERNET_SCHEME nScheme; LPWSTR lpszHostName; DWORD dwHostNameLength; + INTERNET_PORT nPort; LPWSTR lpszUserName; DWORD dwUserNameLength; LPWSTR lpszPassword; DWORD dwPasswordLength; + LPWSTR lpszUrlPath; DWORD dwUrlPathLength; LPWSTR lpszExtraInfo; DWORD dwExtraInfoLength; +} URL_COMPONENTS, *LPURL_COMPONENTS; +#define WINHTTP_NO_PROXY_NAME nullptr +#define WINHTTP_NO_PROXY_BYPASS nullptr +#define WINHTTP_NO_REFERER nullptr +#define WINHTTP_DEFAULT_ACCEPT_TYPES nullptr +#define WINHTTP_NO_ADDITIONAL_HEADERS nullptr +#define WINHTTP_NO_REQUEST_DATA nullptr +#define WINHTTP_HEADER_NAME_BY_INDEX nullptr +#define WINHTTP_NO_HEADER_INDEX nullptr +HINTERNET WinHttpOpen(LPCWSTR agent, DWORD access, LPCWSTR proxy, LPCWSTR bypass, DWORD flags); +BOOL WinHttpSetTimeouts(HINTERNET h, int resolve, int connect, int send, int receive); +BOOL WinHttpSetOption(HINTERNET h, DWORD option, LPVOID buf, DWORD size); +BOOL WinHttpCrackUrl(LPCWSTR url, DWORD length, DWORD flags, LPURL_COMPONENTS uc); +HINTERNET WinHttpConnect(HINTERNET session, LPCWSTR host, INTERNET_PORT port, DWORD reserved); +HINTERNET WinHttpOpenRequest(HINTERNET conn, LPCWSTR verb, LPCWSTR path, LPCWSTR version, LPCWSTR referer, LPCWSTR* accept, DWORD flags); +BOOL WinHttpSendRequest(HINTERNET req, LPCWSTR headers, DWORD headersLen, LPVOID data, DWORD dataLen, DWORD totalLen, DWORD_PTR ctx); +BOOL WinHttpReceiveResponse(HINTERNET req, LPVOID reserved); +BOOL WinHttpQueryHeaders(HINTERNET req, DWORD level, LPCWSTR name, LPVOID buf, LPDWORD len, LPDWORD index); +BOOL WinHttpReadData(HINTERNET req, LPVOID buf, DWORD size, LPDWORD got); +BOOL WinHttpCloseHandle(HINTERNET h); + +// ---- OS version (RtlGetVersion is reached through GetProcAddress of ntdll, which does not load here) ---------------------- +typedef HANDLE HRSRC; +typedef HANDLE HGLOBAL; +#define MAKEINTRESOURCEW(i) ((LPWSTR)(ULONG_PTR)(WORD)(i)) +HRSRC FindResourceW(HMODULE m, LPCWSTR name, LPCWSTR type); // RCDATA from the generated table (resources.S); fails when the build has none +HGLOBAL LoadResource(HMODULE m, HRSRC r); +DWORD SizeofResource(HMODULE m, HRSRC r); +LPVOID LockResource(HGLOBAL h); +BOOL QueryFullProcessImageNameW(HANDLE process, DWORD flags, LPWSTR out, LPDWORD size); +inline int gmtime_s(struct tm* out, const time_t* t) { return gmtime_r(t, out) ? 0 : 22; } // the MSVC argument order + +typedef struct _OSVERSIONINFOW { + DWORD dwOSVersionInfoSize, dwMajorVersion, dwMinorVersion, dwBuildNumber, dwPlatformId; wchar_t szCSDVersion[128]; +} OSVERSIONINFOW; diff --git a/clean/installer/src/platform/posix/win32_posix_internal.h b/clean/installer/src/platform/posix/win32_posix_internal.h new file mode 100644 index 00000000..46bdb081 --- /dev/null +++ b/clean/installer/src/platform/posix/win32_posix_internal.h @@ -0,0 +1,100 @@ +// SPDX-License-Identifier: MIT +// Linux layer internals shared by win32_posix*.cpp: the handle table, path and string conversion, error mapping. +#pragma once +#include +#include + +#include +#include +#include + +#include "win32_posix.h" + +namespace wgposix { + +// One object type behind every HANDLE. Kind says which fields mean something. +enum class Kind { File, Pipe, Map, Process, Thread, Find, Job, Snapshot, Token, Mutex, Event }; +struct Handle { + Kind kind; + int fd = -1; // File, Pipe, Map (dup of the file), Mutex (its lock file) + std::string path; // File: for FILE_FLAG_DELETE_ON_CLOSE + dev_t dev = 0; ino_t ino = 0; // File: identity for the sharing table; Mutex: the lock file's + bool read = false, write = false, del = false; // File: what it was opened for (sharing rules) + DWORD share = 0; // File: FILE_SHARE_* it allows others + bool tracked = false; // File: is in the sharing table + bool deleteOnClose = false; + bool inheritable = false; // Pipe: SECURITY_ATTRIBUTES said inherit + bool borrowed = false; // Pipe: standard handle, the fd is not ours to close + uint64_t mapSize = 0; DWORD mapProtect = 0; // Map + int pid = 0; // Process + std::vector pids; // Job: processes assigned to it + bool killOnClose = false; // Job + std::vector found; size_t next = 0; // Find + std::vector procs; // Snapshot + bool manualReset = false, signaled = false; // Event (guarded by the sync file's lock) + explicit Handle(Kind k) : kind(k) {} +}; +Handle* NewHandle(Kind k); +Handle* Lookup(HANDLE h, Kind k); // null (and ERROR_INVALID_HANDLE) when h is not a live handle of that kind +void Forget(Handle* h); + +// UTF-8 <-> wchar_t. Bytes that are not UTF-8 travel as U+DC80..U+DCFF and come back as the same bytes. +std::string ToUtf8(const wchar_t* s, size_t n); +std::wstring FromUtf8(const char* s, size_t n); +inline std::string ToUtf8(const std::wstring& s) { return ToUtf8(s.data(), s.size()); } +inline std::wstring FromUtf8(const std::string& s) { return FromUtf8(s.data(), s.size()); } + +// A Windows path as a POSIX path ("\" to "/", "\\?\" gone, "Z:\" is "/"); false with `err` set for one that cannot exist here. +// Names that differ from the real ones only in case are matched to the real ones (NTFS ignores case; ext4 does not). +bool ToPosix(const wchar_t* w, std::string& out, DWORD& err); +bool ToPosix(const wchar_t* w, std::string& out); // sets the last error +std::string FixCase(const std::string& p); +wint_t FoldChar(wint_t c); // simple Unicode case folding, for names +std::wstring WinPath(const std::string& posix); // an absolute POSIX path as "Z:\..."; a relative one as it is + +DWORD ErrorFromErrno(int e, const std::string& path); +void SetErrorFromErrno(int e, const std::string& path); +inline bool Fail(DWORD e) { SetLastError(e); return false; } + +DWORD AttributesOf(const struct stat& lst, const std::string& path); // lst: from lstat +FILETIME FileTimeOf(const struct timespec& t); +struct timespec TimespecOf(const FILETIME& ft); +void FillFind(WIN32_FIND_DATAW& d, const struct stat& lst, const std::string& path, const std::string& name); + +// sharing: does a delete, move or replace of the file with this identity clash with another open handle? +bool ShareAllowsDelete(const struct stat& st); +// a child process, reaped once however many handles name it +struct ChildState { bool exited = false; int code = 0; int forcedCode = -1; int refs = 0; /* open process handles */ bool suspended = false; + std::string image; /* the program a suspended start will exec, until it has */ }; +bool PollChild(int pid, ChildState& out); +void KillChild(int pid, int code); + +// named mutexes and events (win32_posix_sync.cpp): WaitForSingleObject on them, CloseHandle of a mutex (before its fd closes) +DWORD WaitMutex(Handle* h, DWORD ms); +DWORD WaitEvent(Handle* h, DWORD ms); +void CloseMutex(Handle* h); + +// the Restart Manager's look at one process (win32_posix_rm.cpp): 1 holds one of the files, 0 not, -1 this user's but unreadable, +// -2 another user's or gone +int RmScanProcess(int pid, const std::vector>& files); +// Is the file (a Windows image) loaded by a Windows program under Wine, as Windows' image check asks before a write open +// (win32_posix.h CreateFileW)? 1 yes (*who: that process), 0 no, -1 cannot be ruled out: a Wine process of this user whose +// maps cannot be read (*who). Only this user's Wine processes are looked at. +int ImageInUse(dev_t dev, ino_t ino, int* who = nullptr); + +// Test seams (posix_layer_tests only): the calls FileRenameInfo's no-replace path makes, to force a file system without +// RENAME_NOREPLACE (EINVAL) or a failing unlink. Never changed outside the tests. +extern int (*g_renameat2)(int, const char*, int, const char*, unsigned int); +extern int (*g_unlink)(const char*); + +// CloseHandle of a job or a process handle +void ReleaseJob(Handle* h); +void ReleaseProcess(Handle* h); + +// registry stores: default HKCU, loaded app hives +std::string HomeDir(); +std::string XdgDataHome(); +std::string XdgConfigHome(); +std::string SteamRoot(); // "" when no Steam install is found + +} // namespace wgposix diff --git a/clean/installer/src/platform/posix/win32_posix_process.cpp b/clean/installer/src/platform/posix/win32_posix_process.cpp new file mode 100644 index 00000000..767c6e71 --- /dev/null +++ b/clean/installer/src/platform/posix/win32_posix_process.cpp @@ -0,0 +1,682 @@ +// SPDX-License-Identifier: MIT +// Linux: Windows process, pipe, job object, token and ShellExecute calls on POSIX (see win32_posix.h). +// +// A process is a child spawned with posix_spawn, reaped once however many handles name it, and forgotten once it is reaped and +// no handle names it. CREATE_SUSPENDED forks instead: the program is found and checked first, so a missing or bad one fails the +// call as it does without the flag; the child then drops the parent's signal handlers and close-on-exec files, stops itself +// (SIGSTOP) before it execs, and ResumeThread sends SIGCONT. Until it has exec'd, its image is the one recorded for it. A job object here is a +// list of process ids, killed one by one, so a child of a child is not in it. No window or priority class exists; those flags +// are ignored. +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "win32_posix_internal.h" + +extern char** environ; + +namespace wgposix { + +// ---- children ---------------------------------------------------------------------------------------------------------- +static std::mutex g_childLock; +static auto& g_children = *new std::map; // never destroyed (see g_handles in win32_posix.cpp) + +static void Reap(int pid, ChildState& c) { + if (c.exited) return; + int status = 0; + const pid_t r = waitpid(pid, &status, WNOHANG); + if (r == pid) { + c.exited = true; + c.code = WIFEXITED(status) ? WEXITSTATUS(status) : c.forcedCode >= 0 ? c.forcedCode : 128 + WTERMSIG(status); + } else if (r < 0 && errno == ECHILD) { // not ours any more (reaped elsewhere): gone + c.exited = true; + c.code = c.forcedCode >= 0 ? c.forcedCode : 0; + } +} +bool PollChild(int pid, ChildState& out) { + std::lock_guard g(g_childLock); + auto it = g_children.find(pid); + if (it == g_children.end()) return false; + Reap(pid, it->second); + out = it->second; + return true; +} +void KillChild(int pid, int code) { + std::lock_guard g(g_childLock); + auto it = g_children.find(pid); + if (it == g_children.end()) return; + Reap(pid, it->second); + if (it->second.exited) return; + it->second.forcedCode = code; + kill(pid, SIGKILL); +} +static void SweepChildren() { // children nobody waits for are reaped here, on the next start; finished ones no handle names go + std::lock_guard g(g_childLock); + for (auto it = g_children.begin(); it != g_children.end();) { + Reap(it->first, it->second); + it = it->second.exited && it->second.refs == 0 ? g_children.erase(it) : std::next(it); + } +} +static void AddChild(int pid, int handles, bool suspended, const std::string& image = std::string()) { + std::lock_guard g(g_childLock); + ChildState c; + c.refs = handles; + c.suspended = suspended; + c.image = image; + g_children[pid] = c; +} + +// ---- jobs -------------------------------------------------------------------------------------------------------------- +static std::mutex g_jobLock; +static auto& g_jobs = *new std::vector; +static void KillJobMembers(Handle* job, int code) { + for (int pid : job->pids) KillChild(pid, code); +} +static void KillJobsAtExit() { + std::lock_guard g(g_jobLock); + for (Handle* j : g_jobs) if (j->killOnClose) KillJobMembers(j, 1); +} +void ReleaseJob(Handle* h) { + std::lock_guard g(g_jobLock); + if (h->killOnClose) KillJobMembers(h, 1); + g_jobs.erase(std::remove(g_jobs.begin(), g_jobs.end(), h), g_jobs.end()); +} +void ReleaseProcess(Handle* h) { + std::lock_guard g(g_childLock); + auto it = g_children.find(h->pid); + if (it == g_children.end()) return; + if (it->second.refs > 0) --it->second.refs; + if (it->second.refs > 0) return; + Reap(h->pid, it->second); + if (it->second.exited) g_children.erase(it); +} + +} // namespace wgposix + +using namespace wgposix; + +// The command line the way CommandLineToArgvW reads it: the first word has no escapes; the rest follow the backslash-quote rules. +static std::vector SplitCommandLine(const wchar_t* c) { + std::vector out; + const size_t n = wcslen(c); + size_t i = 0; + while (i < n && (c[i] == L' ' || c[i] == L'\t')) ++i; + if (i < n) { + const bool quotedName = c[i] == L'"'; + const size_t from = quotedName ? ++i : i; + while (i < n && (quotedName ? c[i] != L'"' : (c[i] != L' ' && c[i] != L'\t'))) ++i; + out.emplace_back(c + from, i - from); + if (quotedName && i < n) ++i; + } + for (;;) { + while (i < n && (c[i] == L' ' || c[i] == L'\t')) ++i; + if (i >= n) break; + std::wstring a; + bool quoted = false; + while (i < n) { + size_t bs = 0; + while (i < n && c[i] == L'\\') { ++bs; ++i; } + if (i < n && c[i] == L'"') { + a.append(bs / 2, L'\\'); + if (bs % 2) { a += L'"'; ++i; } + else if (quoted && i + 1 < n && c[i + 1] == L'"') { a += L'"'; i += 2; } + else { quoted = !quoted; ++i; } + } else { + a.append(bs, L'\\'); + if (i >= n || (!quoted && (c[i] == L' ' || c[i] == L'\t'))) break; + a += c[i++]; + } + } + out.push_back(a); + } + return out; +} + +// ---- the part of a suspended start that happens before fork -------------------------------------------------------------- +// Does the file start like a program the kernel runs: an ELF image or a #! script. Anything else is what execve calls ENOEXEC. +static bool LooksRunnable(const std::string& path) { + const int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC); + if (fd < 0) return true; // unreadable but executable (a setuid program): leave it to exec + char b[4]; + const ssize_t n = read(fd, b, sizeof(b)); + close(fd); + return n >= 2 && ((n == 4 && std::memcmp(b, "\x7f" "ELF", 4) == 0) || (b[0] == '#' && b[1] == '!')); +} +// One candidate for the program: 0 when it can be run, else the errno execve would give for it. `seen` is where the file is as +// the child will see it (after chdir to `cwd`). +static int CheckCandidate(const std::string& cand, const std::string& cwd, std::string& seen) { + seen = cand[0] == '/' || cwd.empty() ? cand : cwd + "/" + cand; + struct stat st; + if (stat(seen.c_str(), &st) != 0) return errno; + if (!S_ISREG(st.st_mode) || access(seen.c_str(), X_OK) != 0) return EACCES; + return LooksRunnable(seen) ? 0 : ENOEXEC; +} +// Finds the program the way posix_spawn(p) does and reports the error it would: `exec` is the name to hand to execve, `image` the +// file's real path. Returns 0, or a Windows error code. +static DWORD ResolveProgram(const std::string& exe, bool search, const std::string& cwd, std::string& exec, std::string& image) { + std::string seen; + int failure = 0; + std::vector candidates; + if (!search) { + candidates.push_back(exe); + } else { + const char* pathEnv = std::getenv("PATH"); + std::string path = pathEnv ? pathEnv : "/usr/local/bin:/usr/bin:/bin"; + for (size_t from = 0;;) { + const size_t colon = path.find(':', from); + std::string dir = path.substr(from, colon == std::string::npos ? std::string::npos : colon - from); + candidates.push_back((dir.empty() ? std::string(".") : dir) + "/" + exe); + if (colon == std::string::npos) break; + from = colon + 1; + } + } + for (const std::string& cand : candidates) { + const int e = CheckCandidate(cand, cwd, seen); + if (e == 0) { + exec = cand; + char real[PATH_MAX]; + image = realpath(seen.c_str(), real) ? real : seen; + return 0; + } + if (!search) return ErrorFromErrno(e, cand); + if (e != ENOENT && e != ENOTDIR && !failure) failure = e; + } + return failure ? ErrorFromErrno(failure, exe) : ERROR_FILE_NOT_FOUND; +} + +// Between fork and exec in the child: only calls that are safe there. Every signal is blocked by now (the parent blocked them +// before it forked), so no handler of the parent's can run; the handlers go, and so does every close-on-exec file the child +// would hold until it execs. +static void ResetSignals() { + for (int sig = 1; sig < NSIG; ++sig) { + struct sigaction sa; + if (sigaction(sig, nullptr, &sa) != 0 || sa.sa_handler == SIG_IGN) continue; // an ignored signal stays ignored through exec + struct sigaction dfl; + std::memset(&dfl, 0, sizeof(dfl)); + dfl.sa_handler = SIG_DFL; + sigaction(sig, &dfl, nullptr); + } +} +static void CloseCloexecFiles(int maxFd) { + struct Dirent64 { uint64_t ino; int64_t off; unsigned short len; unsigned char type; char name[1]; }; + const int dirFd = open("/proc/self/fd", O_RDONLY | O_DIRECTORY | O_CLOEXEC); + if (dirFd >= 0) { + alignas(8) char buf[2048]; + long got; + while ((got = syscall(SYS_getdents64, dirFd, buf, sizeof(buf))) > 0) { + for (long at = 0; at < got;) { + const Dirent64* d = reinterpret_cast(buf + at); + at += d->len; + int fd = 0; + const char* c = d->name; + for (; *c >= '0' && *c <= '9'; ++c) fd = fd * 10 + (*c - '0'); + if (*c || c == d->name || fd < 3 || fd == dirFd) continue; + const int fl = fcntl(fd, F_GETFD); + if (fl >= 0 && (fl & FD_CLOEXEC)) close(fd); + } + } + close(dirFd); + return; + } + for (int fd = 3; fd < maxFd; ++fd) { // no /proc: every number the process may use + const int fl = fcntl(fd, F_GETFD); + if (fl >= 0 && (fl & FD_CLOEXEC)) close(fd); + } +} + +BOOL CreateProcessW(LPCWSTR app, LPWSTR cmdline, LPSECURITY_ATTRIBUTES, LPSECURITY_ATTRIBUTES, BOOL, DWORD flags, LPVOID env, LPCWSTR dir, + STARTUPINFOW* si, PROCESS_INFORMATION* pi) { + std::vector args = SplitCommandLine(cmdline ? cmdline : L""); + const std::wstring exeW = app && *app ? app : args.empty() ? std::wstring() : args[0]; + if (exeW.empty()) return Fail(ERROR_FILE_NOT_FOUND); + if (args.empty()) args.push_back(exeW); + const bool search = !(app && *app) && exeW.find_first_of(L"\\/") == std::wstring::npos; + std::string exe; + if (search) exe = ToUtf8(exeW); + else if (!ToPosix(exeW.c_str(), exe)) return FALSE; + struct stat st; + if (!search && stat(exe.c_str(), &st) != 0) { SetErrorFromErrno(errno, exe); return FALSE; } + if (!search && S_ISDIR(st.st_mode)) return Fail(ERROR_ACCESS_DENIED); + std::string cwd; + if (dir && *dir) { + if (!ToPosix(dir, cwd)) return FALSE; + if (stat(cwd.c_str(), &st) != 0 || !S_ISDIR(st.st_mode)) return Fail(ERROR_DIRECTORY); + } + + std::vector argStore; + for (auto& a : args) argStore.push_back(ToUtf8(a)); + std::vector argv; + for (auto& a : argStore) argv.push_back(a.data()); + argv.push_back(nullptr); + + std::vector envStore; + std::vector envp; + if (env) { + if (flags & CREATE_UNICODE_ENVIRONMENT) { + for (const wchar_t* p = static_cast(env); *p; p += wcslen(p) + 1) envStore.push_back(ToUtf8(p, wcslen(p))); + } else { + for (const char* p = static_cast(env); *p; p += std::strlen(p) + 1) envStore.push_back(p); + } + for (auto& e : envStore) envp.push_back(e.data()); + envp.push_back(nullptr); + } + + int stdFd[3] = {-2, -2, -2}; // what the child gets as 0, 1, 2: a descriptor, -1 for /dev/null, -2 for the parent's own + if (si && (si->dwFlags & STARTF_USESTDHANDLES)) { + const HANDLE std3[3] = {si->hStdInput, si->hStdOutput, si->hStdError}; + for (int n = 0; n < 3; ++n) { + Handle* h = std3[n] && std3[n] != INVALID_HANDLE_VALUE ? Lookup(std3[n], Kind::File) : nullptr; + if (!h && std3[n] && std3[n] != INVALID_HANDLE_VALUE) h = Lookup(std3[n], Kind::Pipe); + stdFd[n] = h ? h->fd : -1; + } + } + char** const childEnv = env ? envp.data() : environ; + SweepChildren(); + pid_t pid = 0; + std::string image; // a suspended start: the program the child will exec + if (flags & CREATE_SUSPENDED) { + // fork, not posix_spawn: the child must stop before it runs a line of the program, and the parent waits to see that. + // Everything the child needs is made here, so that it only has to call what is safe between fork and exec. + std::string execPath; + const DWORD found = ResolveProgram(exe, search, cwd, execPath, image); + if (found) return Fail(found); + struct rlimit rl; + const int maxFd = getrlimit(RLIMIT_NOFILE, &rl) == 0 && rl.rlim_cur < (1u << 20) ? (int)rl.rlim_cur : (1 << 20); + sigset_t all, before; + sigfillset(&all); + pthread_sigmask(SIG_SETMASK, &all, &before); // the child starts with every signal blocked, so no handler runs in it + pid = fork(); + const int forkErr = errno; + if (pid == 0) { + ResetSignals(); + for (int n = 0; n < 3; ++n) { + if (stdFd[n] == n) fcntl(n, F_SETFD, 0); + else if (stdFd[n] >= 0) dup2(stdFd[n], n); + else if (stdFd[n] == -1) { const int f = open("/dev/null", n == 0 ? O_RDONLY : O_WRONLY); if (f >= 0) { dup2(f, n); if (f != n) close(f); } } + } + CloseCloexecFiles(maxFd); + if (!cwd.empty() && chdir(cwd.c_str()) != 0) _exit(126); + raise(SIGSTOP); + sigprocmask(SIG_SETMASK, &before, nullptr); + execve(execPath.c_str(), argv.data(), childEnv); + _exit(127); + } + pthread_sigmask(SIG_SETMASK, &before, nullptr); + if (pid < 0) { SetErrorFromErrno(forkErr, exe); return FALSE; } + int status = 0; + pid_t w; + while ((w = waitpid(pid, &status, WUNTRACED)) < 0 && errno == EINTR) {} + if (w != pid || !WIFSTOPPED(status)) { SetLastError(ERROR_GEN_FAILURE); return FALSE; } // the child died before it stopped + } else { + posix_spawn_file_actions_t fa; + posix_spawn_file_actions_init(&fa); + if (!cwd.empty()) posix_spawn_file_actions_addchdir_np(&fa, cwd.c_str()); + for (int n = 0; n < 3; ++n) { + if (stdFd[n] >= 0) posix_spawn_file_actions_adddup2(&fa, stdFd[n], n); + else if (stdFd[n] == -1) posix_spawn_file_actions_addopen(&fa, n, "/dev/null", n == 0 ? O_RDONLY : O_WRONLY, 0); + } + const int rc = search ? posix_spawnp(&pid, exe.c_str(), &fa, nullptr, argv.data(), childEnv) + : posix_spawn(&pid, exe.c_str(), &fa, nullptr, argv.data(), childEnv); + posix_spawn_file_actions_destroy(&fa); + if (rc != 0) { + SetErrorFromErrno(rc, exe); // ENOEXEC: a file that is no program here (a Windows .exe) is a bad format + return FALSE; + } + } + AddChild(pid, 1, (flags & CREATE_SUSPENDED) != 0, image); + Handle* p = NewHandle(Kind::Process); + p->pid = pid; + Handle* t = NewHandle(Kind::Thread); + t->pid = pid; + if (pi) { pi->hProcess = p; pi->hThread = t; pi->dwProcessId = (DWORD)pid; pi->dwThreadId = (DWORD)pid; } + else { CloseHandle(p); CloseHandle(t); } + return TRUE; +} +DWORD WaitForSingleObject(HANDLE hv, DWORD ms) { + if (Handle* m = Lookup(hv, Kind::Mutex)) return WaitMutex(m, ms); + if (Handle* e = Lookup(hv, Kind::Event)) return WaitEvent(e, ms); + Handle* h = Lookup(hv, Kind::Process); + if (!h) return WAIT_FAILED; + struct timespec start; + clock_gettime(CLOCK_MONOTONIC, &start); + for (;;) { + ChildState c; + if (!PollChild(h->pid, c) || c.exited) return WAIT_OBJECT_0; + if (ms == 0) return WAIT_TIMEOUT; + struct timespec now; + clock_gettime(CLOCK_MONOTONIC, &now); + const long long elapsed = (now.tv_sec - start.tv_sec) * 1000LL + (now.tv_nsec - start.tv_nsec) / 1000000; + if (ms != INFINITE && elapsed >= (long long)ms) return WAIT_TIMEOUT; + Sleep(2); + } +} +BOOL GetExitCodeProcess(HANDLE hv, LPDWORD code) { + Handle* h = Lookup(hv, Kind::Process); + if (!h) return FALSE; + ChildState c; + *code = PollChild(h->pid, c) && c.exited ? (DWORD)c.code : STILL_ACTIVE; + return TRUE; +} +BOOL TerminateProcess(HANDLE hv, UINT code) { + Handle* h = Lookup(hv, Kind::Process); + if (!h) return FALSE; + ChildState c; + if (!PollChild(h->pid, c) || c.exited) return Fail(ERROR_ACCESS_DENIED); + KillChild(h->pid, (int)code); + return TRUE; +} +// The suspend count is 1 for a process started suspended and not yet resumed, else 0. +DWORD ResumeThread(HANDLE hv) { + Handle* t = Lookup(hv, Kind::Thread); + if (!t) return (DWORD)-1; + std::lock_guard g(g_childLock); + auto it = g_children.find(t->pid); + if (it == g_children.end() || !it->second.suspended) return 0; + it->second.suspended = false; + kill(t->pid, SIGCONT); + return 1; +} +HANDLE GetCurrentProcess() { + static Handle* self = [] { Handle* h = NewHandle(Kind::Process); h->pid = getpid(); return h; }(); + return self; +} +HANDLE OpenProcess(DWORD, BOOL, DWORD pid) { + if (kill((pid_t)pid, 0) != 0 && errno != EPERM) { SetErrorFromErrno(errno, ""); return nullptr; } + { + std::lock_guard g(g_childLock); + auto it = g_children.find((int)pid); + if (it != g_children.end()) ++it->second.refs; + } + Handle* h = NewHandle(Kind::Process); + h->pid = (int)pid; + return h; +} + +BOOL CreatePipe(HANDLE* read, HANDLE* write, LPSECURITY_ATTRIBUTES sa, DWORD) { + int fds[2]; + if (pipe2(fds, O_CLOEXEC) != 0) { SetErrorFromErrno(errno, ""); return FALSE; } + Handle* r = NewHandle(Kind::Pipe); + Handle* w = NewHandle(Kind::Pipe); + r->fd = fds[0]; w->fd = fds[1]; + r->inheritable = w->inheritable = sa && sa->bInheritHandle; + *read = r; *write = w; + return TRUE; +} +BOOL PeekNamedPipe(HANDLE hv, LPVOID, DWORD, LPDWORD, LPDWORD available, LPDWORD left) { + Handle* h = Lookup(hv, Kind::Pipe); + if (!h) return FALSE; + int n = 0; + if (ioctl(h->fd, FIONREAD, &n) != 0) { SetErrorFromErrno(errno, ""); return FALSE; } + if (n == 0) { // nothing waiting: a closed write end is an error, as on Windows + struct pollfd p = {h->fd, POLLIN, 0}; + if (poll(&p, 1, 0) > 0 && (p.revents & POLLHUP) && !(p.revents & POLLIN)) return Fail(ERROR_BROKEN_PIPE); + } + if (available) *available = (DWORD)n; + if (left) *left = (DWORD)n; + return TRUE; +} +BOOL SetHandleInformation(HANDLE hv, DWORD mask, DWORD flags) { + Handle* h = Lookup(hv, Kind::Pipe); + if (!h) h = Lookup(hv, Kind::File); + if (!h) return FALSE; + if (mask & HANDLE_FLAG_INHERIT) h->inheritable = flags & HANDLE_FLAG_INHERIT; + return TRUE; +} + +HANDLE CreateJobObjectW(LPSECURITY_ATTRIBUTES, LPCWSTR) { + static std::once_flag once; + std::call_once(once, [] { std::atexit(KillJobsAtExit); }); + Handle* j = NewHandle(Kind::Job); + std::lock_guard g(g_jobLock); + g_jobs.push_back(j); + return j; +} +BOOL SetInformationJobObject(HANDLE hv, JOBOBJECTINFOCLASS cls, LPVOID info, DWORD size) { + Handle* j = Lookup(hv, Kind::Job); + if (!j) return FALSE; + if (cls != JobObjectExtendedLimitInformation || size < sizeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION)) return Fail(ERROR_INVALID_PARAMETER); + std::lock_guard g(g_jobLock); + j->killOnClose = static_cast(info)->BasicLimitInformation.LimitFlags & JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; + return TRUE; +} +BOOL QueryInformationJobObject(HANDLE hv, JOBOBJECTINFOCLASS cls, LPVOID info, DWORD size, LPDWORD returned) { + Handle* j = Lookup(hv, Kind::Job); + if (!j) return FALSE; + if (cls != JobObjectBasicAccountingInformation || size < sizeof(JOBOBJECT_BASIC_ACCOUNTING_INFORMATION)) return Fail(ERROR_INVALID_PARAMETER); + auto* ai = static_cast(info); + std::memset(ai, 0, sizeof(*ai)); + std::lock_guard g(g_jobLock); + for (int pid : j->pids) { + ChildState c; + ++ai->TotalProcesses; + if (PollChild(pid, c) && !c.exited) ++ai->ActiveProcesses; + } + if (returned) *returned = sizeof(*ai); + return TRUE; +} +BOOL AssignProcessToJobObject(HANDLE job, HANDLE process) { + Handle* j = Lookup(job, Kind::Job); + Handle* p = Lookup(process, Kind::Process); + if (!j || !p) return FALSE; + ChildState c; + if (!PollChild(p->pid, c) || c.exited) return Fail(ERROR_ACCESS_DENIED); + std::lock_guard g(g_jobLock); + j->pids.push_back(p->pid); + return TRUE; +} +BOOL TerminateJobObject(HANDLE hv, UINT code) { + Handle* j = Lookup(hv, Kind::Job); + if (!j) return FALSE; + std::lock_guard g(g_jobLock); + KillJobMembers(j, (int)code); + return TRUE; +} + +// What /proc says about a process. The name the kernel keeps (comm) stops at 15 characters, so names come from the command line. +static std::string Slurp(const std::string& f) { + std::string r; + if (FILE* fp = std::fopen(f.c_str(), "r")) { char b[4096]; size_t n; while ((n = std::fread(b, 1, sizeof(b), fp)) > 0) r.append(b, n); std::fclose(fp); } + return r; +} +static std::vector CommandLine(int pid) { + const std::string raw = Slurp("/proc/" + std::to_string(pid) + "/cmdline"); + std::vector out; + for (size_t i = 0; i < raw.size();) { + const size_t e = raw.find('\0', i); + out.push_back(raw.substr(i, e == std::string::npos ? std::string::npos : e - i)); + if (e == std::string::npos) break; + i = e + 1; + } + return out; +} +static std::string BaseOf(const std::string& p) { + const size_t cut = p.find_last_of("\\/"); + return cut == std::string::npos ? p : p.substr(cut + 1); +} +static bool EndsExe(const std::string& s) { return s.size() > 4 && strcasecmp(s.c_str() + s.size() - 4, ".exe") == 0; } +static std::string Lower(std::string s) { for (auto& c : s) c = (char)std::tolower((unsigned char)c); return s; } +// Wine's own program: the Windows program it runs is named in the command line, not in the image. +static bool IsWineLoader(const std::string& image) { + const std::string base = Lower(BaseOf(image)); + if (base == "wine" || base == "wine64" || base == "wine-preloader" || base == "wine64-preloader") return true; + const std::string low = Lower(image); + return low.find("/bin/") != std::string::npos && (low.find("proton") != std::string::npos || low.find("wine") != std::string::npos); +} +// The Windows program a Wine process runs: its own name when that is one (Wine sets it), else the first .exe argument. +static bool WineProgram(const std::vector& args, std::string& out) { + for (const std::string& a : args) if (EndsExe(a)) { out = a; return true; } + return false; +} +static std::string ImageOf(int pid) { + char link[4096]; + const ssize_t n = readlink(("/proc/" + std::to_string(pid) + "/exe").c_str(), link, sizeof(link) - 1); + return n < 0 ? std::string() : std::string(link, (size_t)n); +} +// The program of one of our own children that was started suspended and has not exec'd yet: until then /proc shows this process's +// image, so the one recorded at the start stands in. False for any other process, and once the child runs its own image. +static bool PendingImage(int pid, std::string& image) { + { + std::lock_guard g(g_childLock); + auto it = g_children.find(pid); + if (it == g_children.end() || it->second.image.empty()) return false; + image = it->second.image; + } + const std::string now = ImageOf(pid); + return !now.empty() && now == ImageOf(getpid()); +} + +// Processes by name: the Windows name of a Wine process is in its command line; any other process has its own name. +HANDLE CreateToolhelp32Snapshot(DWORD, DWORD) { + Handle* s = NewHandle(Kind::Snapshot); + DIR* d = opendir("/proc"); + if (!d) { Forget(s); SetErrorFromErrno(errno, ""); return INVALID_HANDLE_VALUE; } + while (dirent* e = readdir(d)) { + char* end = nullptr; + const long pid = std::strtol(e->d_name, &end, 10); + if (*end || pid <= 0) continue; + const std::string base = std::string("/proc/") + e->d_name; + const std::vector cmd = CommandLine((int)pid); + std::string name; + std::string prog; + if (PendingImage((int)pid, prog)) name = BaseOf(prog); + if (name.empty() && IsWineLoader(ImageOf((int)pid)) && WineProgram(cmd, prog)) name = BaseOf(prog); + if (name.empty() && !cmd.empty()) name = BaseOf(cmd[0]); + if (name.empty()) { // a process with no command line (a kernel thread): the kernel's own name + name = Slurp(base + "/comm"); + while (!name.empty() && name.back() == '\n') name.pop_back(); + } + if (name.empty()) continue; + PROCESSENTRY32W pe{}; + pe.dwSize = sizeof(pe); + pe.th32ProcessID = (DWORD)pid; + const std::string stat = Slurp(base + "/stat"); + const size_t paren = stat.rfind(')'); + if (paren != std::string::npos) { int ppid = 0; std::sscanf(stat.c_str() + paren + 2, "%*c %d", &ppid); pe.th32ParentProcessID = (DWORD)ppid; } + const std::wstring w = FromUtf8(name); + wcsncpy(pe.szExeFile, w.c_str(), MAX_PATH - 1); + s->procs.push_back(pe); + } + closedir(d); + return s; +} +BOOL Process32FirstW(HANDLE snap, PROCESSENTRY32W* pe) { + Handle* s = Lookup(snap, Kind::Snapshot); + if (!s) return FALSE; + s->next = 0; + if (s->procs.empty()) return Fail(ERROR_NO_MORE_FILES); + *pe = s->procs[s->next++]; + return TRUE; +} +BOOL Process32NextW(HANDLE snap, PROCESSENTRY32W* pe) { + Handle* s = Lookup(snap, Kind::Snapshot); + if (!s) return FALSE; + if (s->next >= s->procs.size()) return Fail(ERROR_NO_MORE_FILES); + *pe = s->procs[s->next++]; + return TRUE; +} + +// The Windows spelling of the program a process runs. A Wine process runs the loader; its program is the .exe in the command line, and +// with none there the call fails, so a caller that cannot tell takes the process for the one it looks for, as it does for a +// process it cannot open. +BOOL QueryFullProcessImageNameW(HANDLE process, DWORD, LPWSTR out, LPDWORD size) { + Handle* p = Lookup(process, Kind::Process); + if (!p) return FALSE; + const std::string image = ImageOf(p->pid); + if (image.empty()) { SetLastError(ERROR_ACCESS_DENIED); return FALSE; } + std::wstring w; + std::string prog; + if (PendingImage(p->pid, prog)) { + w = WinPath(prog); + } else if (IsWineLoader(image)) { + if (!WineProgram(CommandLine(p->pid), prog)) return Fail(ERROR_NOT_FOUND); + const bool windows = prog.size() >= 2 && ((prog[1] == ':') || prog.compare(0, 2, "\\\\") == 0); + if (windows) w = FromUtf8(prog); + else { + if (prog[0] != '/') { // relative to the process's own folder + char cwd[4096]; + const ssize_t n = readlink(("/proc/" + std::to_string(p->pid) + "/cwd").c_str(), cwd, sizeof(cwd) - 1); + if (n > 0) prog = std::string(cwd, (size_t)n) + "/" + prog; + } + w = WinPath(prog); + } + } else { + w = WinPath(image); + } + if (!size || *size < w.size() + 1) { if (size) *size = (DWORD)w.size() + 1; return Fail(ERROR_INSUFFICIENT_BUFFER); } + std::memcpy(out, w.c_str(), (w.size() + 1) * sizeof(wchar_t)); + *size = (DWORD)w.size(); + return TRUE; +} + +// A token is this process's: its user is the real uid and "elevated" means root. +BOOL OpenProcessToken(HANDLE process, DWORD, HANDLE* token) { + if (!Lookup(process, Kind::Process)) return FALSE; + *token = NewHandle(Kind::Token); + return TRUE; +} +BOOL GetTokenInformation(HANDLE token, TOKEN_INFORMATION_CLASS cls, LPVOID info, DWORD size, LPDWORD needed) { + if (!Lookup(token, Kind::Token)) return FALSE; + if (cls == TokenElevation) { + if (needed) *needed = sizeof(TOKEN_ELEVATION); + if (size < sizeof(TOKEN_ELEVATION)) return Fail(ERROR_INSUFFICIENT_BUFFER); + static_cast(info)->TokenIsElevated = geteuid() == 0; + return TRUE; + } + if (cls == TokenUser) { + const DWORD need = sizeof(TOKEN_USER) + sizeof(SID); + if (needed) *needed = need; + if (size < need) return Fail(ERROR_INSUFFICIENT_BUFFER); + SID* sid = reinterpret_cast(static_cast(info) + sizeof(TOKEN_USER)); + sid->uid = (uint32_t)geteuid(); + static_cast(info)->User = SID_AND_ATTRIBUTES{sid, 0}; + return TRUE; + } + return Fail(ERROR_INVALID_PARAMETER); +} +BOOL ConvertSidToStringSidW(PSID sid, LPWSTR* out) { + if (!sid) return Fail(ERROR_INVALID_PARAMETER); + const std::wstring s = L"S-1-22-1-" + std::to_wstring(sid->uid); // the Unix user authority + wchar_t* m = static_cast(std::malloc((s.size() + 1) * sizeof(wchar_t))); + if (!m) return Fail(ERROR_NOT_ENOUGH_MEMORY); + std::memcpy(m, s.c_str(), (s.size() + 1) * sizeof(wchar_t)); + *out = m; + return TRUE; +} + +// ShellExecuteExW: documents and addresses go to xdg-open; a Windows program has no way to start here. +BOOL ShellExecuteExW(SHELLEXECUTEINFOW* sei) { + if (!sei || !sei->lpFile || !*sei->lpFile) return Fail(ERROR_FILE_NOT_FOUND); + const std::wstring file = sei->lpFile; + auto ends = [&](const wchar_t* ext) { const size_t n = wcslen(ext); return file.size() >= n && _wcsicmp(file.c_str() + file.size() - n, ext) == 0; }; + if (ends(L".exe") || ends(L".com") || ends(L".bat") || ends(L".cmd") || ends(L".msi")) return Fail(ERROR_NOT_SUPPORTED); + const size_t colon = file.find(L':'); + const bool address = colon != std::wstring::npos && colon > 1 && file.find_first_of(L"\\/") > colon; + std::string target; + if (address) target = ToUtf8(file); + else if (!ToPosix(file.c_str(), target)) return FALSE; + std::vector argv = {const_cast("xdg-open"), target.data(), nullptr}; + posix_spawn_file_actions_t fa; + posix_spawn_file_actions_init(&fa); + for (int n = 0; n < 3; ++n) posix_spawn_file_actions_addopen(&fa, n, "/dev/null", n == 0 ? O_RDONLY : O_WRONLY, 0); + pid_t pid = 0; + SweepChildren(); + const int rc = posix_spawnp(&pid, "xdg-open", &fa, nullptr, argv.data(), environ); + posix_spawn_file_actions_destroy(&fa); + if (rc != 0) return Fail(rc == ENOENT ? ERROR_NO_ASSOCIATION : ErrorFromErrno(rc, "")); + AddChild(pid, (sei->fMask & SEE_MASK_NOCLOSEPROCESS) ? 1 : 0, false); + sei->hInstApp = reinterpret_cast(static_cast(33)); + if (sei->fMask & SEE_MASK_NOCLOSEPROCESS) { Handle* p = NewHandle(Kind::Process); p->pid = pid; sei->hProcess = p; } + return TRUE; +} diff --git a/clean/installer/src/platform/posix/win32_posix_registry.cpp b/clean/installer/src/platform/posix/win32_posix_registry.cpp new file mode 100644 index 00000000..9f1cd9bb --- /dev/null +++ b/clean/installer/src/platform/posix/win32_posix_registry.cpp @@ -0,0 +1,383 @@ +// SPDX-License-Identifier: MIT +// Linux: the Windows registry as a small file-backed store (see win32_posix.h). +// +// HKEY_CURRENT_USER lives in $WRONGGPU_REGISTRY_FILE, else $XDG_DATA_HOME/WrongGPU/registry.ini (default ~/.local/share). A +// WRONGGPU_TESTING build keeps it in memory unless WRONGGPU_REGISTRY_FILE is set: a test run never writes the player's file. +// Hives opened with RegLoadAppKeyW are files of their own. HKEY_LOCAL_MACHINE, HKEY_USERS and HKEY_CLASSES_ROOT read as empty +// and refuse writes. HKCU\Software\Valve\Steam\SteamPath, when nothing was stored there, is the Linux Steam folder. +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "win32_posix_internal.h" + +using namespace wgposix; + +namespace { + +struct Value { std::string name; DWORD type = REG_NONE; std::string data; }; // strings: UTF-8 text; the rest: raw bytes +struct Key { std::string name; std::map values; }; // values by lower-case name + +std::string LowerAscii(std::string s) { for (auto& c : s) if (c >= 'A' && c <= 'Z') c = (char)(c - 'A' + 'a'); return s; } + +std::string Escape(const std::string& s) { + std::string o; + for (unsigned char c : s) { + if (c < 0x20 || c == '%' || c == '=' || c == ']') { char b[4]; std::snprintf(b, sizeof(b), "%%%02X", c); o += b; } + else o += (char)c; + } + return o; +} +std::string Unescape(const std::string& s) { + std::string o; + for (size_t i = 0; i < s.size(); ++i) { + if (s[i] == '%' && i + 2 < s.size() && std::isxdigit((unsigned char)s[i + 1]) && std::isxdigit((unsigned char)s[i + 2])) { + o += (char)std::strtol(s.substr(i + 1, 2).c_str(), nullptr, 16); + i += 2; + } else o += s[i]; + } + return o; +} +std::string Hex(const std::string& d) { std::string o; char b[3]; for (unsigned char c : d) { std::snprintf(b, sizeof(b), "%02x", c); o += b; } return o; } +std::string Unhex(const std::string& h) { std::string o; for (size_t i = 0; i + 1 < h.size(); i += 2) o += (char)std::strtol(h.substr(i, 2).c_str(), nullptr, 16); return o; } +bool IsString(DWORD t) { return t == REG_SZ || t == REG_EXPAND_SZ; } + +struct Store { + std::mutex mu; + std::string file; // "" = memory only + bool readOnly = false, loaded = false; + std::map keys; // by lower-case path "a\b\c"; "" is the root + + void Load() { + if (loaded) return; + loaded = true; + keys[""]; + if (file.empty()) return; + FILE* f = std::fopen(file.c_str(), "r"); + if (!f) return; + std::string cur; + bool have = false; + char line[16384]; + while (std::fgets(line, sizeof(line), f)) { + std::string l = line; + while (!l.empty() && (l.back() == '\n' || l.back() == '\r')) l.pop_back(); + if (l.size() >= 2 && l.front() == '[' && l.back() == ']') { + const std::string path = Unescape(l.substr(1, l.size() - 2)); + have = true; + Make(path); + cur = LowerAscii(path); + } else if (have) { + const size_t eq = l.find('='); + if (eq == std::string::npos || l.size() < eq + 3 || l[eq + 2] != ':') continue; + Value v; + const std::string rawName = l.substr(0, eq), body = l.substr(eq + 3); + v.name = rawName == "@" ? "" : Unescape(rawName); + switch (l[eq + 1]) { + case 's': v.type = REG_SZ; v.data = Unescape(body); break; + case 'e': v.type = REG_EXPAND_SZ; v.data = Unescape(body); break; + case 'd': { v.type = REG_DWORD; const uint32_t n = (uint32_t)std::strtoul(body.c_str(), nullptr, 10); v.data.assign(reinterpret_cast(&n), 4); break; } + case 'q': { v.type = REG_QWORD; const uint64_t n = std::strtoull(body.c_str(), nullptr, 10); v.data.assign(reinterpret_cast(&n), 8); break; } + case 'b': v.type = REG_BINARY; v.data = Unhex(body); break; + case 'm': v.type = REG_MULTI_SZ; v.data = Unhex(body); break; + default: continue; + } + keys[cur].values[LowerAscii(v.name)] = v; + } + } + std::fclose(f); + } + // the key and every key above it + void Make(const std::string& path) { + std::string lower; + size_t i = 0; + while (i <= path.size()) { + size_t j = path.find('\\', i); + if (j == std::string::npos) j = path.size(); + const std::string part = path.substr(i, j - i); + if (!part.empty()) { + lower += (lower.empty() ? "" : "\\") + LowerAscii(part); + Key& k = keys[lower]; + if (k.name.empty()) k.name = part; + } + i = j + 1; + } + } + // True when the file now holds the store (or the store has no file); `err` is the errno of the failure otherwise. + bool Save(int& err) { + err = 0; + if (file.empty() || readOnly) return true; + const size_t cut = file.find_last_of('/'); + if (cut != std::string::npos && cut > 0) { + std::string dir; + for (size_t i = 1; i <= cut; ++i) if (i == cut || file[i] == '/') { dir = file.substr(0, i); mkdir(dir.c_str(), 0777); } + } + const std::string tmp = file + ".write"; + FILE* f = std::fopen(tmp.c_str(), "w"); + if (!f) { err = errno; return false; } + bool ok = true; + auto put = [&](int n) { if (n < 0) ok = false; }; + std::map shown; // lower path -> path as written + for (auto& [lower, k] : keys) { + if (lower.empty()) continue; + const size_t cut2 = lower.rfind('\\'); + shown[lower] = (cut2 == std::string::npos ? std::string() : shown[lower.substr(0, cut2)] + "\\") + k.name; + } + for (auto& [lower, k] : keys) { + if (lower.empty()) { if (k.values.empty()) continue; } + put(std::fprintf(f, "[%s]\n", Escape(lower.empty() ? std::string() : shown[lower]).c_str())); + for (auto& [vl, v] : k.values) { + const std::string n = v.name.empty() ? "@" : Escape(v.name); + switch (v.type) { + case REG_SZ: put(std::fprintf(f, "%s=s:%s\n", n.c_str(), Escape(v.data).c_str())); break; + case REG_EXPAND_SZ: put(std::fprintf(f, "%s=e:%s\n", n.c_str(), Escape(v.data).c_str())); break; + case REG_DWORD: { uint32_t x = 0; std::memcpy(&x, v.data.data(), std::min(4, v.data.size())); put(std::fprintf(f, "%s=d:%u\n", n.c_str(), x)); break; } + case REG_QWORD: { uint64_t x = 0; std::memcpy(&x, v.data.data(), std::min(8, v.data.size())); put(std::fprintf(f, "%s=q:%llu\n", n.c_str(), (unsigned long long)x)); break; } + case REG_MULTI_SZ: put(std::fprintf(f, "%s=m:%s\n", n.c_str(), Hex(v.data).c_str())); break; + default: put(std::fprintf(f, "%s=b:%s\n", n.c_str(), Hex(v.data).c_str())); break; + } + } + } + if (std::fflush(f) != 0 || ferror(f)) ok = false; + if (ok && fsync(fileno(f)) != 0) ok = false; + if (!ok) err = errno ? errno : EIO; + if (std::fclose(f) != 0 && ok) { ok = false; err = errno ? errno : EIO; } + if (ok && std::rename(tmp.c_str(), file.c_str()) != 0) { ok = false; err = errno; } + if (!ok) std::remove(tmp.c_str()); + return ok; + } +}; +// the Windows error for a failed save +DWORD SaveError(int err) { return err == EACCES || err == EPERM || err == EROFS ? ERROR_ACCESS_DENIED : ERROR_WRITE_FAULT; } +// Write the store out; when that fails, put `before` back so memory keeps matching the file, and give the error. +LSTATUS SaveOrUndo(Store* s, std::map& before) { + int err = 0; + if (s->Save(err)) return ERROR_SUCCESS; + s->keys = std::move(before); + return SaveError(err); +} + +std::string UserFile() { + if (const char* e = std::getenv("WRONGGPU_REGISTRY_FILE")) if (*e) return e; +#ifdef WRONGGPU_TESTING + return ""; +#else + return XdgDataHome() + "/WrongGPU/registry.ini"; +#endif +} +// the stores and tables here are never destroyed (see g_handles in win32_posix.cpp) +Store& UserStore() { static Store& s = *new Store; static std::once_flag o; std::call_once(o, [] { s.file = UserFile(); }); return s; } +Store& ReadOnlyStore() { static Store& s = *new Store; static std::once_flag o; std::call_once(o, [] { s.readOnly = true; }); return s; } +std::mutex g_hiveLock; +auto& g_hives = *new std::map>; + +} // namespace + +struct HKEY__ { Store* store; std::string path; REGSAM sam; bool loadedRoot; }; + +namespace { +std::mutex g_keyLock; +auto& g_keys = *new std::unordered_set; + +HKEY NewKey(Store* s, const std::string& path, REGSAM sam, bool root = false) { + HKEY k = new HKEY__{s, path, sam, root}; + std::lock_guard g(g_keyLock); + g_keys.insert(k); + return k; +} +struct Resolved { Store* store = nullptr; std::string path; REGSAM sam = KEY_ALL_ACCESS; }; +bool Resolve(HKEY key, Resolved& r) { + if (key == HKEY_CURRENT_USER) { r.store = &UserStore(); return true; } + if (key == HKEY_LOCAL_MACHINE || key == HKEY_USERS || key == HKEY_CLASSES_ROOT) { r.store = &ReadOnlyStore(); return true; } + std::lock_guard g(g_keyLock); + if (!g_keys.count(key)) return false; + r.store = key->store; r.path = key->path; r.sam = key->sam; + return true; +} +std::string Normalize(LPCWSTR sub) { + std::string out; + if (!sub) return out; + const std::string s = ToUtf8(sub, wcslen(sub)); + size_t i = 0; + while (i <= s.size()) { + size_t j = s.find_first_of("\\/", i); + if (j == std::string::npos) j = s.size(); + if (j > i) out += (out.empty() ? "" : "\\") + s.substr(i, j - i); + i = j + 1; + } + return out; +} +std::string JoinPath(const std::string& base, const std::string& sub) { return base.empty() ? sub : sub.empty() ? base : base + "\\" + sub; } +bool SteamKey(Store* s, const std::string& lowerPath) { return s == &UserStore() && lowerPath == "software\\valve\\steam"; } +// the value at (key, name), the Steam folder included +bool FindValue(Store* s, const std::string& lowerPath, const std::string& name, Value& out) { + auto k = s->keys.find(lowerPath); + if (k != s->keys.end()) { + auto v = k->second.values.find(LowerAscii(name)); + if (v != k->second.values.end()) { out = v->second; return true; } + } + if (SteamKey(s, lowerPath) && LowerAscii(name) == "steampath") { + const std::string root = SteamRoot(); + if (!root.empty()) { out = Value{"SteamPath", REG_SZ, "Z:" + root}; return true; } // Steam writes it with "/" as well + } + return false; +} +std::vector Children(Store* s, const std::string& lowerPath) { + std::vector out; + const std::string prefix = lowerPath.empty() ? std::string() : lowerPath + "\\"; + for (auto& [p, k] : s->keys) { + if (p.size() <= prefix.size() || p.compare(0, prefix.size(), prefix) != 0 || p.find('\\', prefix.size()) != std::string::npos) continue; + out.push_back(k.name); + } + return out; +} +} // namespace + +LSTATUS RegOpenKeyExW(HKEY key, LPCWSTR sub, DWORD, REGSAM sam, PHKEY out) { + Resolved r; + if (!Resolve(key, r)) return ERROR_INVALID_HANDLE; + const std::string path = LowerAscii(JoinPath(r.path, Normalize(sub))); + std::lock_guard g(r.store->mu); + r.store->Load(); + if (!r.store->keys.count(path) && !(SteamKey(r.store, path) && !SteamRoot().empty())) return ERROR_FILE_NOT_FOUND; + if (r.store == &ReadOnlyStore() && !path.empty()) return ERROR_FILE_NOT_FOUND; + *out = NewKey(r.store, path, sam); + return ERROR_SUCCESS; +} +LSTATUS RegCreateKeyExW(HKEY key, LPCWSTR sub, DWORD, LPWSTR, DWORD, REGSAM sam, LPSECURITY_ATTRIBUTES, PHKEY out, LPDWORD disposition) { + Resolved r; + if (!Resolve(key, r)) return ERROR_INVALID_HANDLE; + if (r.store->readOnly || !(r.sam & KEY_CREATE_SUB_KEY)) return ERROR_ACCESS_DENIED; + const std::string shown = JoinPath(r.path, Normalize(sub)), path = LowerAscii(shown); + std::lock_guard g(r.store->mu); + r.store->Load(); + const bool existed = r.store->keys.count(path) != 0; + if (!existed) { + // the key's own spelling for the new parts, the parent's for the rest (parents keep the names they were made with) + std::map before = r.store->keys; + r.store->Make(shown); + const LSTATUS saved = SaveOrUndo(r.store, before); + if (saved != ERROR_SUCCESS) return saved; + } + if (disposition) *disposition = existed ? REG_OPENED_EXISTING_KEY : REG_CREATED_NEW_KEY; + *out = NewKey(r.store, path, sam); + return ERROR_SUCCESS; +} +LSTATUS RegCloseKey(HKEY key) { + if (key == HKEY_CURRENT_USER || key == HKEY_LOCAL_MACHINE || key == HKEY_USERS || key == HKEY_CLASSES_ROOT) return ERROR_SUCCESS; + { + std::lock_guard g(g_keyLock); + if (!g_keys.erase(key)) return ERROR_INVALID_HANDLE; + } + delete key; + return ERROR_SUCCESS; +} +LSTATUS RegQueryValueExW(HKEY key, LPCWSTR name, LPDWORD, LPDWORD type, LPBYTE data, LPDWORD size) { + Resolved r; + if (!Resolve(key, r)) return ERROR_INVALID_HANDLE; + if (!(r.sam & KEY_QUERY_VALUE)) return ERROR_ACCESS_DENIED; + Value v; + { + std::lock_guard g(r.store->mu); + r.store->Load(); + if (!FindValue(r.store, r.path, name ? ToUtf8(name, wcslen(name)) : std::string(), v)) return ERROR_FILE_NOT_FOUND; + } + if (type) *type = v.type; + std::wstring wide; + const char* bytes = v.data.data(); + size_t n = v.data.size(); + if (IsString(v.type)) { wide = FromUtf8(v.data); bytes = reinterpret_cast(wide.c_str()); n = (wide.size() + 1) * sizeof(wchar_t); } + if (!data) { if (size) *size = (DWORD)n; return ERROR_SUCCESS; } + if (!size || *size < n) { if (size) *size = (DWORD)n; return ERROR_MORE_DATA; } + std::memcpy(data, bytes, n); + *size = (DWORD)n; + return ERROR_SUCCESS; +} +LSTATUS RegGetValueW(HKEY key, LPCWSTR sub, LPCWSTR name, DWORD flags, LPDWORD type, PVOID data, LPDWORD size) { + HKEY k = key; + if (sub && *sub) { const LSTATUS s = RegOpenKeyExW(key, sub, 0, KEY_READ, &k); if (s != ERROR_SUCCESS) return s; } + DWORD t = 0, cb = size ? *size : 0; + LSTATUS s = RegQueryValueExW(k, name, nullptr, &t, static_cast(data), size ? &cb : nullptr); + if (sub && *sub) RegCloseKey(k); + if (s != ERROR_SUCCESS && s != ERROR_MORE_DATA) return s; + const bool allowed = (flags & RRF_RT_ANY) == RRF_RT_ANY || ((flags & RRF_RT_REG_SZ) && t == REG_SZ) || ((flags & RRF_RT_REG_DWORD) && t == REG_DWORD); + if (!allowed) return ERROR_UNSUPPORTED_TYPE; + if (type) *type = t; + if (size) *size = cb; + return s; +} +LSTATUS RegSetValueExW(HKEY key, LPCWSTR name, DWORD, DWORD type, const BYTE* data, DWORD size) { + Resolved r; + if (!Resolve(key, r)) return ERROR_INVALID_HANDLE; + if (r.store->readOnly || !(r.sam & KEY_SET_VALUE)) return ERROR_ACCESS_DENIED; + Value v; + v.name = name ? ToUtf8(name, wcslen(name)) : std::string(); + v.type = type; + if (IsString(type)) { + // callers size a string as (length + 1) * 2, the UTF-16 size: that many bytes / 2 = characters of the wide string + const wchar_t* w = reinterpret_cast(data); + size_t n = size / 2, len = 0; + while (len < n && w[len]) ++len; + v.data = ToUtf8(w, len); + } else if (data) { + v.data.assign(reinterpret_cast(data), size); + } + std::lock_guard g(r.store->mu); + r.store->Load(); + std::map before = r.store->keys; + r.store->keys[r.path].values[LowerAscii(v.name)] = v; + return SaveOrUndo(r.store, before); +} +LSTATUS RegDeleteKeyW(HKEY key, LPCWSTR sub) { + Resolved r; + if (!Resolve(key, r)) return ERROR_INVALID_HANDLE; + const std::string path = LowerAscii(JoinPath(r.path, Normalize(sub))); + if (path.empty()) return ERROR_ACCESS_DENIED; + std::lock_guard g(r.store->mu); + r.store->Load(); + if (!r.store->keys.count(path)) return ERROR_FILE_NOT_FOUND; + if (r.store->readOnly) return ERROR_ACCESS_DENIED; + if (!Children(r.store, path).empty()) return ERROR_ACCESS_DENIED; // a key with subkeys stays, as on Windows + std::map before = r.store->keys; + r.store->keys.erase(path); + return SaveOrUndo(r.store, before); +} +LSTATUS RegEnumKeyExW(HKEY key, DWORD index, LPWSTR name, LPDWORD nameLen, LPDWORD, LPWSTR, LPDWORD, FILETIME*) { + Resolved r; + if (!Resolve(key, r)) return ERROR_INVALID_HANDLE; + if (!(r.sam & KEY_ENUMERATE_SUB_KEYS)) return ERROR_ACCESS_DENIED; + std::lock_guard g(r.store->mu); + r.store->Load(); + const std::vector kids = Children(r.store, r.path); + if (index >= kids.size()) return ERROR_NO_MORE_ITEMS; + const std::wstring w = FromUtf8(kids[index]); + if (!nameLen || *nameLen < w.size() + 1) { if (nameLen) *nameLen = (DWORD)w.size() + 1; return ERROR_MORE_DATA; } + std::memcpy(name, w.c_str(), (w.size() + 1) * sizeof(wchar_t)); + *nameLen = (DWORD)w.size(); + return ERROR_SUCCESS; +} +LSTATUS RegLoadAppKeyW(LPCWSTR file, PHKEY out, REGSAM sam, DWORD, DWORD) { + std::string p; + DWORD e = 0; + if (!ToPosix(file, p, e)) return e; + Store* s; + { + std::lock_guard g(g_hiveLock); + auto& slot = g_hives[p]; + if (!slot) { slot.reset(new Store()); slot->file = p; } + s = slot.get(); + } + std::lock_guard g(s->mu); + s->keys.clear(); // what the file holds now, not what an earlier load saw + s->loaded = false; + s->Load(); + int saveErr = 0; + s->Save(saveErr); // an app hive file exists once it is loaded, as on Windows; if it cannot be written, the first write says so + *out = NewKey(s, "", sam, true); + return ERROR_SUCCESS; +} diff --git a/clean/installer/src/platform/posix/win32_posix_rm.cpp b/clean/installer/src/platform/posix/win32_posix_rm.cpp new file mode 100644 index 00000000..fffb5371 --- /dev/null +++ b/clean/installer/src/platform/posix/win32_posix_rm.cpp @@ -0,0 +1,238 @@ +// SPDX-License-Identifier: MIT +// Linux: the Restart Manager's list of processes that hold files (restartmanager.h has what it sees and what it cannot). +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "win32_posix_internal.h" + +using namespace wgposix; + +namespace { +std::mutex g_rmLock; +DWORD g_nextSession = 1; +auto& g_sessions = *new std::map>; // session: the files registered (POSIX paths) + +bool Numeric(const char* s) { + if (!*s) return false; + for (; *s; ++s) if (*s < '0' || *s > '9') return false; + return true; +} +std::string ReadSmall(const std::string& path) { + std::ifstream f(path, std::ios::binary); + std::ostringstream o; + o << f.rdbuf(); + return o.str(); +} +// The program's file name: the first word of its command line (a Wine process shows its Windows program there), else comm. +std::wstring AppName(const std::string& pid) { + std::string cmd = ReadSmall("/proc/" + pid + "/cmdline"); + cmd = cmd.substr(0, cmd.find('\0')); + const size_t cut = cmd.find_last_of("/\\"); + if (cut != std::string::npos) cmd.erase(0, cut + 1); + if (cmd.empty()) { + cmd = ReadSmall("/proc/" + pid + "/comm"); + while (!cmd.empty() && cmd.back() == '\n') cmd.pop_back(); + } + return FromUtf8(cmd); +} +// The process's start as a FILETIME: boot time (/proc/stat btime) plus its start in clock ticks (/proc//stat field 22). +FILETIME StartTime(const std::string& pid) { + FILETIME ft{}; + const std::string st = ReadSmall("/proc/" + pid + "/stat"); + const size_t close = st.rfind(')'); // the name in parentheses may hold spaces + if (close == std::string::npos) return ft; + std::istringstream rest(st.substr(close + 2)); + std::string field; + unsigned long long ticks = 0; + for (int i = 3; i <= 22 && rest >> field; ++i) if (i == 22) ticks = std::strtoull(field.c_str(), nullptr, 10); + std::istringstream sys(ReadSmall("/proc/stat")); + std::string line; + unsigned long long boot = 0; + while (std::getline(sys, line)) if (line.rfind("btime ", 0) == 0) boot = std::strtoull(line.c_str() + 6, nullptr, 10); + const long hz = sysconf(_SC_CLK_TCK); + if (!boot || hz <= 0) return ft; + struct timespec t; + t.tv_sec = (time_t)(boot + ticks / (unsigned long long)hz); + t.tv_nsec = (long)((ticks % (unsigned long long)hz) * (1000000000ull / (unsigned long long)hz)); + return FileTimeOf(t); +} +typedef std::set> Ids; +bool Wanted(const Ids& ids, const struct stat& st) { return ids.count({st.st_dev, st.st_ino}) != 0; } +// The process's real user (status "Uid:"; /proc/ itself shows root for a process that is not dumpable); -1: gone. +long long RealUid(const std::string& base) { + std::istringstream st(ReadSmall(base + "/status")); + std::string line; + while (std::getline(st, line)) if (line.rfind("Uid:", 0) == 0) return std::strtoll(line.c_str() + 4, nullptr, 10); + return -1; +} +// Does the process have one of the files mapped? 1, 0; -1 its maps cannot be read; -2 it ended. A maps line is "address perms +// offset major:minor inode path"; the device there is the superblock's (on btrfs not what stat() says), so a line whose inode +// matches is confirmed by a stat() of its path as the process sees it (/proc//root: a game in a container sees other paths). +int ScanMaps(const std::string& base, const Ids& ids) { + FILE* maps = std::fopen((base + "/maps").c_str(), "re"); + if (!maps) return errno == ENOENT ? -2 : -1; + std::set inodes; + for (auto& id : ids) inodes.insert(id.second); + char* buf = nullptr; + size_t cap = 0; + bool found = false; + while (!found && getline(&buf, &cap, maps) > 0) { + std::istringstream l(buf); + std::string addr, perms, offset, dev, path; + unsigned long long inode = 0; + if (!(l >> addr >> perms >> offset >> dev >> inode) || !inode || !inodes.count((ino_t)inode)) continue; + std::getline(l >> std::ws, path); + struct stat st; + found = !path.empty() && path[0] == '/' && + ((stat((base + "/root" + path).c_str(), &st) == 0 && Wanted(ids, st)) || (stat(path.c_str(), &st) == 0 && Wanted(ids, st))); + } + std::free(buf); + std::fclose(maps); + return found ? 1 : 0; +} +// A Windows program under Wine, or Wine itself: Wine sets the first word of the command line to the Windows path of the +// program (C:\..., Z:\...); wineserver and the preloader are named wine*. Anything else does not load Windows images. +bool WineProgram(const std::string& base) { + std::string cmd = ReadSmall(base + "/cmdline"); + cmd = cmd.substr(0, cmd.find('\0')); + if (cmd.find('\\') != std::string::npos) return true; + const size_t cut = cmd.find_last_of('/'); + std::string name = cut == std::string::npos ? cmd : cmd.substr(cut + 1); + for (auto& c : name) c = (char)std::tolower((unsigned char)c); + return (name.size() > 4 && name.compare(name.size() - 4, 4, ".exe") == 0) || name.rfind("wine", 0) == 0; +} +} // namespace + +int wgposix::ImageInUse(dev_t dev, ino_t ino, int* who) { + const Ids ids{{dev, ino}}; + DIR* proc = opendir("/proc"); + if (!proc) return -1; + int result = 0; + while (dirent* e = readdir(proc)) { + if (!Numeric(e->d_name)) continue; + const int pid = std::atoi(e->d_name); + const std::string base = std::string("/proc/") + e->d_name; + if (pid == (int)getpid() || RealUid(base) != (long long)getuid() || !WineProgram(base)) continue; + const int r = ScanMaps(base, ids); + if (r == 1) { + result = 1; + if (who) *who = pid; + break; + } + if (r == -1 && result == 0) { + result = -1; + if (who) *who = pid; + } + } + closedir(proc); + return result; +} + +// Does process `pid` hold one of the files (1, 0)? -1: a process of this user that could not be read (its fd or maps +// closed: not dumpable, or holding capabilities); -2: another user's (not looked at: closed to this user on any Linux) or gone. +int wgposix::RmScanProcess(int pidNum, const std::vector>& wanted) { + const Ids ids(wanted.begin(), wanted.end()); + const std::string pid = std::to_string(pidNum), base = "/proc/" + pid; + if (RealUid(base) != (long long)getuid()) return -2; + DIR* d = opendir((base + "/fd").c_str()); + if (!d) return errno == ENOENT ? -2 : -1; // ENOENT: it ended meanwhile + bool found = false; + while (dirent* e = readdir(d)) { + if (!Numeric(e->d_name)) continue; + struct stat st; + if (stat((base + "/fd/" + e->d_name).c_str(), &st) == 0 && Wanted(ids, st)) { found = true; break; } + } + closedir(d); + return found ? 1 : ScanMaps(base, ids); +} + +DWORD RmStartSession(DWORD* session, DWORD flags, WCHAR key[]) { + if (!session || flags) return ERROR_INVALID_PARAMETER; + std::lock_guard g(g_rmLock); + *session = g_nextSession++; + g_sessions[*session]; + if (key) { + const std::string k = std::to_string(getpid()) + "-" + std::to_string(*session); + size_t i = 0; + for (; i < k.size() && i < CCH_RM_SESSION_KEY; ++i) key[i] = (WCHAR)k[i]; + key[i] = 0; + } + return ERROR_SUCCESS; +} + +DWORD RmRegisterResources(DWORD session, UINT nFiles, LPCWSTR files[], UINT nApplications, RM_UNIQUE_PROCESS[], UINT nServices, LPCWSTR[]) { + if (nApplications || nServices) return ERROR_NOT_SUPPORTED; + std::vector paths; + for (UINT i = 0; i < nFiles; ++i) { + std::string p; + if (!files || !files[i] || !ToPosix(files[i], p)) return ERROR_INVALID_PARAMETER; + paths.push_back(p); + } + std::lock_guard g(g_rmLock); + auto it = g_sessions.find(session); + if (it == g_sessions.end()) return ERROR_INVALID_HANDLE; + it->second.insert(it->second.end(), paths.begin(), paths.end()); + return ERROR_SUCCESS; +} + +DWORD RmGetList(DWORD session, UINT* needed, UINT* count, RM_PROCESS_INFO info[], LPDWORD reasons) { + if (!needed || !count || !reasons || (*count && !info)) return ERROR_INVALID_PARAMETER; + std::vector paths; + { + std::lock_guard g(g_rmLock); + auto it = g_sessions.find(session); + if (it == g_sessions.end()) return ERROR_INVALID_HANDLE; + paths = it->second; + } + Ids ids; + for (auto& p : paths) { + struct stat st; + if (stat(p.c_str(), &st) == 0) ids.insert({st.st_dev, st.st_ino}); // a file that is not there: nobody holds it + } + *reasons = RmRebootReasonNone; + std::vector holders; + if (!ids.empty()) { + DIR* proc = opendir("/proc"); + if (!proc) return ERROR_ACCESS_DENIED; + const std::vector> wanted(ids.begin(), ids.end()); + bool denied = false; + while (dirent* e = readdir(proc)) { + if (!Numeric(e->d_name)) continue; + const int r = RmScanProcess(std::atoi(e->d_name), wanted); + if (r == 1) holders.push_back(e->d_name); + denied = denied || r == -1; + } + closedir(proc); + if (denied) *reasons |= RmRebootReasonPermissionDenied; + } + *needed = (UINT)holders.size(); + if (*count < holders.size()) return ERROR_MORE_DATA; + *count = (UINT)holders.size(); + for (size_t i = 0; i < holders.size(); ++i) { + RM_PROCESS_INFO& r = info[i]; + std::memset(&r, 0, sizeof r); + r.Process.dwProcessId = (DWORD)std::strtoul(holders[i].c_str(), nullptr, 10); + r.Process.ProcessStartTime = StartTime(holders[i]); + const std::wstring app = AppName(holders[i]); + wcsncpy(r.strAppName, app.c_str(), CCH_RM_MAX_APP_NAME); + r.ApplicationType = RmUnknownApp; + r.bRestartable = FALSE; + } + return ERROR_SUCCESS; +} + +DWORD RmEndSession(DWORD session) { + std::lock_guard g(g_rmLock); + return g_sessions.erase(session) ? ERROR_SUCCESS : ERROR_INVALID_HANDLE; +} diff --git a/clean/installer/src/platform/posix/win32_posix_sync.cpp b/clean/installer/src/platform/posix/win32_posix_sync.cpp new file mode 100644 index 00000000..453af53d --- /dev/null +++ b/clean/installer/src/platform/posix/win32_posix_sync.cpp @@ -0,0 +1,225 @@ +// SPDX-License-Identifier: MIT +// Linux: named mutexes and unnamed events (the design is in win32_posix.h, "synchronization"). +// +// Why open file description locks: they are dropped by the kernel when the last descriptor of the open file goes, a +// process's end included (a crashed owner never keeps the lock), they lock byte ranges (one file carries "exists" and +// "owned"), and turning the creator's write lock into a read lock is atomic (flock's conversion is not). A POSIX named +// semaphore has a timed wait but stays taken when its owner dies, so a crash would leave the game's state locked. +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "win32_posix_internal.h" + +using namespace wgposix; + +namespace { +constexpr off_t kExistsByte = 0, kOwnerByte = 1; +// The file's first byte: kOwned from the wait that takes the mutex to the ReleaseMutex that gives it back, so whoever takes +// it after an owner that ended without releasing it sees that (WAIT_ABANDONED). Locks are advisory: the locked bytes and the +// content are independent. +constexpr char kOwned = 'O', kFree = '-'; + +// 0, or the errno (EAGAIN: someone else holds a conflicting lock) +int SetLock(int fd, short type, off_t byte, bool wait) { + struct flock l{}; + l.l_type = type; + l.l_whence = SEEK_SET; + l.l_start = byte; + l.l_len = 1; + int r; + do r = fcntl(fd, wait ? F_OFD_SETLKW : F_OFD_SETLK, &l); while (r != 0 && errno == EINTR); + return r == 0 ? 0 : (errno == EACCES ? EAGAIN : errno); +} + +// What this process knows of one mutex object (its lock file's identity): the owning thread and its count, a thread busy +// taking it, the descriptor that holds the owner byte (a dup, so the lock outlives the handle it was taken through, as +// ownership does on Windows), and how many handles of it are open here. +struct State { + std::thread::id thread; + unsigned count = 0; + bool taking = false; + int fd = -1; + unsigned handles = 0; +}; +std::mutex g_lock; +std::condition_variable g_changed; // an owner released, a take ended, an event was set +auto& g_mutexes = *new std::map, State>; // never destroyed (handles may close during exit) + +// The lock file of a name: Local\X is X (as in a desktop session); Global\X keeps its prefix (another object, as on Windows). +bool LockPath(const wchar_t* name, std::string& out, DWORD& err) { + std::wstring n = name; + if (n.rfind(L"Local\\", 0) == 0) n.erase(0, 6); + std::string enc; + for (unsigned char c : ToUtf8(n)) { + if (isalnum(c) || c == '.' || c == '-' || c == '_') { + enc += (char)c; + } else { + char b[4]; + std::snprintf(b, sizeof b, "%%%02X", c); + enc += b; + } + } + if (enc.empty() || enc.size() > 200) { err = ERROR_INVALID_NAME; return false; } + std::string dir; + if (const char* r = getenv("XDG_RUNTIME_DIR"); r && *r && access(r, W_OK) == 0) dir = r; + else dir = XdgDataHome(); + mkdir(dir.c_str(), 0700); + out = dir + "/wronggpu-mutex-" + enc + ".lock"; + return true; +} + +HANDLE OpenNamed(LPCWSTR name, bool create, bool initialOwner) { + if (!name || !*name) { SetLastError(ERROR_NOT_SUPPORTED); return nullptr; } + std::string path; + DWORD err = 0; + if (!LockPath(name, path, err)) { SetLastError(err); return nullptr; } + const int fd = open(path.c_str(), O_RDWR | O_CLOEXEC | (create ? O_CREAT : 0), 0600); + if (fd < 0) { + SetLastError(errno == ENOENT ? ERROR_FILE_NOT_FOUND : ErrorFromErrno(errno, path)); + return nullptr; + } + struct stat st; + if (fstat(fd, &st) != 0) { SetErrorFromErrno(errno, path); close(fd); return nullptr; } + bool existed = true; + int e = SetLock(fd, F_WRLCK, kExistsByte, false); + if (e == 0) { // no other handle anywhere: a new object, not owned whatever an earlier one left in the file + if (!create) { close(fd); SetLastError(ERROR_FILE_NOT_FOUND); return nullptr; } + existed = false; + if (pwrite(fd, &kFree, 1, 0) != 1) e = errno; + if (!e) e = SetLock(fd, F_RDLCK, kExistsByte, false); // the write lock becomes a read lock at once + } else if (e == EAGAIN) { + e = SetLock(fd, F_RDLCK, kExistsByte, true); // waits only while a creator holds its write lock for a moment + } + if (e) { // a file system without these locks (ENOLCK, EINVAL) or another failure + close(fd); + SetLastError(e == ENOLCK || e == EINVAL ? ERROR_NOT_SUPPORTED : ErrorFromErrno(e, path)); + return nullptr; + } + Handle* h = NewHandle(Kind::Mutex); + h->fd = fd; + h->dev = st.st_dev; + h->ino = st.st_ino; + { + std::lock_guard g(g_lock); + ++g_mutexes[{st.st_dev, st.st_ino}].handles; + } + if (initialOwner && !existed) WaitMutex(h, 0); // Windows: the creator owns it; whoever opened it meanwhile could own it first + SetLastError(existed && create ? ERROR_ALREADY_EXISTS : 0); + return h; +} +} // namespace + +DWORD wgposix::WaitMutex(Handle* h, DWORD ms) { + using clock = std::chrono::steady_clock; + const clock::time_point deadline = ms == INFINITE ? clock::time_point::max() : clock::now() + std::chrono::milliseconds(ms); + const std::thread::id me = std::this_thread::get_id(); + std::unique_lock g(g_lock); + State& s = g_mutexes[{h->dev, h->ino}]; + if (s.count && s.thread == me) { ++s.count; return WAIT_OBJECT_0; } // recursive for its owner + while (s.count || s.taking) { // another thread of this process owns it or is taking it + if (ms == INFINITE) g_changed.wait(g); + else if (g_changed.wait_until(g, deadline) == std::cv_status::timeout && (s.count || s.taking)) return WAIT_TIMEOUT; + } + s.taking = true; + g.unlock(); + const int fd = fcntl(h->fd, F_DUPFD_CLOEXEC, 0); + int err = fd < 0 ? errno : 0; + bool got = false; + for (unsigned pause = 1; !err;) { // between processes: polled, so the timeout holds + const int e = SetLock(fd, F_WRLCK, kOwnerByte, false); + if (e == 0) { got = true; break; } + if (e != EAGAIN) { err = e; break; } + const clock::time_point now = clock::now(); + if (now >= deadline) break; + const auto left = std::chrono::duration_cast(deadline - now).count(); + std::this_thread::sleep_for(std::chrono::milliseconds(std::min(pause, std::max(left, 1)))); + pause = std::min(pause * 2, 20u); + } + bool abandoned = false; + if (got) { + char mark = kFree; + abandoned = pread(fd, &mark, 1, 0) == 1 && mark == kOwned; + if (pwrite(fd, &kOwned, 1, 0) != 1) { err = errno; got = false; SetLock(fd, F_UNLCK, kOwnerByte, false); } + } + g.lock(); + s.taking = false; + if (!got) { + if (fd >= 0) close(fd); + g_changed.notify_all(); + if (err) { SetLastError(ErrorFromErrno(err, "")); return WAIT_FAILED; } + return WAIT_TIMEOUT; + } + s.thread = me; + s.count = 1; + s.fd = fd; + return abandoned ? WAIT_ABANDONED : WAIT_OBJECT_0; +} + +void wgposix::CloseMutex(Handle* h) { + std::lock_guard g(g_lock); + auto it = g_mutexes.find({h->dev, h->ino}); + if (it == g_mutexes.end() || --it->second.handles) return; + // the last handle here: the object ends for this process (on Windows it is destroyed); an owner's lock goes with it, and + // the file still says "owned", so a taker elsewhere that kept it alive sees it abandoned + if (it->second.fd >= 0) close(it->second.fd); + g_mutexes.erase(it); + g_changed.notify_all(); +} + +HANDLE CreateMutexW(LPSECURITY_ATTRIBUTES, BOOL initialOwner, LPCWSTR name) { return OpenNamed(name, true, initialOwner != FALSE); } +HANDLE OpenMutexW(DWORD, BOOL, LPCWSTR name) { return OpenNamed(name, false, false); } + +BOOL ReleaseMutex(HANDLE hv) { + Handle* h = Lookup(hv, Kind::Mutex); + if (!h) return FALSE; + std::lock_guard g(g_lock); + auto it = g_mutexes.find({h->dev, h->ino}); + if (it == g_mutexes.end() || !it->second.count || it->second.thread != std::this_thread::get_id()) return Fail(ERROR_NOT_OWNER); + State& s = it->second; + if (--s.count) return TRUE; + // "free" before the lock goes, so the next owner never reads a released mutex as abandoned + if (pwrite(s.fd, &kFree, 1, 0) != 1) { ++s.count; SetErrorFromErrno(errno, ""); return FALSE; } + SetLock(s.fd, F_UNLCK, kOwnerByte, false); + close(s.fd); + s.fd = -1; + g_changed.notify_all(); + return TRUE; +} + +// ---- events ------------------------------------------------------------------------------------------------------------- +HANDLE CreateEventW(LPSECURITY_ATTRIBUTES, BOOL manualReset, BOOL initialState, LPCWSTR name) { + if (name && *name) { SetLastError(ERROR_NOT_SUPPORTED); return nullptr; } + Handle* h = NewHandle(Kind::Event); + h->manualReset = manualReset != FALSE; + h->signaled = initialState != FALSE; + SetLastError(0); + return h; +} +BOOL SetEvent(HANDLE hv) { + Handle* h = Lookup(hv, Kind::Event); + if (!h) return FALSE; + std::lock_guard g(g_lock); + h->signaled = true; + g_changed.notify_all(); + return TRUE; +} +DWORD wgposix::WaitEvent(Handle* h, DWORD ms) { + using clock = std::chrono::steady_clock; + const clock::time_point deadline = ms == INFINITE ? clock::time_point::max() : clock::now() + std::chrono::milliseconds(ms); + std::unique_lock g(g_lock); + while (!h->signaled) { + if (ms == INFINITE) g_changed.wait(g); + else if (g_changed.wait_until(g, deadline) == std::cv_status::timeout && !h->signaled) return WAIT_TIMEOUT; + } + if (!h->manualReset) h->signaled = false; // an auto-reset event lets one waiter through + return WAIT_OBJECT_0; +} diff --git a/clean/installer/src/platform/posix/win32_window.h b/clean/installer/src/platform/posix/win32_window.h new file mode 100644 index 00000000..03e083ae --- /dev/null +++ b/clean/installer/src/platform/posix/win32_window.h @@ -0,0 +1,313 @@ +// SPDX-License-Identifier: MIT +// Linux: the Win32 window calls the launcher's window makes (CreateWindowExW, the message loop, timers, painting requests, +// focus and capture, cursors, the clipboard, the "EDIT" control) declared the way Windows declares them and implemented on SDL3 +// in win32_window_sdl.cpp and win32_window_edit.cpp, so launcher_ui.cpp's WndProc compiles unchanged. A call the layer lacks fails +// the Linux build at that line, as in win32_posix.h. +// +// Conventions: +// - Coordinates and sizes are device pixels, as Win32's are for a DPI-aware window. A window's DPI is 96 times SDL's display +// scale for it; the client area is the whole SDL window (there is no system caption: the app's toolbar is its title bar). +// - One UI thread. PostMessageW (and the timers' wake-up) may come from any thread; every other call is the UI thread's. +// - The system caption's behaviour comes from WM_NCHITTEST, which the layer asks the window procedure for: HTCAPTION moves the +// window, the HT*border codes resize it (SDL_SetWindowHitTest), and the caption buttons arrive as WM_NC* messages. +#pragma once +#include +#include + +#include "win32_posix.h" + +// ---- types ------------------------------------------------------------------------------------------------------------- +typedef uintptr_t WPARAM; +typedef intptr_t LPARAM; +typedef intptr_t LRESULT; +typedef uintptr_t UINT_PTR; +typedef intptr_t LONG_PTR; +typedef uint32_t COLORREF; +typedef HANDLE HMENU; +typedef HANDLE HICON; +typedef HANDLE HCURSOR; +typedef HANDLE HFONT; +typedef HANDLE HBRUSH; +typedef HANDLE HBITMAP; +typedef HANDLE HDC; +typedef HANDLE HGDIOBJ; +typedef HANDLE HMONITOR; +typedef void(CALLBACK* TIMERPROC)(HWND, UINT, UINT_PTR, DWORD); +typedef LRESULT(CALLBACK* WNDPROC)(HWND, UINT, WPARAM, LPARAM); +typedef LRESULT(CALLBACK* SUBCLASSPROC)(HWND, UINT, WPARAM, LPARAM, UINT_PTR, DWORD_PTR); +typedef struct tagPOINT { LONG x, y; } POINT, *LPPOINT; +typedef struct tagRECT { LONG left, top, right, bottom; } RECT, *LPRECT; +typedef struct tagSIZE { LONG cx, cy; } SIZE; +typedef struct tagMSG { HWND hwnd; UINT message; WPARAM wParam; LPARAM lParam; DWORD time; POINT pt; } MSG, *LPMSG; +typedef struct tagWNDCLASSEXW { + UINT cbSize, style; WNDPROC lpfnWndProc; int cbClsExtra, cbWndExtra; HINSTANCE hInstance; HICON hIcon; HCURSOR hCursor; HBRUSH hbrBackground; + LPCWSTR lpszMenuName, lpszClassName; HICON hIconSm; +} WNDCLASSEXW; +typedef struct tagMINMAXINFO { POINT ptReserved, ptMaxSize, ptMaxPosition, ptMinTrackSize, ptMaxTrackSize; } MINMAXINFO; +typedef struct tagWINDOWPOS { HWND hwnd, hwndInsertAfter; int x, y, cx, cy; UINT flags; } WINDOWPOS; +typedef struct tagNCCALCSIZE_PARAMS { RECT rgrc[3]; WINDOWPOS* lppos; } NCCALCSIZE_PARAMS; +typedef struct tagWINDOWPLACEMENT { UINT length, flags, showCmd; POINT ptMinPosition, ptMaxPosition; RECT rcNormalPosition; } WINDOWPLACEMENT; +typedef struct tagMONITORINFO { DWORD cbSize; RECT rcMonitor, rcWork; DWORD dwFlags; } MONITORINFO; +typedef struct tagPAINTSTRUCT { HDC hdc; BOOL fErase; RECT rcPaint; BOOL fRestore, fIncUpdate; BYTE rgbReserved[32]; } PAINTSTRUCT; +typedef struct tagTRACKMOUSEEVENT { DWORD cbSize, dwFlags; HWND hwndTrack; DWORD dwHoverTime; } TRACKMOUSEEVENT; +typedef struct tagTITLEBARINFOEX { DWORD cbSize; RECT rcTitleBar; DWORD rgstate[6]; RECT rgrect[6]; } TITLEBARINFOEX; +typedef struct tagHIGHCONTRASTW { UINT cbSize; DWORD dwFlags; LPWSTR lpszDefaultScheme; } HIGHCONTRASTW; +typedef struct tagTEXTMETRICW { LONG tmHeight, tmAscent, tmDescent, tmInternalLeading, tmExternalLeading, tmAveCharWidth; } TEXTMETRICW; +#define LF_FACESIZE 32 +typedef struct tagLOGFONTW { LONG lfHeight, lfWidth, lfEscapement, lfOrientation, lfWeight; BYTE lfItalic, lfUnderline, lfStrikeOut, lfCharSet, lfOutPrecision, lfClipPrecision, lfQuality, lfPitchAndFamily; WCHAR lfFaceName[LF_FACESIZE]; } LOGFONTW; +typedef struct tagINITCOMMONCONTROLSEX { DWORD dwSize, dwICC; } INITCOMMONCONTROLSEX; + +#define CCHILDREN_TITLEBAR 5 +#define STATE_SYSTEM_INVISIBLE 0x8000 +#define ENDSESSION_CRITICAL 0x40000000 +#define RGB(r, g, b) ((COLORREF)(((BYTE)(r)) | ((WORD)((BYTE)(g)) << 8) | (((DWORD)(BYTE)(b)) << 16))) +#define GetRValue(c) ((BYTE)((c) & 0xff)) +#define GetGValue(c) ((BYTE)(((c) >> 8) & 0xff)) +#define GetBValue(c) ((BYTE)(((c) >> 16) & 0xff)) +#define MAKELPARAM(l, h) ((LPARAM)(DWORD)MAKELONG(l, h)) +#define MAKEWPARAM(l, h) ((WPARAM)(DWORD)MAKELONG(l, h)) +#define GET_X_LPARAM(lp) ((int)(short)LOWORD(lp)) +#define GET_Y_LPARAM(lp) ((int)(short)HIWORD(lp)) +#define GET_WHEEL_DELTA_WPARAM(wp) ((short)HIWORD(wp)) +#define GET_XBUTTON_WPARAM(wp) (HIWORD(wp)) +#define GET_KEYSTATE_WPARAM(wp) (LOWORD(wp)) +constexpr int WHEEL_DELTA = 120; +constexpr UINT WHEEL_PAGESCROLL = 0xFFFFFFFFu; +constexpr int XBUTTON1 = 1, XBUTTON2 = 2; +#define MAKEINTRESOURCE MAKEINTRESOURCEW +#define GET_APPCOMMAND_LPARAM(lp) ((short)(HIWORD(lp) & ~0xF000)) +constexpr int APPCOMMAND_BROWSER_BACKWARD = 1; +constexpr UINT MB_OK = 0; + +// ---- messages ---------------------------------------------------------------------------------------------------------- +constexpr UINT WM_NULL = 0x0000, WM_CREATE = 0x0001, WM_DESTROY = 0x0002, WM_MOVE = 0x0003, WM_SIZE = 0x0005, WM_ACTIVATE = 0x0006, + WM_SETFOCUS = 0x0007, WM_KILLFOCUS = 0x0008, WM_SETREDRAW = 0x000B, WM_SETTEXT = 0x000C, WM_GETTEXT = 0x000D, + WM_GETTEXTLENGTH = 0x000E, WM_PAINT = 0x000F, WM_CLOSE = 0x0010, WM_QUERYENDSESSION = 0x0011, WM_QUIT = 0x0012, + WM_ERASEBKGND = 0x0014, WM_SYSCOLORCHANGE = 0x0015, WM_ENDSESSION = 0x0016, WM_SHOWWINDOW = 0x0018, + WM_SETTINGCHANGE = 0x001A, WM_SETCURSOR = 0x0020, WM_GETMINMAXINFO = 0x0024, WM_SETFONT = 0x0030, WM_GETFONT = 0x0031, + WM_GETOBJECT = 0x003D, WM_NCCREATE = 0x0081, WM_NCDESTROY = 0x0082, WM_NCCALCSIZE = 0x0083, WM_NCHITTEST = 0x0084, + WM_NCACTIVATE = 0x0086, WM_GETDLGCODE = 0x0087, WM_NCMOUSEMOVE = 0x00A0, WM_NCLBUTTONDOWN = 0x00A1, + WM_NCLBUTTONUP = 0x00A2, WM_NCLBUTTONDBLCLK = 0x00A3, WM_KEYDOWN = 0x0100, WM_KEYUP = 0x0101, WM_CHAR = 0x0102, + WM_SYSKEYDOWN = 0x0104, WM_SYSKEYUP = 0x0105, WM_COMMAND = 0x0111, WM_SYSCOMMAND = 0x0112, WM_TIMER = 0x0113, + WM_CTLCOLOREDIT = 0x0133, WM_MOUSEMOVE = 0x0200, WM_LBUTTONDOWN = 0x0201, WM_LBUTTONUP = 0x0202, + WM_LBUTTONDBLCLK = 0x0203, WM_RBUTTONDOWN = 0x0204, WM_RBUTTONUP = 0x0205, WM_MBUTTONDOWN = 0x0207, + WM_MBUTTONUP = 0x0208, WM_MOUSEWHEEL = 0x020A, WM_XBUTTONDOWN = 0x020B, WM_XBUTTONUP = 0x020C, + WM_CAPTURECHANGED = 0x0215, WM_DPICHANGED = 0x02E0, WM_CUT = 0x0300, WM_COPY = 0x0301, WM_PASTE = 0x0302, + WM_CLEAR = 0x0303, WM_UNDO = 0x0304, WM_DWMCOLORIZATIONCOLORCHANGED = 0x0320, WM_GETTITLEBARINFOEX = 0x033F, + WM_APPCOMMAND = 0x0319, WM_APP = 0x8000, WM_SETICON = 0x0080, WM_MOUSELEAVE = 0x02A3, WM_NCMOUSELEAVE = 0x02A2; +constexpr UINT EM_GETSEL = 0x00B0, EM_SETSEL = 0x00B1, EM_GETRECT = 0x00B2, EM_REPLACESEL = 0x00C2, EM_UNDO = 0x00C7, EM_SETMARGINS = 0x00D3, + EM_SETCUEBANNER = 0x1501, EM_GETCUEBANNER = 0x1502; +constexpr UINT EN_SETFOCUS = 0x0100, EN_KILLFOCUS = 0x0200, EN_CHANGE = 0x0300; +constexpr UINT EC_LEFTMARGIN = 1, EC_RIGHTMARGIN = 2; +constexpr UINT DLGC_WANTARROWS = 1, DLGC_WANTCHARS = 0x80, DLGC_HASSETSEL = 0x08; +constexpr UINT WA_INACTIVE = 0, WA_ACTIVE = 1, WA_CLICKACTIVE = 2; +constexpr UINT SIZE_RESTORED = 0, SIZE_MINIMIZED = 1, SIZE_MAXIMIZED = 2; +constexpr UINT SC_KEYMENU = 0xF100, SC_CLOSE = 0xF060, SC_MINIMIZE = 0xF020, SC_MAXIMIZE = 0xF030, SC_RESTORE = 0xF120; +constexpr UINT ICON_SMALL = 0, ICON_BIG = 1; +constexpr UINT MK_LBUTTON = 1, MK_RBUTTON = 2, MK_SHIFT = 4, MK_CONTROL = 8, MK_MBUTTON = 0x10; +constexpr UINT TME_LEAVE = 2, TME_NONCLIENT = 0x10; +constexpr UINT PM_NOREMOVE = 0, PM_REMOVE = 1; +constexpr UINT QS_ALLINPUT = 0x04FF; +constexpr UINT CS_DBLCLKS = 0x0008; +constexpr UINT ICC_WIN95_CLASSES = 0xFF; +constexpr UINT TTM_SETMAXTIPWIDTH = 0x0418; // (tooltips are not built on Linux: the window's code names this one) + +// hit-test codes (WM_NCHITTEST's result) +constexpr LRESULT HTERROR = -2, HTTRANSPARENT = -1, HTNOWHERE = 0, HTCLIENT = 1, HTCAPTION = 2, HTMINBUTTON = 8, HTMAXBUTTON = 9, HTLEFT = 10, + HTRIGHT = 11, HTTOP = 12, HTTOPLEFT = 13, HTTOPRIGHT = 14, HTBOTTOM = 15, HTBOTTOMLEFT = 16, HTBOTTOMRIGHT = 17, HTCLOSE = 20; + +// ---- window styles, show commands, positions ----------------------------------------------------------------------------- +constexpr DWORD WS_OVERLAPPED = 0, WS_POPUP = 0x80000000u, WS_CHILD = 0x40000000, WS_CLIPCHILDREN = 0x02000000, WS_VISIBLE = 0x10000000, + WS_TABSTOP = 0x00010000, WS_CAPTION = 0x00C00000, WS_SYSMENU = 0x00080000, WS_THICKFRAME = 0x00040000, + WS_MINIMIZEBOX = 0x00020000, WS_MAXIMIZEBOX = 0x00010000, + WS_OVERLAPPEDWINDOW = WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX; +constexpr DWORD WS_EX_TOPMOST = 0x8; +constexpr DWORD ES_AUTOHSCROLL = 0x80; +constexpr int CW_USEDEFAULT = (int)0x80000000; +#define HWND_MESSAGE ((HWND)(intptr_t)-3) +constexpr int SW_RESTORE = 9, SW_SHOWMINIMIZED = 2, SW_SHOWMAXIMIZED = 3, SW_SHOWNA = 8, SW_MINIMIZE = 6, SW_FORCEMINIMIZE = 11, SW_MAXIMIZE = 3; +constexpr UINT SWP_NOSIZE = 1, SWP_NOMOVE = 2, SWP_NOZORDER = 4, SWP_NOREDRAW = 8, SWP_NOACTIVATE = 0x10, SWP_FRAMECHANGED = 0x20, + SWP_NOCOPYBITS = 0x100; +constexpr UINT RDW_INVALIDATE = 1, RDW_ERASE = 4, RDW_FRAME = 0x400, RDW_UPDATENOW = 0x100; +constexpr UINT WPF_RESTORETOMAXIMIZED = 2; +constexpr DWORD MONITOR_DEFAULTTONULL = 0, MONITOR_DEFAULTTOPRIMARY = 1, MONITOR_DEFAULTTONEAREST = 2; +constexpr int SM_CXSCREEN = 0, SM_CYSCREEN = 1, SM_CXFRAME = 32, SM_CYFRAME = 33, SM_CXICON = 11, SM_CYICON = 12, SM_CXSMICON = 49, SM_CYSMICON = 50, + SM_CXPADDEDBORDER = 92; +constexpr UINT SPI_GETHIGHCONTRAST = 0x42, SPI_GETWHEELSCROLLLINES = 0x68, SPI_SETHIGHCONTRAST = 0x43, SPI_GETCLIENTAREAANIMATION = 0x1042, + SPI_GETMESSAGEDURATION = 0x2016; +constexpr DWORD HCF_HIGHCONTRASTON = 1; +constexpr int GWLP_ID = -12, GWLP_USERDATA = -21; +constexpr int COLOR_WINDOW = 5, COLOR_WINDOWTEXT = 8, COLOR_HIGHLIGHT = 13, COLOR_HIGHLIGHTTEXT = 14, COLOR_GRAYTEXT = 17, COLOR_HOTLIGHT = 26; +constexpr int FW_NORMAL = 400; +constexpr BYTE CLEARTYPE_QUALITY = 5, DEFAULT_CHARSET = 1; +constexpr DWORD ERROR_BAD_NETPATH = 53, ERROR_NOT_READY = 21; +constexpr UINT CF_UNICODETEXT = 13; +constexpr UINT GMEM_MOVEABLE = 2; + +// cursors (LoadCursorW's ids) +#define IDC_ARROW MAKEINTRESOURCEW(32512) +#define IDC_IBEAM MAKEINTRESOURCEW(32513) +#define IDC_APPSTARTING MAKEINTRESOURCEW(32650) +#define IDC_HAND MAKEINTRESOURCEW(32649) + +// virtual keys +constexpr WPARAM VK_LBUTTON = 0x01, VK_BACK = 0x08, VK_TAB = 0x09, VK_RETURN = 0x0D, VK_SHIFT = 0x10, VK_CONTROL = 0x11, VK_MENU = 0x12, + VK_ESCAPE = 0x1B, VK_SPACE = 0x20, VK_PRIOR = 0x21, VK_NEXT = 0x22, VK_END = 0x23, VK_HOME = 0x24, VK_LEFT = 0x25, + VK_UP = 0x26, VK_RIGHT = 0x27, VK_DOWN = 0x28, VK_INSERT = 0x2D, VK_DELETE = 0x2E, VK_F4 = 0x73, VK_NUMPAD0 = 0x60, VK_NUMPAD9 = 0x69, VK_F10 = 0x79, VK_BROWSER_BACK = 0xA6, + VK_OEM_3 = 0xC0; +constexpr UINT MAPVK_VK_TO_VSC_EX = 4; + +// ---- windows ------------------------------------------------------------------------------------------------------------- +typedef WORD ATOM; +ATOM RegisterClassExW(const WNDCLASSEXW* wc); +HWND CreateWindowExW(DWORD exStyle, LPCWSTR cls, LPCWSTR title, DWORD style, int x, int y, int w, int h, HWND parent, HMENU menu, HINSTANCE inst, LPVOID param); +BOOL DestroyWindow(HWND h); +BOOL IsWindow(HWND h); +HWND FindWindowW(LPCWSTR cls, LPCWSTR title); // this process's windows only +HWND FindWindowExW(HWND parent, HWND after, LPCWSTR cls, LPCWSTR title); +BOOL ShowWindow(HWND h, int cmd); +BOOL UpdateWindow(HWND h); +BOOL IsWindowVisible(HWND h); +BOOL IsWindowEnabled(HWND h); +BOOL MessageBeep(UINT type); // silent: no sound is made +BOOL IsIconic(HWND h); +BOOL IsZoomed(HWND h); +BOOL SetWindowPos(HWND h, HWND after, int x, int y, int w, int cy, UINT flags); +BOOL GetWindowRect(HWND h, RECT* r); +BOOL GetClientRect(HWND h, RECT* r); +BOOL GetWindowPlacement(HWND h, WINDOWPLACEMENT* wp); +int MapWindowPoints(HWND from, HWND to, POINT* pts, UINT n); +BOOL ScreenToClient(HWND h, POINT* p); +BOOL ClientToScreen(HWND h, POINT* p); +HWND GetParent(HWND h); +LONG_PTR GetWindowLongPtrW(HWND h, int index); // GWLP_ID, GWLP_USERDATA +LONG_PTR SetWindowLongPtrW(HWND h, int index, LONG_PTR v); +BOOL SetWindowTextW(HWND h, LPCWSTR text); +int GetWindowTextW(HWND h, LPWSTR out, int n); +int GetWindowTextLengthW(HWND h); +BOOL SetForegroundWindow(HWND h); +BOOL FlashWindow(HWND h, BOOL invert); +BOOL InvalidateRect(HWND h, const RECT* r, BOOL erase); +BOOL RedrawWindow(HWND h, const RECT* r, void* region, UINT flags); +HDC BeginPaint(HWND h, PAINTSTRUCT* ps); +BOOL EndPaint(HWND h, const PAINTSTRUCT* ps); +BOOL EqualRect(const RECT* a, const RECT* b); +HWND WindowFromPoint(POINT p); +BOOL GetCursorPos(POINT* p); +BOOL SetWindowSubclass(HWND h, SUBCLASSPROC proc, UINT_PTR id, DWORD_PTR data); +LRESULT DefSubclassProc(HWND h, UINT m, WPARAM wp, LPARAM lp); +LRESULT DefWindowProcW(HWND h, UINT m, WPARAM wp, LPARAM lp); +LRESULT CallWindowProcW(WNDPROC proc, HWND h, UINT m, WPARAM wp, LPARAM lp); + +// ---- messages and timers -------------------------------------------------------------------------------------------------- +BOOL PostMessageW(HWND h, UINT m, WPARAM wp, LPARAM lp); // any thread; FALSE when the window is gone +LRESULT SendMessageW(HWND h, UINT m, WPARAM wp, LPARAM lp); +BOOL GetMessageW(MSG* m, HWND h, UINT lo, UINT hi); // 0 for WM_QUIT +BOOL PeekMessageW(MSG* m, HWND h, UINT lo, UINT hi, UINT remove); +BOOL TranslateMessage(const MSG* m); +LRESULT DispatchMessageW(const MSG* m); +void PostQuitMessage(int code); +DWORD MsgWaitForMultipleObjects(DWORD n, const HANDLE* handles, BOOL all, DWORD ms, DWORD mask); +UINT_PTR SetTimer(HWND h, UINT_PTR id, UINT ms, TIMERPROC proc); // proc: called from the message loop instead of WM_TIMER +BOOL KillTimer(HWND h, UINT_PTR id); +UINT GetDoubleClickTime(); +HWND SetFocus(HWND h); +HWND GetFocus(); +HWND SetCapture(HWND h); +BOOL ReleaseCapture(); +HWND GetCapture(); +short GetKeyState(int vk); +BOOL TrackMouseEvent(TRACKMOUSEEVENT* t); +UINT MapVirtualKeyW(UINT code, UINT type); +int GetKeyNameTextW(LONG lp, LPWSTR out, int n); + +// ---- cursors, icons, metrics, monitors -------------------------------------------------------------------------------------- +HCURSOR LoadCursorW(HINSTANCE inst, LPCWSTR id); +HCURSOR SetCursor(HCURSOR c); +HICON LoadIconW(HINSTANCE inst, LPCWSTR id); +BOOL DestroyIcon(HICON i); +int GetSystemMetrics(int index); +int GetSystemMetricsForDpi(int index, UINT dpi); +UINT GetDpiForWindow(HWND h); +UINT GetDpiForSystem(); +BOOL AdjustWindowRectExForDpi(RECT* r, DWORD style, BOOL menu, DWORD exStyle, UINT dpi); +BOOL SystemParametersInfoW(UINT action, UINT param, PVOID data, UINT winIni); +DWORD GetSysColor(int index); +HBRUSH GetSysColorBrush(int index); +HMONITOR MonitorFromPoint(POINT p, DWORD flags); +HMONITOR MonitorFromRect(const RECT* r, DWORD flags); +HMONITOR MonitorFromWindow(HWND h, DWORD flags); +BOOL GetMonitorInfoW(HMONITOR m, MONITORINFO* mi); +HRESULT DwmSetWindowAttribute(HWND h, DWORD attr, LPCVOID value, DWORD size); // no DWM: always fails +BOOL ShutdownBlockReasonCreate(HWND h, LPCWSTR reason); // no session manager hook: succeeds, does nothing +BOOL ShutdownBlockReasonDestroy(HWND h); +void GetStartupInfoW(STARTUPINFOW* si); +INT_PTR ShellExecuteW(HWND h, LPCWSTR verb, LPCWSTR file, LPCWSTR params, LPCWSTR dir, int show); // xdg-open for documents and addresses + +// ---- GDI stand-ins: only what the text fields' font and colours need ------------------------------------------------------------ +HFONT CreateFontIndirectW(const LOGFONTW* lf); +HBRUSH CreateSolidBrush(COLORREF c); +BOOL DeleteObject(HGDIOBJ o); +HDC GetDC(HWND h); +int ReleaseDC(HWND h, HDC dc); +HGDIOBJ SelectObject(HDC dc, HGDIOBJ o); +int GetTextFaceW(HDC dc, int n, LPWSTR out); +BOOL GetTextMetricsW(HDC dc, TEXTMETRICW* tm); +COLORREF SetTextColor(HDC dc, COLORREF c); +COLORREF SetBkColor(HDC dc, COLORREF c); +BOOL InitCommonControlsEx(const INITCOMMONCONTROLSEX*); + +// ---- clipboard (text only) -------------------------------------------------------------------------------------------------------- +BOOL OpenClipboard(HWND owner); +BOOL EmptyClipboard(); +HANDLE SetClipboardData(UINT format, HANDLE mem); +HANDLE GetClipboardData(UINT format); +BOOL CloseClipboard(); +HGLOBAL GlobalAlloc(UINT flags, SIZE_T bytes); +LPVOID GlobalLock(HGLOBAL h); +BOOL GlobalUnlock(HGLOBAL h); +HGLOBAL GlobalFree(HGLOBAL h); + +// ---- process start and console (main.cpp, cli.cpp) ------------------------------------------------------------------------------------ +void WgSetCommandLine(int argc, char** argv); // main() hands the process's arguments over; GetCommandLineW returns them quoted +LPWSTR GetCommandLineW(); +LPWSTR* CommandLineToArgvW(LPCWSTR cmd, int* argc); +BOOL SetDefaultDllDirectories(DWORD flags); +BOOL AttachConsole(DWORD pid); +constexpr DWORD ATTACH_PARENT_PROCESS = 0xFFFFFFFFu; +BOOL WriteConsoleW(HANDLE h, const void* buf, DWORD n, LPDWORD written, LPVOID reserved); +double _wtof(const wchar_t* s); +int MulDiv(int a, int b, int c); + +// ---- what the Linux build's own code (ui_gfx_cairo.cpp, the test hook) asks of the layer -------------------------------------------------- +#include +#include +namespace wgwin { +// The frame (premultiplied BGRA, `stride` bytes a row) shown in the window; false when the window has no surface or another size. +bool Present(HWND h, const uint8_t* bgra, int w, int h2, int stride); +// What a text field shows, for the drawing code to paint after the frame: its rectangle in the parent's client pixels, text, +// selection, the cue banner, margins, the caret's state and the font's pixel height. +struct EditView { + HWND h = nullptr; + RECT rc{}; + std::wstring text, cue; + int selStart = 0, selEnd = 0, caret = 0, marginL = 0, marginR = 0, fontPx = 13, scroll = 0; + bool focused = false, caretOn = false; + // x of the character boundary `i` in the text, in pixels from the field's left edge; set by the painter (Measure) +}; +// the visible text fields of `parent`, in creation order +void EditViews(HWND parent, std::vector& out); +// The painter's text measure (pixels from the text start to the boundary before character `i` of `text`) for the field's font: +// the caret and the selection are placed with it. +// The text field's horizontal scroll, kept by the painter so the caret stays in view. +void SetEditScroll(HWND h, int scroll); +// The window's icon: straight-alpha BGRA pixels. +void SetIcon(HWND h, const uint8_t* bgra, int w, int h2); +void SetEditMeasure(std::function f); +// Test builds only (WRONGGPU_TESTING): WRONGGPU_UI_SCRIPT names a script of synthetic input run by the message loop; its `shot` +// and `dump` lines call this hook with the rest of the line (the Linux app's test hook: ui_live_hook_linux.cpp). +void SetScriptHook(std::function f); +// For the hook: a left click at (x, y) in the window's client DIPs. A script line that starts with `until` is asked again every +// 100 ms until the hook says true (at most 30 s). +void ScriptClick(float x, float y); +} // namespace wgwin diff --git a/clean/installer/src/platform/posix/win32_window_edit.cpp b/clean/installer/src/platform/posix/win32_window_edit.cpp new file mode 100644 index 00000000..8c281879 --- /dev/null +++ b/clean/installer/src/platform/posix/win32_window_edit.cpp @@ -0,0 +1,248 @@ +// SPDX-License-Identifier: MIT +// Linux: the Win32 "EDIT" control as the launcher uses it: a single line with a caret and a selection, keyboard editing (arrows, +// Home/End, Backspace/Delete, Ctrl+A/C/X/V/Z, word moves), the mouse (click, drag, double click for a word), the clipboard, the +// messages the app sends it (WM_SETTEXT / WM_GETTEXT / WM_GETTEXTLENGTH, EM_SETSEL, EM_GETSEL, EM_REPLACESEL, EM_SETMARGINS, +// EM_GETRECT, EM_SETCUEBANNER, WM_SETFONT, WM_GETFONT, WM_CUT / WM_COPY / WM_PASTE / WM_CLEAR / WM_UNDO) and the notifications it +// expects (EN_CHANGE, EN_SETFOCUS, EN_KILLFOCUS as WM_COMMAND to the parent). The field draws nothing itself: the Linux Gfx paints +// it after the app's frame from wgwin::EditViews. Not emulated: several lines, password and number styles, drag and drop, IME +// composition, right-to-left text. +#include +#include + +#include "win32_window_internal.h" + +namespace wgwin { + +namespace { + +bool WordCh(wchar_t c) { return iswalnum((wint_t)c) || c == L'_'; } +int PrevWord(const std::wstring& t, int i) { + while (i > 0 && !WordCh(t[(size_t)i - 1])) --i; + while (i > 0 && WordCh(t[(size_t)i - 1])) --i; + return i; +} +int NextWord(const std::wstring& t, int i) { + const int n = (int)t.size(); + while (i < n && WordCh(t[(size_t)i])) ++i; + while (i < n && !WordCh(t[(size_t)i])) ++i; + return i; +} + +void Notify(Win* w, UINT code) { + if (w->parent) Send((HWND)w->parent, WM_COMMAND, MAKEWPARAM((WORD)(w->ctrlId & 0xFFFF), (WORD)code), (LPARAM)(HWND)w->id); +} +void Touch(Win* w) { + w->edit->lastInputMs = NowMs(); + InvalidateWin(w); +} +int Len(Win* w) { return (int)w->text.size(); } +int Clamp(Win* w, int i) { return std::max(0, std::min(i, Len(w))); } +int SelLo(EditState& s) { return std::min(s.anchor, s.caret); } +int SelHi(EditState& s) { return std::max(s.anchor, s.caret); } + +void Snapshot(Win* w) { + EditState& s = *w->edit; + s.undoText = w->text; s.undoAnchor = s.anchor; s.undoCaret = s.caret; +} + +// the text between [lo, hi) replaced; the caret after what went in +void Replace(Win* w, int lo, int hi, const std::wstring& ins) { + EditState& s = *w->edit; + lo = Clamp(w, lo); hi = Clamp(w, hi); + if (hi < lo) std::swap(lo, hi); + std::wstring clean; + for (wchar_t c : ins) if (c != L'\r' && c != L'\n') clean += c; // a single line + if (lo == hi && clean.empty()) return; + Snapshot(w); + w->text.replace((size_t)lo, (size_t)(hi - lo), clean); + s.anchor = s.caret = lo + (int)clean.size(); + Touch(w); + Notify(w, EN_CHANGE); +} + +void DeleteSel(Win* w) { EditState& s = *w->edit; Replace(w, SelLo(s), SelHi(s), L""); } + +void Copy(Win* w) { + EditState& s = *w->edit; + if (SelLo(s) != SelHi(s)) ClipSet(w->text.substr((size_t)SelLo(s), (size_t)(SelHi(s) - SelLo(s)))); +} +void Paste(Win* w) { + EditState& s = *w->edit; + const std::wstring t = ClipGet(); + if (!t.empty()) Replace(w, SelLo(s), SelHi(s), t); +} +void Undo(Win* w) { + EditState& s = *w->edit; + if (s.undoText == w->text) return; + std::swap(s.undoText, w->text); + std::swap(s.undoAnchor, s.anchor); + std::swap(s.undoCaret, s.caret); + s.anchor = Clamp(w, s.anchor); s.caret = Clamp(w, s.caret); + Touch(w); + Notify(w, EN_CHANGE); +} + +// the character boundary nearest to x (pixels from the field's left edge) +int IndexAt(Win* w, int x) { + EditState& s = *w->edit; + const float rel = (float)(x - s.marginL + s.scroll); + int lo = 0, hi = Len(w); + if (rel <= 0) return 0; + while (lo < hi) { // the first boundary at or past rel + const int mid = (lo + hi) / 2; + if (EditMeasure(w->text, s.fontPx, mid) < rel) lo = mid + 1; else hi = mid; + } + if (lo > 0 && lo <= Len(w)) { + const float a = EditMeasure(w->text, s.fontPx, lo - 1), b = EditMeasure(w->text, s.fontPx, lo); + if (rel - a < b - rel) --lo; + } + return Clamp(w, lo); +} + +void Move(Win* w, int to, bool extend) { + EditState& s = *w->edit; + s.caret = Clamp(w, to); + if (!extend) s.anchor = s.caret; + Touch(w); +} + +LRESULT Key(Win* w, WPARAM vk) { + EditState& s = *w->edit; + const bool shift = GetKeyState(VK_SHIFT) < 0, ctrl = GetKeyState(VK_CONTROL) < 0; + const bool sel = SelLo(s) != SelHi(s); + switch (vk) { + case VK_LEFT: + if (sel && !shift && !ctrl) Move(w, SelLo(s), false); + else Move(w, ctrl ? PrevWord(w->text, s.caret) : s.caret - 1, shift); + return 0; + case VK_RIGHT: + if (sel && !shift && !ctrl) Move(w, SelHi(s), false); + else Move(w, ctrl ? NextWord(w->text, s.caret) : s.caret + 1, shift); + return 0; + case VK_HOME: Move(w, 0, shift); return 0; + case VK_END: Move(w, Len(w), shift); return 0; + case VK_BACK: + if (sel) DeleteSel(w); + else Replace(w, ctrl ? PrevWord(w->text, s.caret) : s.caret - 1, s.caret, L""); + return 0; + case VK_DELETE: + if (shift && sel) { Copy(w); DeleteSel(w); } + else if (sel) DeleteSel(w); + else Replace(w, s.caret, ctrl ? NextWord(w->text, s.caret) : s.caret + 1, L""); + return 0; + case VK_INSERT: + if (ctrl) Copy(w); else if (shift) Paste(w); + return 0; + case 'A': if (ctrl) { s.anchor = 0; s.caret = Len(w); Touch(w); } return 0; + case 'C': if (ctrl) Copy(w); return 0; + case 'X': if (ctrl) { Copy(w); DeleteSel(w); } return 0; + case 'V': if (ctrl) Paste(w); return 0; + case 'Z': if (ctrl) Undo(w); return 0; + default: return 0; + } +} + +} // namespace + +void EditInit(Win* w) { + w->edit = std::make_unique(); + w->edit->lastInputMs = NowMs(); +} + +void EditSetText(Win* w, const std::wstring& text, bool notify) { + EditState& s = *w->edit; + if (notify) Snapshot(w); + w->text = text; + s.anchor = s.caret = 0; // as a Win32 edit (and Wine's): setting the text leaves the caret at its start; the app selects + // all itself where it wants that (EM_SETSEL 0, -1 on the search box) + s.scroll = 0; + Touch(w); + if (notify) Notify(w, EN_CHANGE); +} + +LRESULT EditClassProc(Win* w, UINT m, WPARAM wp, LPARAM lp) { + EditState& s = *w->edit; + const HWND h = (HWND)w->id; + switch (m) { + case WM_GETDLGCODE: return DLGC_WANTCHARS | DLGC_HASSETSEL | DLGC_WANTARROWS; + case WM_SETTEXT: EditSetText(w, lp ? (const wchar_t*)lp : L"", true); return TRUE; + case WM_GETTEXT: { + wchar_t* out = (wchar_t*)lp; + if (!out || wp == 0) return 0; + const size_t n = std::min(w->text.size(), wp - 1); + for (size_t i = 0; i < n; ++i) out[i] = w->text[i]; + out[n] = 0; + return (LRESULT)n; + } + case WM_GETTEXTLENGTH: return (LRESULT)w->text.size(); + case WM_SETFONT: { + LOGFONTW lf{}; + if (GdiFont((HFONT)wp, &lf)) { s.font = (HFONT)wp; s.fontPx = std::max(1, (int)std::abs(lf.lfHeight)); } + if (lp) InvalidateWin(w); + return 0; + } + case WM_GETFONT: return (LRESULT)s.font; + case EM_SETMARGINS: + if (wp & EC_LEFTMARGIN) s.marginL = (int)LOWORD(lp); + if (wp & EC_RIGHTMARGIN) s.marginR = (int)HIWORD(lp); + InvalidateWin(w); + return 0; + case EM_GETRECT: + if (lp) *(RECT*)lp = RECT{s.marginL, 0, std::max(0, w->w - s.marginR), w->h}; + return 0; + case EM_SETSEL: { + const int a = (int)wp, b = (int)lp; + if (a == -1) { s.anchor = s.caret; } + else { s.anchor = Clamp(w, a); s.caret = b < 0 ? Len(w) : Clamp(w, b); } + Touch(w); + return 0; + } + case EM_GETSEL: + if (wp) *(DWORD*)wp = (DWORD)SelLo(s); + if (lp) *(DWORD*)lp = (DWORD)SelHi(s); + return MAKELONG(SelLo(s), SelHi(s)); + case EM_REPLACESEL: Replace(w, SelLo(s), SelHi(s), lp ? (const wchar_t*)lp : L""); return 0; + case EM_SETCUEBANNER: s.cue = lp ? (const wchar_t*)lp : L""; return TRUE; + case EM_GETCUEBANNER: return FALSE; + case WM_CUT: Copy(w); DeleteSel(w); return 0; + case WM_COPY: Copy(w); return 0; + case WM_PASTE: Paste(w); return 0; + case WM_CLEAR: DeleteSel(w); return 0; + case WM_UNDO: case EM_UNDO: Undo(w); return TRUE; + case WM_SETFOCUS: s.lastInputMs = NowMs(); Notify(w, EN_SETFOCUS); InvalidateWin(w); return 0; + case WM_KILLFOCUS: s.dragging = false; Notify(w, EN_KILLFOCUS); InvalidateWin(w); return 0; + case WM_KEYDOWN: case WM_SYSKEYDOWN: return Key(w, wp); + case WM_CHAR: + if (wp >= 32 && wp != 127 && GetKeyState(VK_CONTROL) >= 0) Replace(w, SelLo(s), SelHi(s), std::wstring(1, (wchar_t)wp)); + return 0; + case WM_SETCURSOR: SetCursor(LoadCursorW(nullptr, IDC_IBEAM)); return TRUE; + case WM_LBUTTONDOWN: { + SetFocus(h); + const int i = IndexAt(w, GET_X_LPARAM(lp)); + Move(w, i, GetKeyState(VK_SHIFT) < 0); + s.dragging = true; + SetCapture(h); + return 0; + } + case WM_LBUTTONDBLCLK: { + const int i = IndexAt(w, GET_X_LPARAM(lp)); + int lo = i, hi = i; + while (lo > 0 && WordCh(w->text[(size_t)lo - 1])) --lo; + while (hi < Len(w) && WordCh(w->text[(size_t)hi])) ++hi; + s.anchor = lo; s.caret = hi; + Touch(w); + return 0; + } + case WM_MOUSEMOVE: + if (s.dragging) Move(w, IndexAt(w, GET_X_LPARAM(lp)), true); + return 0; + case WM_LBUTTONUP: + if (s.dragging) { s.dragging = false; if (GetCapture() == h) ReleaseCapture(); } + return 0; + case WM_CAPTURECHANGED: s.dragging = false; return 0; + case WM_NCDESTROY: if (g_focus == h) g_focus = nullptr; return 0; + default: return DefWindowProcW(h, m, wp, lp); + } +} + +} // namespace wgwin diff --git a/clean/installer/src/platform/posix/win32_window_internal.h b/clean/installer/src/platform/posix/win32_window_internal.h new file mode 100644 index 00000000..60869124 --- /dev/null +++ b/clean/installer/src/platform/posix/win32_window_internal.h @@ -0,0 +1,77 @@ +// SPDX-License-Identifier: MIT +// Linux window layer internals shared by win32_window_sdl.cpp (windows, messages, SDL events) and win32_window_edit.cpp (the +// "EDIT" control). +#pragma once +#include +#include +#include +#include +#include + +#include "win32_window.h" + +struct SDL_Window; + +namespace wgwin { + +// The text field's state (a single line, as the launcher uses it) +struct EditState { + int anchor = 0, caret = 0; // the selection: anchor is where it started, caret where it ends (and where the caret shows) + int marginL = 0, marginR = 0; + int fontPx = 13; + int scroll = 0; // pixels the text is moved left (the caret kept in view) + std::wstring cue, undoText; + int undoAnchor = 0, undoCaret = 0; + bool dragging = false; + uint64_t lastInputMs = 0; // the caret shows solid for a moment after an edit or a move + HFONT font = nullptr; +}; + +struct Sub { SUBCLASSPROC proc; UINT_PTR id; DWORD_PTR data; }; + +struct Win { + uintptr_t id = 0; + std::wstring cls, text; + WNDPROC proc = nullptr; // the class's window procedure; null for a built-in class (EDIT) + uintptr_t parent = 0; // 0: top-level (or message-only) + DWORD style = 0, exStyle = 0; + bool messageOnly = false, visible = false, builtinEdit = false; + int x = 0, y = 0, w = 0, h = 0; // top-level: its place on the screen (pixels); a child: in its parent's client area + SDL_Window* sdl = nullptr; + unsigned sdlId = 0; + float density = 1; // pixels per SDL window unit (read again when the display scale or pixel size changes) + RECT dpiRect{}; // the suggested rect of the WM_DPICHANGED message queued for this window + bool invalid = false; + uint64_t lastPaintMs = 0; + bool trackLeave = false, trackNcLeave = false; + LONG_PTR userdata = 0, ctrlId = 0; + std::vector subs; // outermost first + std::unique_ptr edit; + bool maximized = false, minimized = false; +}; + +Win* Find(HWND h); // null when gone +uint64_t NowMs(); +// a message posted or sent to a window, through its subclasses to the class's procedure +LRESULT Send(HWND h, UINT m, WPARAM wp, LPARAM lp); +void InvalidateWin(Win* w); +POINT ClientOriginOnScreen(Win* w); // the client area's top-left corner on the screen (pixels) +HWND TopOf(Win* w); +extern HWND g_focus; // the window with the keyboard (a text field or the window) +void ShowTextInput(bool on, Win* w); +#ifdef WRONGGPU_TESTING +void TestSetPixelDensity(float d); // the density every window reports from now on (0: SDL's own); the window units stay +#endif + +// the "EDIT" class's procedure (win32_window_edit.cpp) +LRESULT EditClassProc(Win* w, UINT m, WPARAM wp, LPARAM lp); +void EditInit(Win* w); +// the text replaced as a whole with the caret after it (WM_SETTEXT; notify: the undo step and EN_CHANGE of one made by a message) +void EditSetText(Win* w, const std::wstring& text, bool notify); +// measure: the painter's, for caret placement by the mouse +float EditMeasure(const std::wstring& text, int fontPx, int upTo); +std::wstring ClipGet(); // the clipboard's text (win32_window_sdl.cpp) +void ClipSet(const std::wstring& text); +bool GdiFont(HFONT f, LOGFONTW* out); // a font made by CreateFontIndirectW (win32_window_misc.cpp) + +} // namespace wgwin diff --git a/clean/installer/src/platform/posix/win32_window_misc.cpp b/clean/installer/src/platform/posix/win32_window_misc.cpp new file mode 100644 index 00000000..1f273c63 --- /dev/null +++ b/clean/installer/src/platform/posix/win32_window_misc.cpp @@ -0,0 +1,200 @@ +// SPDX-License-Identifier: MIT +// Linux: the smaller Win32 calls the launcher's window and command line make that need no SDL: the GDI stand-ins behind the text +// fields' font, the clipboard (text), the command line main() hands over, console output and a few conversions (win32_window.h). +#include + +#include + +#include +#include +#include +#include + +#include "win32_posix_internal.h" +#include "win32_window_internal.h" + +// ---- GDI: a font is its LOGFONT, a brush its colour, a device context what was selected into it ------------------------------------ +namespace { +struct GdiObj { + enum Type { Font, Brush, Dc } type; + LOGFONTW lf{}; + COLORREF color = 0, text = 0, bk = 0; + HGDIOBJ selected = nullptr; +}; +std::mutex g_gdiMu; +std::unordered_set g_gdi; +GdiObj* Obj(HANDLE h) { + std::lock_guard l(g_gdiMu); + auto* o = static_cast(h); + return h && g_gdi.count(o) ? o : nullptr; +} +GdiObj* NewObj(GdiObj::Type t) { + auto* o = new GdiObj; + o->type = t; + std::lock_guard l(g_gdiMu); + g_gdi.insert(o); + return o; +} +} // namespace + +namespace wgwin { +bool GdiFont(HFONT f, LOGFONTW* out) { + GdiObj* o = Obj(f); + if (!o || o->type != GdiObj::Font) return false; + *out = o->lf; + return true; +} +} // namespace wgwin + +HFONT CreateFontIndirectW(const LOGFONTW* lf) { + GdiObj* o = NewObj(GdiObj::Font); + if (lf) o->lf = *lf; + return o; +} +HBRUSH CreateSolidBrush(COLORREF c) { GdiObj* o = NewObj(GdiObj::Brush); o->color = c; return o; } +BOOL DeleteObject(HGDIOBJ h) { + GdiObj* o = Obj(h); + if (!o) return FALSE; + { + std::lock_guard l(g_gdiMu); + g_gdi.erase(o); + } + delete o; + return TRUE; +} +HDC GetDC(HWND) { return NewObj(GdiObj::Dc); } +int ReleaseDC(HWND, HDC dc) { DeleteObject(dc); return 1; } +HGDIOBJ SelectObject(HDC dc, HGDIOBJ o) { + GdiObj* d = Obj(dc); + if (!d) return nullptr; + HGDIOBJ old = d->selected; + d->selected = o; + return old; +} +int GetTextFaceW(HDC dc, int n, LPWSTR out) { + GdiObj* d = Obj(dc); + GdiObj* f = d ? Obj(d->selected) : nullptr; + if (!f || f->type != GdiObj::Font || !out || n <= 0) return 0; + int i = 0; + for (; i < n - 1 && f->lf.lfFaceName[i]; ++i) out[i] = f->lf.lfFaceName[i]; + out[i] = 0; + return i; +} +BOOL GetTextMetricsW(HDC dc, TEXTMETRICW* tm) { + GdiObj* d = Obj(dc); + GdiObj* f = d ? Obj(d->selected) : nullptr; + if (!f || !tm) return FALSE; + const double em = std::abs((double)f->lf.lfHeight); + // Selawik, as Segoe UI: ascent 1.08 em, descent 0.25 em + tm->tmAscent = (LONG)std::lround(em * 1.08); + tm->tmDescent = (LONG)std::lround(em * 0.25); + tm->tmHeight = tm->tmAscent + tm->tmDescent; + tm->tmInternalLeading = tm->tmExternalLeading = 0; + tm->tmAveCharWidth = (LONG)std::lround(em * 0.55); + return TRUE; +} +COLORREF SetTextColor(HDC dc, COLORREF c) { GdiObj* d = Obj(dc); if (!d) return 0; const COLORREF o = d->text; d->text = c; return o; } +COLORREF SetBkColor(HDC dc, COLORREF c) { GdiObj* d = Obj(dc); if (!d) return 0; const COLORREF o = d->bk; d->bk = c; return o; } +BOOL InitCommonControlsEx(const INITCOMMONCONTROLSEX*) { return TRUE; } + +// ---- clipboard (text): the layer's own text is held until the next one --------------------------------------------------------------------- +namespace { +std::wstring g_pending; +std::wstring g_got; // what GetClipboardData handed out (the system owns it: it stays valid until the next call) +} // namespace +BOOL OpenClipboard(HWND) { return TRUE; } +BOOL EmptyClipboard() { g_pending.clear(); return TRUE; } +HANDLE SetClipboardData(UINT format, HANDLE mem) { + if (format != CF_UNICODETEXT || !mem) return nullptr; + g_pending = static_cast(mem); + wgwin::ClipSet(g_pending); + return mem; +} +HANDLE GetClipboardData(UINT format) { + if (format != CF_UNICODETEXT) return nullptr; + g_got = wgwin::ClipGet(); + return (HANDLE)g_got.c_str(); +} +BOOL CloseClipboard() { return TRUE; } +HGLOBAL GlobalAlloc(UINT, SIZE_T bytes) { return calloc(1, bytes ? bytes : 1); } +LPVOID GlobalLock(HGLOBAL h) { return h; } +BOOL GlobalUnlock(HGLOBAL) { return TRUE; } +HGLOBAL GlobalFree(HGLOBAL h) { free(h); return nullptr; } + +// ---- the command line ------------------------------------------------------------------------------------------------------------------------ +namespace { +std::wstring g_cmd; +std::wstring Quoted(const std::wstring& a) { + if (!a.empty() && a.find_first_of(L" \t\"") == std::wstring::npos) return a; + std::wstring o = L"\""; + size_t bs = 0; + for (wchar_t c : a) { + if (c == L'\\') { ++bs; continue; } + if (c == L'"') { o.append(bs * 2 + 1, L'\\'); o += L'"'; } + else { o.append(bs, L'\\'); o += c; } + bs = 0; + } + o.append(bs * 2, L'\\'); + return o + L"\""; +} +} // namespace +void WgSetCommandLine(int argc, char** argv) { + g_cmd.clear(); + for (int i = 0; i < argc; ++i) { + if (i) g_cmd += L' '; + g_cmd += Quoted(wgposix::FromUtf8(argv[i], strlen(argv[i]))); + } +} +LPWSTR GetCommandLineW() { return g_cmd.empty() ? const_cast(L"") : g_cmd.data(); } +// the way CommandLineToArgvW reads it: the first word has no escapes; then backslashes before a quote are halved +LPWSTR* CommandLineToArgvW(LPCWSTR cmd, int* argc) { + std::vector args; + const wchar_t* p = cmd ? cmd : L""; + if (*p == L'"') { ++p; std::wstring a; while (*p && *p != L'"') a += *p++; if (*p) ++p; args.push_back(a); } + else { std::wstring a; while (*p && *p != L' ' && *p != L'\t') a += *p++; args.push_back(a); } + for (;;) { + while (*p == L' ' || *p == L'\t') ++p; + if (!*p) break; + std::wstring a; + bool quoted = false; + while (*p && (quoted || (*p != L' ' && *p != L'\t'))) { + size_t bs = 0; + while (*p == L'\\') { ++bs; ++p; } + if (*p == L'"') { + a.append(bs / 2, L'\\'); + if (bs % 2) a += L'"'; + else if (quoted && p[1] == L'"') { a += L'"'; ++p; } + else quoted = !quoted; + ++p; + } else { a.append(bs, L'\\'); if (*p) a += *p++; } + } + args.push_back(a); + } + size_t chars = 0; + for (auto& a : args) chars += a.size() + 1; + auto* block = static_cast(malloc(sizeof(wchar_t*) * (args.size() + 1) + sizeof(wchar_t) * chars)); + if (!block) return nullptr; + auto** v = reinterpret_cast(block); + auto* s = reinterpret_cast(block + sizeof(wchar_t*) * (args.size() + 1)); + for (size_t i = 0; i < args.size(); ++i) { + v[i] = s; + memcpy(s, args[i].c_str(), sizeof(wchar_t) * (args[i].size() + 1)); + s += args[i].size() + 1; + } + v[args.size()] = nullptr; + if (argc) *argc = (int)args.size(); + return v; +} +BOOL SetDefaultDllDirectories(DWORD) { return TRUE; } + +// ---- console ---------------------------------------------------------------------------------------------------------------------------------- +BOOL AttachConsole(DWORD) { return isatty(1) || isatty(2) ? TRUE : FALSE; } +BOOL WriteConsoleW(HANDLE h, const void* buf, DWORD n, LPDWORD written, LPVOID) { + const std::string u = wgposix::ToUtf8(static_cast(buf), n); + DWORD w = 0; + const BOOL ok = WriteFile(h, u.data(), (DWORD)u.size(), &w, nullptr); + if (written) *written = n; + return ok; +} +double _wtof(const wchar_t* s) { return wcstod(s, nullptr); } +int MulDiv(int a, int b, int c) { return c ? (int)std::llround((double)a * b / c) : -1; } diff --git a/clean/installer/src/platform/posix/win32_window_sdl.cpp b/clean/installer/src/platform/posix/win32_window_sdl.cpp new file mode 100644 index 00000000..114651f7 --- /dev/null +++ b/clean/installer/src/platform/posix/win32_window_sdl.cpp @@ -0,0 +1,1460 @@ +// SPDX-License-Identifier: MIT +// Linux: the Win32 window layer on SDL3 (win32_window.h). The launcher's WndProc, its timers, its posted messages from worker +// threads and its nested message loops (dialogs) all run on it unchanged: SDL events become the Win32 messages the app answers, +// posted messages and timers share one queue, WM_PAINT comes when the queue is empty, and the custom caption works through +// WM_NCHITTEST (SDL_SetWindowHitTest moves and sizes a borderless window; the caption buttons arrive as WM_NC* messages). +// Without SDL's video (ui-dump and ui-render use a message-only window) nothing here starts SDL. +#include "win32_window_internal.h" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "win32_posix_internal.h" + +namespace wgwin { + +HWND g_focus = nullptr; +uint64_t NowMs() { + using namespace std::chrono; + return (uint64_t)duration_cast(steady_clock::now().time_since_epoch()).count(); +} + +namespace { + +std::mutex g_mu; +std::unordered_map> g_wins; +uintptr_t g_nextId = 1; +std::map g_classes; // by lower-case name +// The keys and buttons down as of an input message: GetKeyState reports these for the message being handled (Win32), not what SDL's +// events later in the same batch made of the keyboard. +struct KeySnap { std::bitset<256> down; uint8_t btn = 0; }; +struct Queued { MSG msg; bool hasSnap; KeySnap snap; }; +std::deque g_q; +std::condition_variable g_cv; +bool g_quit = false; +int g_quitCode = 0; +struct Timer { uintptr_t hwnd; UINT_PTR id; uint64_t interval, due; TIMERPROC proc; }; +std::vector g_timers; +std::vector> g_depth; // the subclass chain position of each message being handled (DefSubclassProc) + +bool g_sdlUp = false; +Uint32 g_wakeType = 0; +std::atomic g_wakePending{false}; +std::unordered_map g_bySdl; +HWND g_capture = nullptr, g_active = nullptr; +POINT g_mouse{0, 0}; // the pointer on the screen (pixels), as the last event said +std::bitset<256> g_down; // the keys down as the last SDL event pumped said (the UI thread's) +uint8_t g_btn = 0; // MK_LBUTTON | MK_RBUTTON | MK_MBUTTON held +KeySnap g_cur; // the state of the input message taken off the queue last +std::atomic g_uiThread{0}; // the thread that runs the loop (a hash of its id; 0 until it first calls in) +size_t ThisThread() { return std::hash()(std::this_thread::get_id()) | 1; } +void NoteUiThread() { size_t none = 0; g_uiThread.compare_exchange_strong(none, ThisThread()); } +bool OnUiThread() { return g_uiThread.load() == ThisThread(); } +std::function g_measure; +std::function& Hook() { static std::function f; return f; } // a function-local static: set by another file's static initialiser +std::unordered_map g_cursors; +unsigned g_cursorId = 0; +constexpr UINT_PTR kCaretTimer = 0x7E01; // an internal timer: the focused text field's caret blinks; never reaches the app + +bool EnsureSdl() { + if (g_sdlUp) return true; + SDL_SetAppMetadata("WrongGPU", "0.6", "org.wronggpu.WrongGPU"); + SDL_SetHint(SDL_HINT_APP_ID, "WrongGPU"); + SDL_SetHint(SDL_HINT_VIDEO_ALLOW_SCREENSAVER, "1"); + SDL_SetHint(SDL_HINT_QUIT_ON_LAST_WINDOW_CLOSE, "0"); + if (!SDL_Init(SDL_INIT_VIDEO)) return false; + g_wakeType = SDL_RegisterEvents(1); + g_sdlUp = true; + return true; +} + +Win* FindLocked(HWND h) { + auto it = g_wins.find((uintptr_t)h); + return it == g_wins.end() ? nullptr : it->second.get(); +} + +void Wake() { + g_cv.notify_all(); + if (g_sdlUp && !g_wakePending.exchange(true)) { + SDL_Event e; + SDL_zero(e); + e.type = g_wakeType; + SDL_PushEvent(&e); + } +} + +// input: made from an SDL event on the UI thread, so it carries the keys and buttons as that event left them; a post from another +// thread has no pointer position (g_mouse is the UI thread's) and leaves the key state as it was +void Enqueue(HWND h, UINT m, WPARAM wp, LPARAM lp, bool input = false) { + const bool ui = OnUiThread(); + Queued q{}; + q.msg.hwnd = h; q.msg.message = m; q.msg.wParam = wp; q.msg.lParam = lp; q.msg.time = (DWORD)NowMs(); + q.msg.pt = ui ? g_mouse : POINT{0, 0}; + if (input && ui) { q.hasSnap = true; q.snap.down = g_down; q.snap.btn = g_btn; } + { + std::lock_guard l(g_mu); + g_q.push_back(q); + } + Wake(); +} + +std::wstring Lower(const std::wstring& s) { + std::wstring o = s; + for (auto& c : o) c = (wchar_t)towlower(c); + return o; +} + +HWND Hw(const Win* w) { return (HWND)w->id; } + +Win* TopWin(Win* w) { + while (w && w->parent) w = Find((HWND)w->parent); + return w; +} + +// ---- geometry --------------------------------------------------------------------------------------------------------------- +float DensityGuess(SDL_DisplayID d) { + // before a window exists: window units are pixels on X11, points (scaled by the display) on Wayland + const char* drv = SDL_GetCurrentVideoDriver(); + if (drv && !strcmp(drv, "wayland")) { const float s = SDL_GetDisplayContentScale(d); return s > 0 ? s : 1.f; } + return 1.f; +} + +#ifdef WRONGGPU_TESTING +float g_testDensity = 0; // a test's stand-in for a display scale change the offscreen driver cannot make (0: the real one) +#endif +float PixelDensityOf(SDL_Window* s) { +#ifdef WRONGGPU_TESTING + if (g_testDensity > 0) return g_testDensity; +#endif + return SDL_GetWindowPixelDensity(s); +} + +void SdlSizePx(Win* w, int& pw, int& ph) { + pw = ph = 0; + if (!w->sdl) return; +#ifdef WRONGGPU_TESTING + if (g_testDensity > 0) { + SDL_GetWindowSize(w->sdl, &pw, &ph); + pw = (int)std::lround(pw * g_testDensity); ph = (int)std::lround(ph * g_testDensity); + return; + } +#endif + SDL_GetWindowSizeInPixels(w->sdl, &pw, &ph); +} + +POINT OriginOf(Win* w) { // the client area's corner on the screen + if (!w) return POINT{0, 0}; + if (w->parent) { + Win* p = Find((HWND)w->parent); + POINT o = OriginOf(p); + return POINT{o.x + w->x, o.y + w->y}; + } + if (w->sdl) { + int x = 0, y = 0; + SDL_GetWindowPosition(w->sdl, &x, &y); + return POINT{(LONG)std::lround(x * w->density), (LONG)std::lround(y * w->density)}; + } + return POINT{w->x, w->y}; +} + +void ClientSize(Win* w, int& cw, int& ch) { + if (w->sdl) SdlSizePx(w, cw, ch); + else { cw = w->w; ch = w->h; } +} + +void RefreshDensity(Win* w) { if (w->sdl) w->density = std::max(0.5f, PixelDensityOf(w->sdl)); } + +UINT DpiOf(Win* w) { + Win* t = TopWin(w); + if (t && t->sdl) { +#ifdef WRONGGPU_TESTING + const float s = g_testDensity > 0 ? g_testDensity : SDL_GetWindowDisplayScale(t->sdl); +#else + const float s = SDL_GetWindowDisplayScale(t->sdl); +#endif + if (s > 0.25f) return (UINT)std::lround(96 * s); + } + return 96; +} + +} // namespace + +Win* Find(HWND h) { + std::lock_guard l(g_mu); + return FindLocked(h); +} +POINT ClientOriginOnScreen(Win* w) { return OriginOf(w); } +HWND TopOf(Win* w) { Win* t = TopWin(w); return t ? Hw(t) : nullptr; } + +void InvalidateWin(Win* w) { + Win* t = TopWin(w); + if (t) t->invalid = true; + Wake(); +} + +namespace { + +// ---- sending: the subclass chain, then the class --------------------------------------------------------------------------------------- +LRESULT ClassProc(Win* w, UINT m, WPARAM wp, LPARAM lp) { + if (w->builtinEdit) return EditClassProc(w, m, wp, lp); + if (w->proc) return w->proc(Hw(w), m, wp, lp); + return DefWindowProcW(Hw(w), m, wp, lp); +} + +// ---- keys ---------------------------------------------------------------------------------------------------------------------- +WPARAM VkOf(SDL_Keycode k) { + if (k >= 'a' && k <= 'z') return (WPARAM)(k - 'a' + 'A'); + if (k >= '0' && k <= '9') return (WPARAM)k; + if (k >= SDLK_F1 && k <= SDLK_F12) return (WPARAM)(0x70 + (k - SDLK_F1)); + if (k >= SDLK_KP_1 && k <= SDLK_KP_9) return (WPARAM)(0x61 + (k - SDLK_KP_1)); + switch (k) { + case SDLK_KP_0: return 0x60; + case SDLK_RETURN: case SDLK_KP_ENTER: return VK_RETURN; + case SDLK_ESCAPE: return VK_ESCAPE; + case SDLK_TAB: return VK_TAB; + case SDLK_BACKSPACE: return VK_BACK; + case SDLK_SPACE: return VK_SPACE; + case SDLK_LEFT: return VK_LEFT; + case SDLK_RIGHT: return VK_RIGHT; + case SDLK_UP: return VK_UP; + case SDLK_DOWN: return VK_DOWN; + case SDLK_HOME: return VK_HOME; + case SDLK_END: return VK_END; + case SDLK_PAGEUP: return VK_PRIOR; + case SDLK_PAGEDOWN: return VK_NEXT; + case SDLK_DELETE: return VK_DELETE; + case SDLK_INSERT: return VK_INSERT; + case SDLK_LSHIFT: case SDLK_RSHIFT: return VK_SHIFT; + case SDLK_LCTRL: case SDLK_RCTRL: return VK_CONTROL; + case SDLK_LALT: case SDLK_RALT: return VK_MENU; + case SDLK_AC_BACK: return VK_BROWSER_BACK; + case SDLK_GRAVE: return VK_OEM_3; + case SDLK_MINUS: return 0xBD; + case SDLK_EQUALS: return 0xBB; + case SDLK_COMMA: return 0xBC; + case SDLK_PERIOD: return 0xBE; + case SDLK_SLASH: return 0xBF; + case SDLK_SEMICOLON: return 0xBA; + case SDLK_APOSTROPHE: return 0xDE; + case SDLK_LEFTBRACKET: return 0xDB; + case SDLK_RIGHTBRACKET: return 0xDD; + case SDLK_BACKSLASH: return 0xDC; + default: return 0; + } +} + +void SetMods(SDL_Keymod mod) { + g_down[VK_SHIFT] = (mod & SDL_KMOD_SHIFT) != 0; + g_down[VK_CONTROL] = (mod & SDL_KMOD_CTRL) != 0; + g_down[VK_MENU] = (mod & SDL_KMOD_ALT) != 0; +} + +UINT KeyStates() { + return (g_btn & MK_LBUTTON) | (g_btn & MK_RBUTTON) | (g_btn & MK_MBUTTON) | (g_down[VK_SHIFT] ? MK_SHIFT : 0) | (g_down[VK_CONTROL] ? MK_CONTROL : 0); +} + +// ---- the window under a point ---------------------------------------------------------------------------------------------------------------- +Win* ChildAt(Win* top, int px, int py, int& rx, int& ry) { // the deepest visible child holding the point (client pixels of top) + rx = px; ry = py; + Win* best = top; + std::vector kids; + { + std::lock_guard l(g_mu); + for (auto& e : g_wins) if (e.second->parent == top->id && e.second->visible) kids.push_back(e.second.get()); + } + std::sort(kids.begin(), kids.end(), [](Win* a, Win* b) { return a->id > b->id; }); // the newest on top + for (Win* k : kids) + if (px >= k->x && py >= k->y && px < k->x + k->w && py < k->y + k->h) { best = k; rx = px - k->x; ry = py - k->y; break; } + return best; +} + +HCURSOR CursorFor(LPCWSTR id) { return (HCURSOR)(uintptr_t)(uint16_t)(uintptr_t)id; } + +// ---- SDL events to messages --------------------------------------------------------------------------------------------------------------- + +LRESULT HitTest(Win* top, int px, int py) { + const POINT o = OriginOf(top); + return Send(Hw(top), WM_NCHITTEST, 0, MAKELPARAM((short)(o.x + px), (short)(o.y + py))); +} + +void StateSize(Win* w, bool force) { + int pw = 0, ph = 0; + SdlSizePx(w, pw, ph); + if (!force && pw == w->w && ph == w->h) return; + w->w = pw; w->h = ph; + const WPARAM st = w->minimized ? SIZE_MINIMIZED : w->maximized ? SIZE_MAXIMIZED : SIZE_RESTORED; + Enqueue(Hw(w), WM_SIZE, st, MAKELPARAM((WORD)pw, (WORD)ph)); +} + +void Activate(Win* top, bool on) { + if (on) { + if (g_active == Hw(top)) return; + g_active = Hw(top); + Send(Hw(top), WM_NCACTIVATE, TRUE, 0); + Send(Hw(top), WM_ACTIVATE, WA_ACTIVE, 0); + } else { + if (g_active != Hw(top)) return; + Send(Hw(top), WM_NCACTIVATE, FALSE, 0); + Send(Hw(top), WM_ACTIVATE, WA_INACTIVE, 0); // the focus window is still known to it here + g_active = nullptr; + if (g_focus) { + const HWND old = g_focus; + g_focus = nullptr; + Send(old, WM_KILLFOCUS, 0, 0); + ShowTextInput(false, top); + } + } +} + +void TranslateMouse(const SDL_Event& e) { + SDL_WindowID wid = 0; + float fx = 0, fy = 0; + switch (e.type) { + case SDL_EVENT_MOUSE_MOTION: wid = e.motion.windowID; fx = e.motion.x; fy = e.motion.y; break; + case SDL_EVENT_MOUSE_BUTTON_DOWN: case SDL_EVENT_MOUSE_BUTTON_UP: wid = e.button.windowID; fx = e.button.x; fy = e.button.y; break; + case SDL_EVENT_MOUSE_WHEEL: wid = e.wheel.windowID; fx = e.wheel.mouse_x; fy = e.wheel.mouse_y; break; + default: return; + } + Win* top = nullptr; + { + std::lock_guard l(g_mu); + auto it = g_bySdl.find(wid); + if (it != g_bySdl.end()) top = FindLocked((HWND)it->second); + } + if (!top) return; + const int px = (int)std::lround(fx * top->density), py = (int)std::lround(fy * top->density); + const POINT o = OriginOf(top); + g_mouse = POINT{o.x + px, o.y + py}; + int rx = px, ry = py; + Win* target = ChildAt(top, px, py, rx, ry); + if (g_capture) { // the capture window gets it all, in its own coordinates + if (Win* c = Find(g_capture)) { + const POINT co = OriginOf(c); + target = c; rx = g_mouse.x - co.x; ry = g_mouse.y - co.y; + } + } + const LRESULT ht = target == top && !g_capture ? HitTest(top, px, py) : HTCLIENT; + const bool nc = ht != HTCLIENT; + const LPARAM scr = MAKELPARAM((short)g_mouse.x, (short)g_mouse.y), cli = MAKELPARAM((short)rx, (short)ry); + + if (e.type == SDL_EVENT_MOUSE_WHEEL) { + const int delta = (int)std::lround(e.wheel.y * WHEEL_DELTA * (e.wheel.direction == SDL_MOUSEWHEEL_FLIPPED ? -1 : 1)); + if (delta) Enqueue(Hw(target), WM_MOUSEWHEEL, MAKEWPARAM((WORD)KeyStates(), (WORD)(short)delta), scr, true); + return; + } + if (e.type == SDL_EVENT_MOUSE_MOTION) { + // moving between the client area and the caption: the leave messages the app asked for with TrackMouseEvent + if (nc && top->trackLeave && !g_capture) { top->trackLeave = false; Enqueue(Hw(top), WM_MOUSELEAVE, 0, 0, true); } + if (!nc && top->trackNcLeave) { top->trackNcLeave = false; Enqueue(Hw(top), WM_NCMOUSELEAVE, 0, 0, true); } + Enqueue(Hw(target), WM_SETCURSOR, (WPARAM)Hw(target), MAKELPARAM((WORD)ht, WM_MOUSEMOVE), true); + if (nc) Enqueue(Hw(top), WM_NCMOUSEMOVE, (WPARAM)ht, scr, true); + else Enqueue(Hw(target), WM_MOUSEMOVE, KeyStates(), cli, true); + return; + } + const bool down = e.type == SDL_EVENT_MOUSE_BUTTON_DOWN; + const int b = e.button.button; + const int clicks = e.button.clicks; + if (b == SDL_BUTTON_LEFT) { + if (down) g_btn |= MK_LBUTTON; else g_btn &= ~MK_LBUTTON; + g_down[VK_LBUTTON] = down; + if (nc) { + if (down) Enqueue(Hw(top), clicks >= 2 ? WM_NCLBUTTONDBLCLK : WM_NCLBUTTONDOWN, (WPARAM)ht, scr, true); + else Enqueue(Hw(top), WM_NCLBUTTONUP, (WPARAM)ht, scr, true); + } else { + Enqueue(Hw(target), down ? (clicks >= 2 ? WM_LBUTTONDBLCLK : WM_LBUTTONDOWN) : WM_LBUTTONUP, KeyStates(), cli, true); + } + } else if (b == SDL_BUTTON_RIGHT) { + if (down) g_btn |= MK_RBUTTON; else g_btn &= ~MK_RBUTTON; + if (!nc) Enqueue(Hw(target), down ? WM_RBUTTONDOWN : WM_RBUTTONUP, KeyStates(), cli, true); + } else if (b == SDL_BUTTON_MIDDLE) { + if (down) g_btn |= MK_MBUTTON; else g_btn &= ~MK_MBUTTON; + if (!nc) Enqueue(Hw(target), down ? WM_MBUTTONDOWN : WM_MBUTTONUP, KeyStates(), cli, true); + } else if (b == SDL_BUTTON_X1 || b == SDL_BUTTON_X2) { + if (!nc) Enqueue(Hw(target), down ? WM_XBUTTONDOWN : WM_XBUTTONUP, MAKEWPARAM((WORD)KeyStates(), (WORD)(b == SDL_BUTTON_X1 ? XBUTTON1 : XBUTTON2)), cli, true); + } +} + +void TranslateKey(const SDL_Event& e) { + const bool down = e.type == SDL_EVENT_KEY_DOWN; + SetMods(e.key.mod); + const WPARAM vk = VkOf(e.key.key); + if (!vk) return; + if (vk != VK_SHIFT && vk != VK_CONTROL && vk != VK_MENU) g_down[vk & 255] = down; + Win* top = nullptr; + { + std::lock_guard l(g_mu); + auto it = g_bySdl.find(e.key.windowID); + if (it != g_bySdl.end()) top = FindLocked((HWND)it->second); + } + HWND target = g_focus && Find(g_focus) ? g_focus : top ? Hw(top) : nullptr; + if (!target) return; + const bool alt = (e.key.mod & SDL_KMOD_ALT) != 0 || vk == VK_MENU || vk == 0x79; + LPARAM lp = 1 | ((LPARAM)(e.key.scancode & 0xFF) << 16); + if (e.key.repeat) lp |= 1 << 30; + if (alt && (e.key.mod & SDL_KMOD_ALT)) lp |= 1 << 29; + if (!down) lp |= (1 << 30) | ((LPARAM)1 << 31); + const UINT m = down ? (alt ? WM_SYSKEYDOWN : WM_KEYDOWN) : (alt ? WM_SYSKEYUP : WM_KEYUP); + Enqueue(target, m, vk, lp, true); +} + +void TranslateText(const SDL_Event& e) { + HWND target = g_focus && Find(g_focus) ? g_focus : nullptr; + if (!target) return; + const char* s = e.text.text; + while (s && *s) { + uint32_t c = (unsigned char)*s++; + int extra = c >= 0xF0 ? 3 : c >= 0xE0 ? 2 : c >= 0xC0 ? 1 : 0; + c = extra == 3 ? c & 7 : extra == 2 ? c & 15 : extra == 1 ? c & 31 : c; + while (extra-- > 0 && *s) c = (c << 6) | ((unsigned char)*s++ & 63); + Enqueue(target, WM_CHAR, (WPARAM)c, 1, true); + } +} + +void TranslateWindow(const SDL_Event& e) { + Win* w = nullptr; + { + std::lock_guard l(g_mu); + auto it = g_bySdl.find(e.window.windowID); + if (it != g_bySdl.end()) w = FindLocked((HWND)it->second); + } + if (!w) return; + switch (e.type) { + case SDL_EVENT_WINDOW_CLOSE_REQUESTED: Enqueue(Hw(w), WM_CLOSE, 0, 0); break; + case SDL_EVENT_WINDOW_RESIZED: case SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED: RefreshDensity(w); StateSize(w, false); break; + case SDL_EVENT_WINDOW_MOVED: { + const POINT o = OriginOf(w); + Enqueue(Hw(w), WM_MOVE, 0, MAKELPARAM((short)o.x, (short)o.y)); + break; + } + case SDL_EVENT_WINDOW_MAXIMIZED: w->maximized = true; w->minimized = false; StateSize(w, true); break; + case SDL_EVENT_WINDOW_MINIMIZED: w->minimized = true; StateSize(w, true); break; + case SDL_EVENT_WINDOW_RESTORED: w->maximized = false; w->minimized = false; StateSize(w, true); break; + case SDL_EVENT_WINDOW_EXPOSED: w->invalid = true; break; + case SDL_EVENT_WINDOW_FOCUS_GAINED: Activate(w, true); break; + case SDL_EVENT_WINDOW_FOCUS_LOST: Activate(w, false); break; + case SDL_EVENT_WINDOW_MOUSE_LEAVE: + if (w->trackLeave && !g_capture) { w->trackLeave = false; Enqueue(Hw(w), WM_MOUSELEAVE, 0, 0); } + break; + case SDL_EVENT_WINDOW_DISPLAY_SCALE_CHANGED: case SDL_EVENT_WINDOW_DISPLAY_CHANGED: { + RefreshDensity(w); // before the rect: SetWindowPos and the mouse turn units to pixels with it + const POINT o = OriginOf(w); + int pw = 0, ph = 0; + SdlSizePx(w, pw, ph); + w->dpiRect = RECT{o.x, o.y, o.x + pw, o.y + ph}; // handed over by pointer: the window's own, whatever else is queued + const UINT dpi = DpiOf(w); + { + // one WM_DPICHANGED per window at a time: a scale change while the last one is still queued (a filtered peek + // left it there) updates it, so its DPI and the rect it points to always describe the same, latest scale + std::lock_guard l(g_mu); + for (Queued& q : g_q) + if (q.msg.hwnd == Hw(w) && q.msg.message == WM_DPICHANGED) { + q.msg.wParam = MAKEWPARAM((WORD)dpi, (WORD)dpi); + return; + } + } + Enqueue(Hw(w), WM_DPICHANGED, MAKEWPARAM((WORD)dpi, (WORD)dpi), (LPARAM)&w->dpiRect); + break; + } + default: break; + } +} + +void Translate(const SDL_Event& e) { + if (e.type == g_wakeType && g_wakeType) { g_wakePending = false; return; } + switch (e.type) { + case SDL_EVENT_MOUSE_MOTION: case SDL_EVENT_MOUSE_BUTTON_DOWN: case SDL_EVENT_MOUSE_BUTTON_UP: case SDL_EVENT_MOUSE_WHEEL: TranslateMouse(e); break; + case SDL_EVENT_KEY_DOWN: case SDL_EVENT_KEY_UP: TranslateKey(e); break; + case SDL_EVENT_TEXT_INPUT: TranslateText(e); break; + case SDL_EVENT_QUIT: { // a signal (Ctrl+C, SIGTERM): the windows are asked to close, as a close button would + std::vector tops; + { + std::lock_guard l(g_mu); + for (auto& x : g_wins) if (!x.second->parent && x.second->sdl) tops.push_back(Hw(x.second.get())); + } + for (HWND h : tops) Enqueue(h, WM_CLOSE, 0, 0); + break; + } + default: + if (e.type >= SDL_EVENT_WINDOW_FIRST && e.type <= SDL_EVENT_WINDOW_LAST) TranslateWindow(e); + break; + } +} + +void PumpSdl(int waitMs) { + if (!g_sdlUp) return; + SDL_Event e; + if (waitMs > 0) { + if (SDL_WaitEventTimeout(&e, waitMs)) Translate(e); + else return; + } + while (SDL_PollEvent(&e)) Translate(e); +} + +// ---- the scripted input of a test build --------------------------------------------------------------------------------------------------- +#ifdef WRONGGPU_TESTING +struct Script { + bool loaded = false, done = false; + std::vector lines; + size_t next = 0; + uint64_t waitUntil = 0; + float mx = 0, my = 0; // the pointer, in client DIPs + int retries = 0; +}; +Script g_script; + +SDL_WindowID MainSdlId() { + std::lock_guard l(g_mu); + SDL_WindowID best = 0; + uintptr_t bestId = ~(uintptr_t)0; + for (auto& e : g_bySdl) if (e.second < bestId) { bestId = e.second; best = e.first; } + return best; +} + +void PushMouse(SDL_EventType t, float x, float y, int button, int clicks) { + const SDL_WindowID mainId = MainSdlId(); + Win* top = nullptr; + { std::lock_guard l(g_mu); auto it = g_bySdl.find(mainId); if (it != g_bySdl.end()) top = FindLocked((HWND)it->second); } + if (!top) return; + const float k = DpiOf(top) / 96.f / top->density; // DIPs to SDL window units + SDL_Event e; + SDL_zero(e); + e.type = t; + if (t == SDL_EVENT_MOUSE_MOTION) { e.motion.windowID = MainSdlId(); e.motion.x = x * k; e.motion.y = y * k; } + else if (t == SDL_EVENT_MOUSE_WHEEL) { e.wheel.windowID = MainSdlId(); e.wheel.mouse_x = x * k; e.wheel.mouse_y = y * k; e.wheel.y = (float)button; } + else { e.button.windowID = MainSdlId(); e.button.x = x * k; e.button.y = y * k; e.button.button = (Uint8)button; e.button.clicks = (Uint8)clicks; e.button.down = t == SDL_EVENT_MOUSE_BUTTON_DOWN; } + SDL_PushEvent(&e); +} + +void PushKey(SDL_Keycode k, SDL_Keymod mod, bool down) { + SDL_Event e; + SDL_zero(e); + e.type = down ? SDL_EVENT_KEY_DOWN : SDL_EVENT_KEY_UP; + e.key.windowID = MainSdlId(); + e.key.key = k; e.key.mod = mod; e.key.down = down; + SDL_PushEvent(&e); +} + +SDL_Keycode KeyByName(const std::string& n) { + static const std::map t = { + {"return", SDLK_RETURN}, {"escape", SDLK_ESCAPE}, {"tab", SDLK_TAB}, {"backspace", SDLK_BACKSPACE}, {"left", SDLK_LEFT}, {"right", SDLK_RIGHT}, + {"up", SDLK_UP}, {"down", SDLK_DOWN}, {"home", SDLK_HOME}, {"end", SDLK_END}, {"delete", SDLK_DELETE}, {"space", SDLK_SPACE}, + {"pagedown", SDLK_PAGEDOWN}, {"pageup", SDLK_PAGEUP}}; + auto it = t.find(n); + if (it != t.end()) return it->second; + return n.size() == 1 ? (SDL_Keycode)n[0] : SDLK_UNKNOWN; +} + +bool ScriptPending() { return g_script.loaded && !g_script.done && g_script.next < g_script.lines.size(); } + +void ScriptClickImpl(float x, float y) { + g_script.mx = x; g_script.my = y; + PushMouse(SDL_EVENT_MOUSE_MOTION, x, y, 0, 0); + PushMouse(SDL_EVENT_MOUSE_BUTTON_DOWN, x, y, SDL_BUTTON_LEFT, 1); + PushMouse(SDL_EVENT_MOUSE_BUTTON_UP, x, y, SDL_BUTTON_LEFT, 1); +} + +// one line per step: wait MS | until WHAT (the hook) | clickname NAME (the hook) | move X Y | click X Y | dclick X Y | wheel N | key NAME | key ctrl+NAME | key shift+NAME | text WORDS | shot FILE | dump FILE | close +bool RunScriptStep() { + Script& s = g_script; + if (!s.loaded) { + s.loaded = true; + if (const char* f = getenv("WRONGGPU_UI_SCRIPT")) { + FILE* fp = fopen(f, "r"); + if (!fp) { fprintf(stderr, "wronggpu: cannot read the script %s\n", f); s.done = true; return false; } + char b[4096]; + while (fgets(b, sizeof b, fp)) { + std::string l = b; + while (!l.empty() && (l.back() == '\n' || l.back() == '\r')) l.pop_back(); + if (!l.empty() && l[0] != '#') s.lines.push_back(l); + } + fclose(fp); + } else s.done = true; + } + if (s.done || !g_sdlUp || s.next >= s.lines.size() || NowMs() < s.waitUntil) return false; + if (MainSdlId() == 0) return false; + const std::string l = s.lines[s.next++]; + const size_t sp = l.find(' '); + const std::string cmd = l.substr(0, sp), arg = sp == std::string::npos ? "" : l.substr(sp + 1); + float x = 0, y = 0; + if (cmd == "wait") s.waitUntil = NowMs() + (uint64_t)atoi(arg.c_str()); + else if (cmd == "move" && sscanf(arg.c_str(), "%f %f", &x, &y) == 2) { s.mx = x; s.my = y; PushMouse(SDL_EVENT_MOUSE_MOTION, x, y, 0, 0); } + else if ((cmd == "click" || cmd == "dclick") && sscanf(arg.c_str(), "%f %f", &x, &y) == 2) { + s.mx = x; s.my = y; + PushMouse(SDL_EVENT_MOUSE_MOTION, x, y, 0, 0); + PushMouse(SDL_EVENT_MOUSE_BUTTON_DOWN, x, y, SDL_BUTTON_LEFT, 1); + PushMouse(SDL_EVENT_MOUSE_BUTTON_UP, x, y, SDL_BUTTON_LEFT, 1); + if (cmd == "dclick") { + PushMouse(SDL_EVENT_MOUSE_BUTTON_DOWN, x, y, SDL_BUTTON_LEFT, 2); + PushMouse(SDL_EVENT_MOUSE_BUTTON_UP, x, y, SDL_BUTTON_LEFT, 2); + } + s.waitUntil = NowMs() + 150; + } + else if (cmd == "wheel") { PushMouse(SDL_EVENT_MOUSE_WHEEL, s.mx, s.my, atoi(arg.c_str()), 0); s.waitUntil = NowMs() + 100; } + else if (cmd == "key") { + SDL_Keymod mod = SDL_KMOD_NONE; + std::string n = arg; + for (;;) { + if (n.rfind("ctrl+", 0) == 0) { mod = (SDL_Keymod)(mod | SDL_KMOD_LCTRL); n = n.substr(5); } + else if (n.rfind("shift+", 0) == 0) { mod = (SDL_Keymod)(mod | SDL_KMOD_LSHIFT); n = n.substr(6); } + else if (n.rfind("alt+", 0) == 0) { mod = (SDL_Keymod)(mod | SDL_KMOD_LALT); n = n.substr(4); } + else break; + } + const SDL_Keycode k = KeyByName(n); + PushKey(k, mod, true); + PushKey(k, mod, false); + s.waitUntil = NowMs() + 60; + } + else if (cmd == "text") { + SDL_Event e; + SDL_zero(e); + e.type = SDL_EVENT_TEXT_INPUT; + e.text.windowID = MainSdlId(); + static std::string keep; // the event's text pointer must outlive the push + keep = arg; + e.text.text = keep.c_str(); + SDL_PushEvent(&e); + s.waitUntil = NowMs() + 100; + } + else if ((cmd == "shot" || cmd == "dump" || cmd == "clickname") && Hook()) { Hook()(l); s.waitUntil = NowMs() + 150; } + else if (cmd == "until" && Hook()) { + if (!Hook()(l)) { // not yet: asked again soon + --s.next; + s.waitUntil = NowMs() + 100; + if (++s.retries > 300) { fprintf(stderr, "wronggpu: script condition never came true: %s\n", l.c_str()); ++s.next; s.retries = 0; } + } else s.retries = 0; + } + else if (cmd == "close") { + SDL_Event e; + SDL_zero(e); + e.type = SDL_EVENT_WINDOW_CLOSE_REQUESTED; + e.window.windowID = MainSdlId(); + SDL_PushEvent(&e); + s.waitUntil = NowMs() + 200; + } else fprintf(stderr, "wronggpu: script line not understood: %s\n", l.c_str()); + return true; +} +#else +bool RunScriptStep() { return false; } +bool ScriptPending() { return false; } +#endif + +// ---- timers and paints ----------------------------------------------------------------------------------------------------------- +constexpr uint64_t kPaintGapMs = 14; // frames are at most ~70 a second (a swap chain's wait for the display has no counterpart here) + +// the message filter of GetMessageW and PeekMessageW: a window (null: any) and a range (0, 0: any) +bool Wanted(HWND fh, UINT lo, UINT hi, HWND h, UINT m) { + return (!fh || fh == h) && ((lo == 0 && hi == 0) || (m >= lo && m <= hi)); +} + +// remove: the timer moves on to its next period; a message only looked at (PM_NOREMOVE) stays due +bool TakeTimer(MSG* out, uint64_t now, bool remove, HWND fh, UINT lo, UINT hi) { + std::lock_guard l(g_mu); + for (auto& t : g_timers) { + if (t.due > now || !Wanted(fh, lo, hi, (HWND)t.hwnd, WM_TIMER)) continue; + if (remove) t.due = now + t.interval; + out->hwnd = (HWND)t.hwnd; out->message = WM_TIMER; out->wParam = t.id; out->lParam = (LPARAM)t.proc; out->time = (DWORD)now; out->pt = g_mouse; + return true; + } + return false; +} + +bool TakePaint(MSG* out, uint64_t now, HWND fh, UINT lo, UINT hi) { + std::lock_guard l(g_mu); + for (auto& e : g_wins) { + Win* w = e.second.get(); + if (w->parent || w->messageOnly || !w->visible || !w->invalid || w->minimized) continue; + if (now < w->lastPaintMs + kPaintGapMs || !Wanted(fh, lo, hi, Hw(w), WM_PAINT)) continue; + out->hwnd = Hw(w); out->message = WM_PAINT; out->wParam = 0; out->lParam = 0; out->time = (DWORD)now; out->pt = g_mouse; + return true; + } + return false; +} + +// the time until something is due (timers, a paint held back by the frame gap): -1 for nothing +int64_t NextDueMs(uint64_t now) { + int64_t best = -1; + std::lock_guard l(g_mu); + for (auto& t : g_timers) { const int64_t d = std::max(0, (int64_t)t.due - (int64_t)now); if (best < 0 || d < best) best = d; } + for (auto& e : g_wins) { + Win* w = e.second.get(); + if (w->parent || w->messageOnly || !w->visible || !w->invalid || w->minimized) continue; + const int64_t d = std::max(1, (int64_t)(w->lastPaintMs + kPaintGapMs) - (int64_t)now); + if (best < 0 || d < best) best = d; + } + return best; +} + +// the first queued message the filter wants; remove: taken off the queue, and the keys it carries become what GetKeyState reports +bool TakeQueued(MSG* out, bool remove, HWND fh, UINT lo, UINT hi) { + std::lock_guard l(g_mu); + for (auto it = g_q.begin(); it != g_q.end(); ++it) { + if (!Wanted(fh, lo, hi, it->msg.hwnd, it->msg.message)) continue; + *out = it->msg; + if (remove) { + if (it->hasSnap) g_cur = it->snap; + g_q.erase(it); + } + return true; + } + return false; +} + +// the next message, taking SDL's events, paints and timers in as Windows orders them: posted and input first, then WM_QUIT, then +// WM_PAINT, then WM_TIMER. block: wait for one (GetMessage) or return false (PeekMessage). remove: take it off the queue. fh, lo, hi: the +// window and message range wanted. +bool NextMessage(MSG* out, bool block, bool remove, HWND fh = nullptr, UINT lo = 0, UINT hi = 0) { + NoteUiThread(); + for (;;) { + if (TakeQueued(out, remove, fh, lo, hi)) return true; + PumpSdl(0); + if (RunScriptStep()) continue; + if (TakeQueued(out, remove, fh, lo, hi)) return true; + const uint64_t now = NowMs(); + if (g_quit && !fh && Wanted(nullptr, lo, hi, nullptr, WM_QUIT)) { // a thread message: for no window in particular + if (remove) g_quit = false; + *out = MSG{}; + out->message = WM_QUIT; out->wParam = (WPARAM)g_quitCode; + return true; + } + if (TakePaint(out, now, fh, lo, hi)) return true; + if (TakeTimer(out, now, remove, fh, lo, hi)) return true; + if (!block) return false; + int64_t wait = NextDueMs(now); + if (ScriptPending()) wait = wait < 0 ? 20 : std::min(wait, 20); // a script step + if (wait < 0) wait = 1000; + if (g_sdlUp) PumpSdl((int)std::max(1, wait)); + else { + std::unique_lock l(g_mu); + g_cv.wait_for(l, std::chrono::milliseconds(std::max(1, wait)), [] { return !g_q.empty() || g_quit; }); + } + } +} + +} // namespace + +// ---- the public entry the Linux Gfx and the test hook use ---------------------------------------------------------------------------------- +bool Present(HWND hh, const uint8_t* bgra, int w, int h, int stride) { + Win* t = Find(hh); + if (!t || !t->sdl || !bgra) return false; + SDL_Surface* s = SDL_GetWindowSurface(t->sdl); + if (!s || s->w != w || s->h != h) return false; + if (SDL_MUSTLOCK(s) && !SDL_LockSurface(s)) return false; + const bool ok = SDL_ConvertPixels(w, h, SDL_PIXELFORMAT_ARGB8888, bgra, stride, s->format, s->pixels, s->pitch); + if (SDL_MUSTLOCK(s)) SDL_UnlockSurface(s); + if (!ok) return false; + return SDL_UpdateWindowSurface(t->sdl); +} + +void SetIcon(HWND hh, const uint8_t* bgra, int w, int h) { // straight alpha, BGRA + Win* t = Find(hh); + if (!t || !t->sdl || !bgra) return; + SDL_Surface* s = SDL_CreateSurfaceFrom(w, h, SDL_PIXELFORMAT_ARGB8888, const_cast(bgra), w * 4); + if (!s) return; + SDL_SetWindowIcon(t->sdl, s); + SDL_DestroySurface(s); +} + +// The text last set while SDL is not up (a headless run: the dump reads back what a Copy button put there) +static std::wstring g_clipHeld; +std::wstring ClipGet() { + if (!g_sdlUp) return g_clipHeld; + char* t = SDL_GetClipboardText(); + std::wstring w = t ? wgposix::FromUtf8(t, strlen(t)) : L""; + SDL_free(t); + return w; +} +void ClipSet(const std::wstring& text) { + g_clipHeld = text; + if (g_sdlUp) SDL_SetClipboardText(wgposix::ToUtf8(text).c_str()); +} + +void SetEditMeasure(std::function f) { g_measure = std::move(f); } +float EditMeasure(const std::wstring& text, int fontPx, int upTo) { + if (g_measure) return g_measure(text, fontPx, upTo); + return (float)upTo * fontPx * 0.55f; +} +#ifdef WRONGGPU_TESTING +void TestSetPixelDensity(float d) { g_testDensity = d; } +#endif +void SetScriptHook(std::function f) { Hook() = std::move(f); } +#ifdef WRONGGPU_TESTING +void ScriptClick(float x, float y) { ScriptClickImpl(x, y); } +#else +void ScriptClick(float, float) {} +#endif + +void EditViews(HWND parent, std::vector& out) { + out.clear(); + std::vector kids; + { + std::lock_guard l(g_mu); + for (auto& e : g_wins) if (e.second->parent == (uintptr_t)parent && e.second->builtinEdit && e.second->visible) kids.push_back(e.second.get()); + } + std::sort(kids.begin(), kids.end(), [](Win* a, Win* b) { return a->id < b->id; }); + for (Win* k : kids) { + EditView v; + v.h = Hw(k); + v.rc = RECT{k->x, k->y, k->x + k->w, k->y + k->h}; + v.text = k->text; + EditState& s = *k->edit; + v.selStart = std::min(s.anchor, s.caret); v.selEnd = std::max(s.anchor, s.caret); v.caret = s.caret; + v.cue = s.cue; v.marginL = s.marginL; v.marginR = s.marginR; v.fontPx = s.fontPx; v.scroll = s.scroll; + v.focused = g_focus == Hw(k); + v.caretOn = v.focused && ((NowMs() - s.lastInputMs) % 1060 < 530 || NowMs() - s.lastInputMs < 530); + out.push_back(std::move(v)); + } +} +void SetEditScroll(HWND h, int scroll) { + if (Win* w = Find(h)) if (w->edit) w->edit->scroll = scroll; +} + +void ShowTextInput(bool on, Win* w) { + Win* t = TopWin(w); + if (!g_sdlUp || !t || !t->sdl) return; + if (on) SDL_StartTextInput(t->sdl); else SDL_StopTextInput(t->sdl); +} + +LRESULT Send(HWND h, UINT m, WPARAM wp, LPARAM lp) { + Win* w = Find(h); + if (!w) return 0; + if (w->subs.empty()) return ClassProc(w, m, wp, lp); + const Sub s = w->subs[0]; + g_depth.push_back({h, 0}); + const LRESULT r = s.proc(h, m, wp, lp, s.id, s.data); + if (!g_depth.empty()) g_depth.pop_back(); + return r; +} + +} // namespace wgwin + +using namespace wgwin; + +// ================================================================================================================================ +// the Win32 calls +// ================================================================================================================================ +ATOM RegisterClassExW(const WNDCLASSEXW* wc) { + if (!wc || !wc->lpszClassName) return 0; + NoteUiThread(); + std::lock_guard l(g_mu); + g_classes[Lower(wc->lpszClassName)] = *wc; + return (ATOM)(g_classes.size() + 0xC000); +} + +namespace { +SDL_HitTestResult HitTestCallback(SDL_Window*, const SDL_Point* area, void* data) { + Win* top = Find((HWND)data); + if (!top) return SDL_HITTEST_NORMAL; + const LRESULT ht = HitTest(top, (int)std::lround(area->x * top->density), (int)std::lround(area->y * top->density)); + switch (ht) { + case HTCAPTION: return SDL_HITTEST_DRAGGABLE; + case HTTOPLEFT: return SDL_HITTEST_RESIZE_TOPLEFT; + case HTTOP: return SDL_HITTEST_RESIZE_TOP; + case HTTOPRIGHT: return SDL_HITTEST_RESIZE_TOPRIGHT; + case HTRIGHT: return SDL_HITTEST_RESIZE_RIGHT; + case HTBOTTOMRIGHT: return SDL_HITTEST_RESIZE_BOTTOMRIGHT; + case HTBOTTOM: return SDL_HITTEST_RESIZE_BOTTOM; + case HTBOTTOMLEFT: return SDL_HITTEST_RESIZE_BOTTOMLEFT; + case HTLEFT: return SDL_HITTEST_RESIZE_LEFT; + default: return SDL_HITTEST_NORMAL; // the client area, and the caption buttons: their clicks come as WM_NC* messages + } +} + +void ApplyMinMax(Win* w) { + if (!w->sdl) return; + MINMAXINFO mm{}; + mm.ptMinTrackSize = POINT{1, 1}; + Send(Hw(w), WM_GETMINMAXINFO, 0, (LPARAM)&mm); + if (mm.ptMinTrackSize.x > 1 || mm.ptMinTrackSize.y > 1) + SDL_SetWindowMinimumSize(w->sdl, (int)std::lround(mm.ptMinTrackSize.x / w->density), (int)std::lround(mm.ptMinTrackSize.y / w->density)); +} +} // namespace + +HWND CreateWindowExW(DWORD exStyle, LPCWSTR cls, LPCWSTR title, DWORD style, int x, int y, int w, int h, HWND parent, HMENU menu, HINSTANCE, LPVOID) { + NoteUiThread(); + auto win = std::make_unique(); + const std::wstring lc = cls ? Lower(cls) : L""; + win->cls = cls ? cls : L""; + win->style = style; win->exStyle = exStyle; + if (lc == L"edit") { + win->builtinEdit = true; + EditInit(win.get()); + EditSetText(win.get(), title ? title : L"", false); // the title is the text, with the caret after it, as WM_SETTEXT leaves it + } else { + win->text = title ? title : L""; + std::lock_guard l(g_mu); + auto it = g_classes.find(lc); + if (it == g_classes.end()) { SetLastError(1407); return nullptr; } // ERROR_CANNOT_FIND_WND_CLASS + win->proc = it->second.lpfnWndProc; + } + win->ctrlId = (LONG_PTR)menu; + const bool child = (style & WS_CHILD) != 0 && parent && parent != HWND_MESSAGE; + if (child) { + if (!Find(parent)) { SetLastError(1400); return nullptr; } + win->parent = (uintptr_t)parent; + win->x = x; win->y = y; win->w = w; win->h = h; + win->visible = (style & WS_VISIBLE) != 0; + } else if (parent == HWND_MESSAGE) { + win->messageOnly = true; + } else { + if (!EnsureSdl()) { fprintf(stderr, "WrongGPU: cannot open a window: %s\n", SDL_GetError()); exit(3); } + SDL_WindowFlags f = SDL_WINDOW_HIDDEN | SDL_WINDOW_BORDERLESS | SDL_WINDOW_HIGH_PIXEL_DENSITY; + if (style & WS_THICKFRAME) f |= SDL_WINDOW_RESIZABLE; + const std::string t8 = wgposix::ToUtf8(title ? title : L""); + win->sdl = SDL_CreateWindow(t8.c_str(), std::max(1, w), std::max(1, h), f); + if (!win->sdl) { fprintf(stderr, "WrongGPU: cannot open a window: %s\n", SDL_GetError()); exit(3); } + win->sdlId = SDL_GetWindowID(win->sdl); + win->density = std::max(0.5f, PixelDensityOf(win->sdl)); + // the size asked for is in pixels: set again in SDL's window units now that the density is known + SDL_SetWindowSize(win->sdl, std::max(1, (int)std::lround(w / win->density)), std::max(1, (int)std::lround(h / win->density))); + if (x != CW_USEDEFAULT && y != CW_USEDEFAULT) SDL_SetWindowPosition(win->sdl, (int)std::lround(x / win->density), (int)std::lround(y / win->density)); + win->w = w; win->h = h; + } + Win* raw = win.get(); + { + std::lock_guard l(g_mu); + raw->id = g_nextId++; + g_wins[raw->id] = std::move(win); + if (raw->sdl) g_bySdl[raw->sdlId] = raw->id; + } + const HWND hw = Hw(raw); + if (raw->sdl) SDL_SetWindowHitTest(raw->sdl, HitTestCallback, hw); + Send(hw, WM_NCCREATE, 0, 0); + Send(hw, WM_CREATE, 0, 0); + return hw; +} + +BOOL IsWindow(HWND h) { return Find(h) != nullptr; } + +BOOL DestroyWindow(HWND h) { + Win* w = Find(h); + if (!w) return FALSE; + std::vector kids; + { + std::lock_guard l(g_mu); + for (auto& e : g_wins) if (e.second->parent == (uintptr_t)h) kids.push_back(Hw(e.second.get())); + } + for (HWND k : kids) DestroyWindow(k); + if (g_capture == h) g_capture = nullptr; + if (g_focus == h) { g_focus = nullptr; } + Send(h, WM_DESTROY, 0, 0); + Send(h, WM_NCDESTROY, 0, 0); + w = Find(h); + if (!w) return TRUE; + if (g_active == h) g_active = nullptr; + SDL_Window* sdl = w->sdl; + unsigned sid = w->sdlId; + { + std::lock_guard l(g_mu); + g_timers.erase(std::remove_if(g_timers.begin(), g_timers.end(), [&](const Timer& t) { return t.hwnd == (uintptr_t)h; }), g_timers.end()); + for (auto it = g_q.begin(); it != g_q.end();) it = it->msg.hwnd == h ? g_q.erase(it) : it + 1; + g_bySdl.erase(sid); + g_wins.erase((uintptr_t)h); + } + if (sdl) SDL_DestroyWindow(sdl); + return TRUE; +} + +HWND FindWindowExW(HWND parent, HWND after, LPCWSTR cls, LPCWSTR) { + std::vector all; + { + std::lock_guard l(g_mu); + for (auto& e : g_wins) if (e.second->parent == (uintptr_t)parent) all.push_back(e.second.get()); + } + std::sort(all.begin(), all.end(), [](Win* a, Win* b) { return a->id < b->id; }); + bool seen = after == nullptr; + for (Win* w : all) { + if (!seen) { if (Hw(w) == after) seen = true; continue; } + if (!cls || Lower(w->cls) == Lower(cls)) return Hw(w); + } + return nullptr; +} +HWND FindWindowW(LPCWSTR cls, LPCWSTR title) { return FindWindowExW(nullptr, nullptr, cls, title); } + +BOOL ShowWindow(HWND h, int cmd) { + Win* w = Find(h); + if (!w) return FALSE; + const bool was = w->visible; + if (cmd == SW_HIDE) { + w->visible = false; + if (w->sdl) SDL_HideWindow(w->sdl); + if (g_focus == h && w->parent) { /* a hidden field keeps no keys: the app moves them */ } + } else if (w->sdl) { + w->visible = true; + if (!was) ApplyMinMax(w); + if (cmd == SW_SHOWMAXIMIZED) { SDL_ShowWindow(w->sdl); SDL_MaximizeWindow(w->sdl); w->maximized = true; } + else if (cmd == SW_SHOWMINNOACTIVE || cmd == SW_MINIMIZE || cmd == SW_SHOWMINIMIZED || cmd == SW_FORCEMINIMIZE) { SDL_ShowWindow(w->sdl); SDL_MinimizeWindow(w->sdl); w->minimized = true; } + else if (cmd == SW_RESTORE) { SDL_RestoreWindow(w->sdl); w->minimized = w->maximized = false; SDL_ShowWindow(w->sdl); } + else { SDL_ShowWindow(w->sdl); if (cmd != SW_SHOWNOACTIVATE && cmd != SW_SHOWNA) SDL_RaiseWindow(w->sdl); } + w->invalid = true; + // a display server that sends no focus event (the offscreen driver) still gets an active window, as Windows has + if (!g_active && !w->minimized && cmd != SW_SHOWNOACTIVATE && cmd != SW_SHOWMINNOACTIVE) Activate(w, true); + if (!was) Send(h, WM_SHOWWINDOW, TRUE, 0); + } else { + w->visible = true; + if (w->builtinEdit) InvalidateWin(w); + } + return was; +} + +BOOL UpdateWindow(HWND h) { + Win* w = Find(h); + if (!w || w->parent || !w->visible || !w->invalid) return TRUE; + Send(h, WM_PAINT, 0, 0); + return TRUE; +} + +BOOL IsWindowVisible(HWND h) { + Win* w = Find(h); + if (!w) return FALSE; + for (Win* p = w; p; p = p->parent ? Find((HWND)p->parent) : nullptr) if (!p->visible) return FALSE; + return TRUE; +} +BOOL IsWindowEnabled(HWND h) { return Find(h) != nullptr; } +BOOL MessageBeep(UINT) { return TRUE; } +BOOL IsIconic(HWND h) { Win* w = Find(h); return w && w->minimized; } +BOOL IsZoomed(HWND h) { Win* w = Find(h); return w && w->maximized; } + +BOOL SetWindowPos(HWND h, HWND, int x, int y, int cx, int cy, UINT flags) { + Win* w = Find(h); + if (!w) return FALSE; + if (w->parent) { + if (!(flags & SWP_NOMOVE)) { w->x = x; w->y = y; } + if (!(flags & SWP_NOSIZE)) { w->w = cx; w->h = cy; } + return TRUE; + } + if (!w->sdl) return TRUE; + if (!(flags & SWP_NOSIZE) && cx > 0 && cy > 0) SDL_SetWindowSize(w->sdl, (int)std::lround(cx / w->density), (int)std::lround(cy / w->density)); + if (!(flags & SWP_NOMOVE)) SDL_SetWindowPosition(w->sdl, (int)std::lround(x / w->density), (int)std::lround(y / w->density)); + return TRUE; +} + +BOOL GetWindowRect(HWND h, RECT* r) { + Win* w = Find(h); + if (!w || !r) return FALSE; + const POINT o = OriginOf(w); + int cw = 0, ch = 0; + ClientSize(w, cw, ch); + *r = RECT{o.x, o.y, o.x + cw, o.y + ch}; + return TRUE; +} +BOOL GetClientRect(HWND h, RECT* r) { + Win* w = Find(h); + if (!w || !r) return FALSE; + int cw = 0, ch = 0; + ClientSize(w, cw, ch); + *r = RECT{0, 0, cw, ch}; + return TRUE; +} +BOOL GetWindowPlacement(HWND h, WINDOWPLACEMENT* wp) { + Win* w = Find(h); + if (!w || !wp) return FALSE; + wp->showCmd = w->minimized ? SW_SHOWMINIMIZED : w->maximized ? SW_SHOWMAXIMIZED : SW_SHOWNORMAL; + wp->flags = 0; + GetWindowRect(h, &wp->rcNormalPosition); + return TRUE; +} + +int MapWindowPoints(HWND from, HWND to, POINT* pts, UINT n) { + const POINT of = from ? OriginOf(Find(from)) : POINT{0, 0}, ot = to ? OriginOf(Find(to)) : POINT{0, 0}; + for (UINT i = 0; i < n; ++i) { pts[i].x += of.x - ot.x; pts[i].y += of.y - ot.y; } + return 0; +} +BOOL ScreenToClient(HWND h, POINT* p) { MapWindowPoints(nullptr, h, p, 1); return TRUE; } +BOOL ClientToScreen(HWND h, POINT* p) { MapWindowPoints(h, nullptr, p, 1); return TRUE; } +HWND GetParent(HWND h) { Win* w = Find(h); return w ? (HWND)w->parent : nullptr; } + +LONG_PTR GetWindowLongPtrW(HWND h, int index) { + Win* w = Find(h); + if (!w) return 0; + return index == GWLP_ID ? w->ctrlId : index == GWLP_USERDATA ? w->userdata : 0; +} +LONG_PTR SetWindowLongPtrW(HWND h, int index, LONG_PTR v) { + Win* w = Find(h); + if (!w) return 0; + LONG_PTR& slot = index == GWLP_ID ? w->ctrlId : w->userdata; + const LONG_PTR old = slot; + slot = v; + return old; +} + +BOOL SetWindowTextW(HWND h, LPCWSTR text) { return h ? (BOOL)(Send(h, WM_SETTEXT, 0, (LPARAM)(text ? text : L"")) != 0) : FALSE; } +int GetWindowTextW(HWND h, LPWSTR out, int n) { + if (!out || n <= 0) return 0; + return (int)Send(h, WM_GETTEXT, (WPARAM)n, (LPARAM)out); +} +int GetWindowTextLengthW(HWND h) { return (int)Send(h, WM_GETTEXTLENGTH, 0, 0); } + +BOOL SetForegroundWindow(HWND h) { + Win* w = Find(h); + if (w && w->sdl) SDL_RaiseWindow(w->sdl); + return TRUE; +} +BOOL FlashWindow(HWND h, BOOL invert) { + Win* w = Find(h); + if (w && w->sdl && invert) SDL_FlashWindow(w->sdl, SDL_FLASH_BRIEFLY); + return TRUE; +} + +BOOL InvalidateRect(HWND h, const RECT*, BOOL) { + Win* w = Find(h); + if (!w) return FALSE; + InvalidateWin(w); + return TRUE; +} +BOOL RedrawWindow(HWND h, const RECT*, void*, UINT flags) { + Win* w = Find(h); + if (!w) return FALSE; + // a text field is drawn inside its window's frame: moved inside that frame's paint, it needs no second one + if (w->parent) return TRUE; + InvalidateWin(w); + if (flags & RDW_UPDATENOW) UpdateWindow(h); + return TRUE; +} +HDC BeginPaint(HWND h, PAINTSTRUCT* ps) { + Win* w = Find(h); + if (w) { w->invalid = false; w->lastPaintMs = NowMs(); } + if (ps) { + *ps = PAINTSTRUCT{}; + ps->hdc = (HDC)(uintptr_t)1; + if (w) { int cw = 0, ch = 0; ClientSize(w, cw, ch); ps->rcPaint = RECT{0, 0, cw, ch}; } + } + return (HDC)(uintptr_t)1; +} +BOOL EndPaint(HWND, const PAINTSTRUCT*) { return TRUE; } +BOOL EqualRect(const RECT* a, const RECT* b) { return a->left == b->left && a->top == b->top && a->right == b->right && a->bottom == b->bottom; } + +HWND WindowFromPoint(POINT p) { + std::vector tops; + { + std::lock_guard l(g_mu); + for (auto& e : g_wins) if (!e.second->parent && e.second->sdl && e.second->visible) tops.push_back(e.second.get()); + } + for (Win* t : tops) { + const POINT o = OriginOf(t); + int cw = 0, ch = 0; + ClientSize(t, cw, ch); + if (p.x >= o.x && p.y >= o.y && p.x < o.x + cw && p.y < o.y + ch) return Hw(t); + } + return nullptr; +} +BOOL GetCursorPos(POINT* p) { if (p) *p = g_mouse; return TRUE; } + +BOOL SetWindowSubclass(HWND h, SUBCLASSPROC proc, UINT_PTR id, DWORD_PTR data) { + Win* w = Find(h); + if (!w) return FALSE; + for (auto& s : w->subs) if (s.proc == proc && s.id == id) { s.data = data; return TRUE; } + w->subs.insert(w->subs.begin(), Sub{proc, id, data}); + return TRUE; +} +LRESULT DefSubclassProc(HWND h, UINT m, WPARAM wp, LPARAM lp) { + Win* w = Find(h); + if (!w) return 0; + size_t at = 0; + bool found = false; + for (size_t i = g_depth.size(); i-- > 0;) if (g_depth[i].first == h) { at = g_depth[i].second; found = true; break; } + const size_t nx = found ? at + 1 : 0; + if (nx < w->subs.size()) { + const Sub s = w->subs[nx]; + g_depth.push_back({h, nx}); + const LRESULT r = s.proc(h, m, wp, lp, s.id, s.data); + if (!g_depth.empty()) g_depth.pop_back(); + return r; + } + return ClassProc(w, m, wp, lp); +} +LRESULT CallWindowProcW(WNDPROC proc, HWND h, UINT m, WPARAM wp, LPARAM lp) { return proc ? proc(h, m, wp, lp) : 0; } + +LRESULT DefWindowProcW(HWND h, UINT m, WPARAM wp, LPARAM lp) { + Win* w = Find(h); + if (!w) return 0; + switch (m) { + case WM_NCHITTEST: { // a borderless window: the resize border is this layer's (the app's toolbar answers the caption itself) + if (w->parent || w->messageOnly || !(w->style & WS_THICKFRAME) || w->maximized) return HTCLIENT; + const POINT o = OriginOf(w); + const int x = GET_X_LPARAM(lp) - o.x, y = GET_Y_LPARAM(lp) - o.y; + int cw = 0, ch = 0; + ClientSize(w, cw, ch); + const int b = std::max(1, GetSystemMetricsForDpi(SM_CXFRAME, DpiOf(w))); + const bool l = x < b, r = x >= cw - b, t = y < b, bt = y >= ch - b; + const int cr = b * 2; // corners are a little longer than the edges + if ((l && y < cr) || (t && x < cr)) return HTTOPLEFT; + if ((r && y < cr) || (t && x >= cw - cr)) return HTTOPRIGHT; + if ((l && y >= ch - cr) || (bt && x < cr)) return HTBOTTOMLEFT; + if ((r && y >= ch - cr) || (bt && x >= cw - cr)) return HTBOTTOMRIGHT; + if (l) return HTLEFT; + if (r) return HTRIGHT; + if (bt) return HTBOTTOM; + if (t) return HTTOP; + return HTCLIENT; + } + case WM_NCACTIVATE: return TRUE; + case WM_ACTIVATE: + if (LOWORD(wp) != WA_INACTIVE) { // the window takes the keys unless one of its fields already has them + const HWND f = g_focus; + if (!f || TopOf(Find(f)) != h) SetFocus(h); + } + return 0; + case WM_ERASEBKGND: return 1; + case WM_PAINT: { PAINTSTRUCT ps; BeginPaint(h, &ps); EndPaint(h, &ps); return 0; } + case WM_CLOSE: DestroyWindow(h); return 0; + case WM_SYSCOMMAND: { + const UINT c = (UINT)(wp & 0xFFF0); + if (c == SC_CLOSE) { Send(h, WM_CLOSE, 0, 0); return 0; } + if (!w->sdl) return 0; + if (c == SC_MINIMIZE) { SDL_MinimizeWindow(w->sdl); w->minimized = true; } + else if (c == SC_MAXIMIZE) SDL_MaximizeWindow(w->sdl); + else if (c == SC_RESTORE) { SDL_RestoreWindow(w->sdl); } + return 0; + } + case WM_NCLBUTTONDBLCLK: + if (wp == HTCAPTION && w->sdl) { if (w->maximized) SDL_RestoreWindow(w->sdl); else SDL_MaximizeWindow(w->sdl); } + return 0; + case WM_SYSKEYDOWN: + if (wp == 0x73) { Send(h, WM_SYSCOMMAND, SC_CLOSE, 0); return 0; } // Alt+F4 + return 0; + case WM_MOUSEWHEEL: // a field passes the wheel on to its window + if (w->parent) return Send((HWND)w->parent, m, wp, lp); + return 0; + case WM_SETICON: return 0; + default: return 0; + } +} + +// ---- messages and timers ---------------------------------------------------------------------------------------------------- +BOOL PostMessageW(HWND h, UINT m, WPARAM wp, LPARAM lp) { + if (!h) { Enqueue(nullptr, m, wp, lp); return TRUE; } + { + std::lock_guard l(g_mu); + if (!FindLocked(h)) return FALSE; + } + Enqueue(h, m, wp, lp); + return TRUE; +} +LRESULT SendMessageW(HWND h, UINT m, WPARAM wp, LPARAM lp) { return Send(h, m, wp, lp); } + +BOOL GetMessageW(MSG* m, HWND h, UINT lo, UINT hi) { + NextMessage(m, true, true, h, lo, hi); + return m->message != WM_QUIT; +} +BOOL PeekMessageW(MSG* m, HWND h, UINT lo, UINT hi, UINT remove) { return NextMessage(m, false, (remove & PM_REMOVE) != 0, h, lo, hi); } +BOOL TranslateMessage(const MSG* m) { + if (m->message == WM_KEYDOWN && (m->wParam == VK_RETURN || m->wParam == VK_TAB || m->wParam == VK_ESCAPE) && !g_cur.down[VK_MENU]) + Enqueue(m->hwnd, WM_CHAR, m->wParam == VK_RETURN ? 13 : m->wParam == VK_TAB ? 9 : 27, m->lParam); + return TRUE; +} +LRESULT DispatchMessageW(const MSG* m) { + if (m->message == WM_TIMER && m->lParam) { // a timer with its own procedure + reinterpret_cast(m->lParam)(m->hwnd, WM_TIMER, m->wParam, m->time); + return 0; + } + if (!m->hwnd) return 0; + if (m->message == WM_TIMER && m->wParam == kCaretTimer) { // the blink: a frame, nothing for the app + if (Win* w = Find(m->hwnd)) InvalidateWin(w); + return 0; + } + return Send(m->hwnd, m->message, m->wParam, m->lParam); +} +void PostQuitMessage(int code) { g_quit = true; g_quitCode = code; Wake(); } + +DWORD MsgWaitForMultipleObjects(DWORD, const HANDLE*, BOOL, DWORD ms, DWORD) { + const uint64_t until = NowMs() + (ms == INFINITE ? 3600000u : ms); + for (;;) { + { + std::lock_guard l(g_mu); + if (!g_q.empty()) return WAIT_OBJECT_0; + } + PumpSdl(0); + { + std::lock_guard l(g_mu); + if (!g_q.empty()) return WAIT_OBJECT_0; + } + const uint64_t now = NowMs(); + if (now >= until) return WAIT_TIMEOUT; + const int w = (int)std::min(until - now, 20); + if (g_sdlUp) PumpSdl(w); + else { std::unique_lock l(g_mu); g_cv.wait_for(l, std::chrono::milliseconds(w), [] { return !g_q.empty(); }); } + } +} + +UINT_PTR SetTimer(HWND h, UINT_PTR id, UINT ms, TIMERPROC proc) { + if (!h) return 0; + { + std::lock_guard l(g_mu); + const uint64_t now = NowMs(); + for (auto& t : g_timers) if (t.hwnd == (uintptr_t)h && t.id == id) { t.interval = ms; t.due = now + ms; t.proc = proc; Wake(); return id; } + g_timers.push_back(Timer{(uintptr_t)h, id, ms, now + ms, proc}); + } + Wake(); + return id; +} +BOOL KillTimer(HWND h, UINT_PTR id) { + std::lock_guard l(g_mu); + const size_t n = g_timers.size(); + g_timers.erase(std::remove_if(g_timers.begin(), g_timers.end(), [&](const Timer& t) { return t.hwnd == (uintptr_t)h && t.id == id; }), g_timers.end()); + return g_timers.size() != n; +} +UINT GetDoubleClickTime() { return 500; } + +HWND SetFocus(HWND h) { + const HWND old = g_focus; + Win* nw = h ? Find(h) : nullptr; + if (h && !nw) return old; + if (old == h) return old; + g_focus = h; + if (old && Find(old)) Send(old, WM_KILLFOCUS, (WPARAM)h, 0); + if (nw) Send(h, WM_SETFOCUS, (WPARAM)old, 0); + ShowTextInput(nw && nw->builtinEdit, nw ? nw : (old ? Find(old) : nullptr)); + // the blinking caret's clock: only while a field has the keys + Win* top = nw ? TopWin(nw) : nullptr; + if (top) { + if (nw->builtinEdit) SetTimer(Hw(top), kCaretTimer, 530, nullptr); else KillTimer(Hw(top), kCaretTimer); + } + return old; +} +HWND GetFocus() { return g_focus && Find(g_focus) ? g_focus : nullptr; } +HWND SetCapture(HWND h) { + const HWND old = g_capture; + g_capture = h; + if (old && old != h && Find(old)) Send(old, WM_CAPTURECHANGED, 0, (LPARAM)h); // the window that lost it learns who has it + return old; +} +BOOL ReleaseCapture() { + const HWND old = g_capture; + g_capture = nullptr; + if (old && Find(old)) Send(old, WM_CAPTURECHANGED, 0, 0); + return TRUE; +} +HWND GetCapture() { return g_capture && Find(g_capture) ? g_capture : nullptr; } +short GetKeyState(int vk) { // as of the input message taken off the queue last, as Win32's is + if (vk == VK_LBUTTON) return (g_cur.btn & MK_LBUTTON) ? (short)0x8000 : 0; + return vk >= 0 && vk < 256 && g_cur.down[vk] ? (short)0x8000 : 0; +} +BOOL TrackMouseEvent(TRACKMOUSEEVENT* t) { + Win* w = t ? Find(t->hwndTrack) : nullptr; + if (!w) return FALSE; + Win* top = TopWin(w); + if (t->dwFlags & TME_NONCLIENT) top->trackNcLeave = true; else top->trackLeave = true; + return TRUE; +} +UINT MapVirtualKeyW(UINT code, UINT) { return code; } +int GetKeyNameTextW(LONG, LPWSTR out, int n) { if (out && n > 0) out[0] = 0; return 0; } + +// ---- cursors, icons, metrics, monitors ------------------------------------------------------------------------------------------------ +HCURSOR LoadCursorW(HINSTANCE, LPCWSTR id) { return CursorFor(id); } +HCURSOR SetCursor(HCURSOR c) { + const unsigned id = (unsigned)(uintptr_t)c; + const HCURSOR old = (HCURSOR)(uintptr_t)g_cursorId; + if (!g_sdlUp || id == g_cursorId) return old; + g_cursorId = id; + auto it = g_cursors.find(id); + if (it == g_cursors.end()) { + const SDL_SystemCursor k = id == 32649 ? SDL_SYSTEM_CURSOR_POINTER : id == 32513 ? SDL_SYSTEM_CURSOR_TEXT : id == 32650 ? SDL_SYSTEM_CURSOR_PROGRESS : SDL_SYSTEM_CURSOR_DEFAULT; + it = g_cursors.emplace(id, SDL_CreateSystemCursor(k)).first; + } + if (it->second) SDL_SetCursor(it->second); + return old; +} +HICON LoadIconW(HINSTANCE, LPCWSTR) { return nullptr; } +BOOL DestroyIcon(HICON) { return TRUE; } + +int GetSystemMetricsForDpi(int index, UINT dpi) { + switch (index) { + case SM_CXFRAME: case SM_CYFRAME: return (int)std::lround(6 * dpi / 96.0); + case SM_CXPADDEDBORDER: return 0; + case SM_CXICON: case SM_CYICON: return (int)std::lround(32 * dpi / 96.0); + case SM_CXSMICON: case SM_CYSMICON: return (int)std::lround(16 * dpi / 96.0); + default: return 0; + } +} +int GetSystemMetrics(int index) { + if (index == SM_CXSCREEN || index == SM_CYSCREEN) { + MONITORINFO mi{}; + mi.cbSize = sizeof mi; + GetMonitorInfoW(MonitorFromPoint(POINT{0, 0}, MONITOR_DEFAULTTOPRIMARY), &mi); + return index == SM_CXSCREEN ? mi.rcMonitor.right - mi.rcMonitor.left : mi.rcMonitor.bottom - mi.rcMonitor.top; + } + return GetSystemMetricsForDpi(index, GetDpiForSystem()); +} +UINT GetDpiForWindow(HWND h) { Win* w = Find(h); return w ? DpiOf(w) : 96; } +UINT GetDpiForSystem() { + if (!EnsureSdl()) return 96; + const float s = SDL_GetDisplayContentScale(SDL_GetPrimaryDisplay()); + return s > 0.25f ? (UINT)std::lround(96 * s) : 96; +} +BOOL AdjustWindowRectExForDpi(RECT*, DWORD, BOOL, DWORD, UINT) { return TRUE; } // no system frame: the client area is the window + +BOOL SystemParametersInfoW(UINT action, UINT param, PVOID data, UINT) { + switch (action) { + case SPI_GETWHEELSCROLLLINES: if (data) *(UINT*)data = 3; return TRUE; + case SPI_GETHIGHCONTRAST: if (data) ((HIGHCONTRASTW*)data)->dwFlags = 0; return TRUE; + case SPI_GETCLIENTAREAANIMATION: if (data) *(BOOL*)data = TRUE; return TRUE; + case SPI_GETMESSAGEDURATION: if (data) *(UINT*)data = 5; return TRUE; + default: (void)param; return FALSE; + } +} +DWORD GetSysColor(int index) { + switch (index) { + case COLOR_WINDOW: return RGB(255, 255, 255); + case COLOR_WINDOWTEXT: return RGB(0, 0, 0); + case COLOR_HIGHLIGHT: return RGB(0, 120, 215); + case COLOR_HIGHLIGHTTEXT: return RGB(255, 255, 255); + case COLOR_GRAYTEXT: return RGB(109, 109, 109); + default: return 0; + } +} +HBRUSH GetSysColorBrush(int index) { return CreateSolidBrush(GetSysColor(index)); } + +namespace { +SDL_DisplayID DisplayOfPoint(POINT p) { + SDL_Point sp{p.x, p.y}; + SDL_DisplayID d = SDL_GetDisplayForPoint(&sp); + return d ? d : SDL_GetPrimaryDisplay(); +} +} // namespace +HMONITOR MonitorFromPoint(POINT p, DWORD) { + if (!EnsureSdl()) return (HMONITOR)(uintptr_t)1; + return (HMONITOR)(uintptr_t)DisplayOfPoint(p); +} +HMONITOR MonitorFromRect(const RECT* r, DWORD flags) { return MonitorFromPoint(POINT{r->left, r->top}, flags); } +HMONITOR MonitorFromWindow(HWND h, DWORD flags) { + Win* w = Find(h); + if (w && w->sdl) { const SDL_DisplayID d = SDL_GetDisplayForWindow(w->sdl); if (d) return (HMONITOR)(uintptr_t)d; } + return MonitorFromPoint(POINT{0, 0}, flags); +} +BOOL GetMonitorInfoW(HMONITOR m, MONITORINFO* mi) { + if (!mi) return FALSE; + const SDL_DisplayID d = (SDL_DisplayID)(uintptr_t)m; + SDL_Rect b{0, 0, 1920, 1080}, u{0, 0, 1920, 1080}; + float k = 1; + if (g_sdlUp && d) { SDL_GetDisplayBounds(d, &b); if (!SDL_GetDisplayUsableBounds(d, &u)) u = b; k = DensityGuess(d); } + mi->rcMonitor = RECT{(LONG)std::lround(b.x * k), (LONG)std::lround(b.y * k), (LONG)std::lround((b.x + b.w) * k), (LONG)std::lround((b.y + b.h) * k)}; + mi->rcWork = RECT{(LONG)std::lround(u.x * k), (LONG)std::lround(u.y * k), (LONG)std::lround((u.x + u.w) * k), (LONG)std::lround((u.y + u.h) * k)}; + mi->dwFlags = 1; + return TRUE; +} + +HRESULT DwmSetWindowAttribute(HWND, DWORD, LPCVOID, DWORD) { return E_NOTIMPL; } +BOOL ShutdownBlockReasonCreate(HWND, LPCWSTR) { return TRUE; } +BOOL ShutdownBlockReasonDestroy(HWND) { return TRUE; } + +void GetStartupInfoW(STARTUPINFOW* si) { if (si) { memset(si, 0, sizeof *si); si->cb = sizeof *si; } } + +INT_PTR ShellExecuteW(HWND, LPCWSTR verb, LPCWSTR file, LPCWSTR params, LPCWSTR dir, int show) { + SHELLEXECUTEINFOW sei{}; + sei.cbSize = sizeof sei; sei.lpVerb = verb; sei.lpFile = file; sei.lpParameters = params; sei.lpDirectory = dir; sei.nShow = show; + return ShellExecuteExW(&sei) ? 33 : 31; +} diff --git a/clean/installer/src/platform/posix/windows.h b/clean/installer/src/platform/posix/windows.h new file mode 100644 index 00000000..0442a001 --- /dev/null +++ b/clean/installer/src/platform/posix/windows.h @@ -0,0 +1,5 @@ +// SPDX-License-Identifier: MIT +// Linux: stands in for the Windows header of the same name (win32_posix.h). +#pragma once +#include "win32_posix.h" +#include "win32_window.h" diff --git a/clean/installer/src/platform/posix/windowsx.h b/clean/installer/src/platform/posix/windowsx.h new file mode 100644 index 00000000..638cfb9a --- /dev/null +++ b/clean/installer/src/platform/posix/windowsx.h @@ -0,0 +1,4 @@ +// SPDX-License-Identifier: MIT +// Linux: stands in for the Windows header of the same name (win32_window.h). +#pragma once +#include "win32_window.h" diff --git a/clean/installer/src/platform/posix/winevt.h b/clean/installer/src/platform/posix/winevt.h new file mode 100644 index 00000000..b13ed666 --- /dev/null +++ b/clean/installer/src/platform/posix/winevt.h @@ -0,0 +1,4 @@ +// SPDX-License-Identifier: MIT +// Linux: stands in for the Windows header of the same name (win32_posix.h). +#pragma once +#include "win32_posix.h" diff --git a/clean/installer/src/platform/posix/winhttp.h b/clean/installer/src/platform/posix/winhttp.h new file mode 100644 index 00000000..b13ed666 --- /dev/null +++ b/clean/installer/src/platform/posix/winhttp.h @@ -0,0 +1,4 @@ +// SPDX-License-Identifier: MIT +// Linux: stands in for the Windows header of the same name (win32_posix.h). +#pragma once +#include "win32_posix.h" diff --git a/clean/installer/src/wg_core/appimage.cpp b/clean/installer/src/wg_core/appimage.cpp new file mode 100644 index 00000000..d3fe4528 --- /dev/null +++ b/clean/installer/src/wg_core/appimage.cpp @@ -0,0 +1,259 @@ +// SPDX-License-Identifier: MIT +// WrongGPU launcher core: the native Linux launcher's own removal (appimage.h). Written for this project. +#include "appimage.h" + +#include +#include + +#include "launcher.h" + +namespace wg { + +// A Linux path from the environment ("/home/x/WrongGPU.AppImage") as the core spells it (Z:\home\x\WrongGPU.AppImage). +static wstring CoreSpelling(wstring p) { + if (!p.empty() && p[0] == L'/') p = L"Z:" + p; + for (auto& c : p) if (c == L'/') c = L'\\'; + return p; +} + +// The system's process folder. A WRONGGPU_TESTING build takes WRONGGPU_TEST_PROC_ROOT instead (a made-up tree the tests fill with +// the entries the real one would have); a release build never reads it. +static wstring ProcRoot() { +#ifdef WRONGGPU_TESTING + const wstring env = EnvVar(L"WRONGGPU_TEST_PROC_ROOT"); + if (!env.empty()) return CoreSpelling(env); +#endif + return L"Z:\\proc"; +} + +// A file's identity on its disk (st_dev and st_ino through the layer) and, when asked, the first 16 bytes it holds right now. +struct DiskIdent { + DWORD volume = 0, high = 0, low = 0; + bool operator==(const DiskIdent& o) const { return volume == o.volume && high == o.high && low == o.low; } +}; +static bool IdentOf(const wstring& p, DiskIdent& id, unsigned char* head16 = nullptr) { + HANDLE h = CreateFileW(p.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + if (h == INVALID_HANDLE_VALUE) return false; + BY_HANDLE_FILE_INFORMATION bi{}; + bool ok = GetFileInformationByHandle(h, &bi) != FALSE; + if (ok) { id.volume = bi.dwVolumeSerialNumber; id.high = bi.nFileIndexHigh; id.low = bi.nFileIndexLow; } + DWORD got = 0; + if (ok && head16) ok = ReadFile(h, head16, 16, &got, nullptr) && got == 16; + CloseHandle(h); + return ok; +} +// an AppImage is an ELF file with "AI" and the type number 2 in bytes 8 to 10 of its header +static bool IsAppImageHead(const unsigned char* head) { + return head[0] == 0x7f && head[1] == 'E' && head[2] == 'L' && head[3] == 'F' && head[8] == 'A' && head[9] == 'I' && head[10] == 2; +} + +// What a file read gives back as text, up to a limit (the process folder's files report size 0 and are read to their end). +static bool ReadText(const wstring& p, string& out, size_t limit = 1u << 20) { + out.clear(); + HANDLE h = CreateFileW(p.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + if (h == INVALID_HANDLE_VALUE) return false; + char buf[4096]; + DWORD got = 0; + while (out.size() < limit && ReadFile(h, buf, sizeof buf, &got, nullptr) && got) out.append(buf, got); + CloseHandle(h); + return true; +} + +// The real path of an existing file or folder in the host's own spelling: links followed, "." and ".." folded, and the case the +// disk has (a Linux disk tells "App" from "app"). +// (Both spellings are host ones, taken as they are: the layer's own path code would fold the letter case.) +static bool Canonical(const string& hostPath, string& host) { + std::error_code ec; + const auto c = std::filesystem::canonical(hostPath, ec); + if (ec) return false; + host = c.string(); + return !host.empty() && host[0] == '/'; +} + +std::string HostSelfPath() { + std::error_code ec; + const auto p = std::filesystem::read_symlink("/proc/self/exe", ec); + if (ec) return string(); + const string s = p.string(); + return !s.empty() && s[0] == '/' ? s : string(); +} + +// The device number the way a file's st_dev reaches the core (the layer keeps its low 32 bits): Linux's own packing. +static DWORD DevNumber(unsigned major, unsigned minor) { + return (DWORD)(((major & 0xfffu) << 8) | (minor & 0xffu) | ((minor & ~0xffu) << 12)); +} + +// The line of the system's mount table (mountinfo) for a mount point, as "major:minor fstype". Octal escapes (\040) are undone. +// The last line wins: it is the one on top when a folder is mounted over more than once. +static bool MountOf(const string& table, const string& point, unsigned& major, unsigned& minor, string& fstype) { + bool found = false; + size_t pos = 0; + while (pos < table.size()) { + size_t end = table.find('\n', pos); + if (end == string::npos) end = table.size(); + const string line = table.substr(pos, end - pos); + pos = end + 1; + // id parent major:minor root mountpoint options [optional fields] - fstype source superoptions + size_t f[6]; + size_t at = 0; + bool bad = false; + for (int i = 0; i < 6 && !bad; ++i) { + f[i] = at; + const size_t sp = line.find(' ', at); + if (sp == string::npos) bad = true; else at = sp + 1; + } + if (bad) continue; + auto field = [&](int i) { const size_t e = line.find(' ', f[i]); return line.substr(f[i], e == string::npos ? string::npos : e - f[i]); }; + string mp; + const string raw = field(4); + for (size_t i = 0; i < raw.size(); ++i) { + if (raw[i] == '\\' && i + 3 < raw.size() && raw[i + 1] >= '0' && raw[i + 1] <= '7' && raw[i + 2] >= '0' && raw[i + 2] <= '7' && raw[i + 3] >= '0' && raw[i + 3] <= '7') { + mp += (char)((raw[i + 1] - '0') * 64 + (raw[i + 2] - '0') * 8 + (raw[i + 3] - '0')); + i += 3; + } else mp += raw[i]; + } + if (mp != point) continue; + unsigned a = 0, b = 0; + if (std::sscanf(field(2).c_str(), "%u:%u", &a, &b) != 2) continue; + const size_t dash = line.find(" - "); + if (dash == string::npos) continue; + const size_t ts = dash + 3, te = line.find(' ', ts); + major = a; minor = b; + fstype = line.substr(ts, te == string::npos ? string::npos : te - ts); + found = true; + } + return found; +} + +// Does a live process serve this FUSE mount, and is it the program that file holds? The AppImage runtime mounts its own file +// through its own copy of FUSE: the process that serves the mount is the runtime, started from that file, and the kernel +// names the mount's connection (fuse_connection: ) in the fdinfo of the process's /dev/fuse +// descriptor. So the link from mount to file is the kernel's: connection number -> server -> its executable's identity. +static bool ServedFromFile(const wstring& procRoot, unsigned minor, const DiskIdent& image) { + std::error_code ec; + const string want = "fuse_connection:\t" + std::to_string(minor); + for (const auto& pid : std::filesystem::directory_iterator(FsPath(procRoot), ec)) { + const string name = pid.path().filename().string(); + if (name.empty() || name.find_first_not_of("0123456789") != string::npos) continue; + const wstring base = procRoot + L"\\" + FromUtf8(name); + DiskIdent exe; + if (!IdentOf(base + L"\\exe", exe) || !(exe == image)) continue; + std::error_code ec2; + for (const auto& fd : std::filesystem::directory_iterator(FsPath(base + L"\\fdinfo"), ec2)) { + string info; + if (!ReadText(base + L"\\fdinfo\\" + FromUtf8(fd.path().filename().string()), info, 4096)) continue; + size_t at = 0; + while ((at = info.find(want, at)) != string::npos) { + const size_t after = at + want.size(); + if (at == 0 || info[at - 1] == '\n') { + if (after >= info.size() || info[after] == '\n') return true; // (the whole number: 12 is not 120) + } + at = after; + } + } + } + return false; +} + +namespace { +// The file that was proven to be this program's own AppImage, as it was when it was checked. +struct Checked { wstring file; DiskIdent id; wstring host; }; +} + +static bool CheckOwn(Checked& out, wstring* why) { + auto no = [&](const wstring& w) { if (why) *why = w; return false; }; + const wstring env = EnvVar(L"APPIMAGE"); + if (env.empty()) return no(L"WrongGPU is not running from an AppImage here, so there is no file for it to delete. Delete the program file yourself."); + wstring p = CoreSpelling(env); + // the environment's own spelling is looked up as it is (the layer's path code would fold letter case, a Linux disk does not) + std::error_code ec; + const string envHost = ToUtf8(env); + const auto status = std::filesystem::symlink_status(envHost, ec); // (a link is not followed: it is not the file) + const wstring notPlain = p + L" is not a plain file (it is missing, a folder or a link), so WrongGPU will not delete it."; + if (ec || !std::filesystem::is_regular_file(status)) return no(notPlain); + // the file as the disk spells it (a link in a folder above it is followed once, here, and the answer used from now on) + string imageHost; + if (!Canonical(envHost, imageHost)) return no(notPlain); + p = CoreSpelling(FromUtf8(imageHost)); + const wstring name = BaseName(p); + if (!StartsWithI(name, L"WrongGPU") || !EndsWithI(name, L".AppImage")) + return no(L"The file is called " + name + L", not WrongGPU...AppImage, so WrongGPU cannot tell it is its own and will not delete it."); + unsigned char head[16] = {}; + DiskIdent id; + if (!IdentOf(p, id, head) || !IsAppImageHead(head)) + return no(name + L" is not an AppImage file, so WrongGPU will not delete it."); + const wstring notStarted = L"WrongGPU cannot prove that " + name + L" is the AppImage this program was started from, so it will not delete it."; + string appdirHost, selfHost; + if (EnvVar(L"APPDIR").empty() || !Canonical(ToUtf8(EnvVar(L"APPDIR")), appdirHost) || !Canonical(HostSelfPath(), selfHost) || + selfHost.compare(0, appdirHost.size() + 1, appdirHost + "/") != 0) + return no(L"This running program is not inside " + name + L", so WrongGPU cannot tell the file is the one it was started from and will not delete it."); + // $APPDIR must be a FUSE mount that the system itself says is served from this very file + const wstring procRoot = ProcRoot(); + string table; + unsigned major = 0, minor = 0; + string fstype; + DiskIdent selfId; + if (!ReadText(procRoot + L"\\self\\mountinfo", table) || !MountOf(table, appdirHost, major, minor, fstype) || + fstype.compare(0, 5, "fuse.") != 0) + return no(notStarted + L" (" + FromUtf8(appdirHost) + L" is not a mounted AppImage.)"); + if (!IdentOf(SelfPath(), selfId) || selfId.volume != DevNumber(major, minor)) + return no(notStarted + L" (This program is not on that mount.)"); + if (!ServedFromFile(procRoot, minor, id)) + return no(notStarted + L" (No process started from the file serves the mount.)"); + out.file = p; + out.id = id; + out.host = FromUtf8(imageHost); + return true; +} + +// Just before the delete: the path is still a plain file, still the same one that was proven, and still an AppImage. +static bool StillTheSame(const Checked& c, wstring* why) { + std::error_code ec; + const auto status = std::filesystem::symlink_status(FsPath(c.file), ec); + unsigned char head[16] = {}; + DiskIdent now; + if (ec || !std::filesystem::is_regular_file(status) || !IdentOf(c.file, now, head) || !(now == c.id) || !IsAppImageHead(head)) { + if (why) *why = BaseName(c.file) + L" changed while WrongGPU was checking it (another file is there now), so WrongGPU will not delete it. Nothing was removed."; + return false; + } + return true; +} + +bool OwnAppImage(wstring& file, wstring* why, wstring* host) { + Checked c; + if (!CheckOwn(c, why)) return false; + file = c.file; + if (host) *host = c.host; + return true; +} + +bool RunsInsideAnAppImage() { + string appdir, self; + if (EnvVar(L"APPIMAGE").empty() || EnvVar(L"APPDIR").empty() || !Canonical(ToUtf8(EnvVar(L"APPDIR")), appdir) || !Canonical(HostSelfPath(), self)) + return false; + return self.compare(0, appdir.size() + 1, appdir + "/") == 0; +} + +bool UninstallAppImage(Context& ctx, wstring* why, wstring* removedFile, wstring* kept) { + if (removedFile) removedFile->clear(); + Checked c; + if (!CheckOwn(c, why)) return false; + // what can stop the data from going is looked at first: the file goes before the data, so nothing may be left to refuse after it + const SharedDataLook look = LookAtSharedData(ctx); + if (look.there && look.anyGame) { if (why) *why = L"a game still has WrongGPU and uses this data. Uninstall WrongGPU from it first. Nothing was removed."; return false; } + TestFault("appimage-before-delete"); // tests: a file is put in the AppImage's place here + if (!StillTheSame(c, why)) return false; + if (!DeleteFileW(c.file.c_str())) { + if (why) *why = c.file + L" could not be deleted (" + ErrText(GetLastError()) + L"). Nothing was removed."; + return false; + } + if (removedFile) *removedFile = c.file; + wstring dataWhy; + if (!RemoveSharedData(ctx, &dataWhy, kept, true)) { + if (why) *why = L"The AppImage file " + c.file + L" is deleted, but WrongGPU's data was not removed: " + dataWhy; + return false; + } + return true; +} + +} // namespace wg diff --git a/clean/installer/src/wg_core/appimage.h b/clean/installer/src/wg_core/appimage.h new file mode 100644 index 00000000..f0096b11 --- /dev/null +++ b/clean/installer/src/wg_core/appimage.h @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: MIT +// WrongGPU launcher core: the native Linux launcher's own removal. An AppImage is one file ($APPIMAGE) and the launcher keeps its +// data in one folder (WrongGPU, under $XDG_DATA_HOME); there is no installer entry, so "Uninstall WrongGPU" in Settings deletes +// those two things after one confirmation and nothing else. Written for this project. +#pragma once +#include "context.h" + +namespace wg { + +// The AppImage file this process runs from, when it can be told to be WrongGPU's own. All of these must hold, or false with *why in +// plain words (nothing is deleted on a false): $APPIMAGE names a regular file (not a link, not a folder) whose name starts with +// WrongGPU and ends in .AppImage, the file is an AppImage (an ELF file with the type 2 AppImage mark), and the system itself ties +// it to this process: $APPDIR (case-sensitive, links resolved) is a FUSE mount in the system's mount table, this running program is +// on it, and a live process whose executable is that very file (same device and inode) holds the mount's /dev/fuse connection. The +// AppImage runtime mounts its own file that way, so $APPIMAGE and $APPDIR from the environment alone prove nothing. Where the +// system gives no such proof (the process folder cannot be read, the AppImage was unpacked instead of mounted) the answer is no. +// *file is the real path as the core spells it (Z:\...). +// *host (when given): the same file in its Linux spelling (/home/x/WrongGPU.AppImage, links resolved), what a shell is given. +bool OwnAppImage(wstring& file, wstring* why, wstring* host = nullptr); + +// Whether this program runs from an AppImage at all, a weaker question than OwnAppImage, for words only (never for a delete): +// $APPIMAGE and $APPDIR are set and this running program is inside $APPDIR. True too for an AppImage that was extracted and run +// (APPIMAGE_EXTRACT_AND_RUN), which has no FUSE mount to prove; false for the bare binary started with another AppImage's variables. +bool RunsInsideAnAppImage(); + +// Native Linux: this program's own file as the system names it (/proc/self/exe), with no round trip through the core's Windows-style +// spelling (which turns a backslash in a Linux name into a separator) and no length limit. Empty when it cannot be read. +std::string HostSelfPath(); + +// Uninstall: the AppImage file (OwnAppImage) and WrongGPU's data folder (RemoveSharedData: the converted model data, the +// games' list, the launcher's settings and logs; refused while a game still has WrongGPU, which reads that data). The file is +// proven first and its identity (device, inode, header) kept; a game still using the data is looked for next; then, just before the +// delete, the path must still be that same plain file (a file renamed in between is refused); the file goes first, then the data. +// *removedFile: the file's path; *kept: what RemoveSharedData kept (the player's ignore list). Never throws. +bool UninstallAppImage(Context& ctx, wstring* why, wstring* removedFile = nullptr, wstring* kept = nullptr); + +} // namespace wg diff --git a/clean/installer/src/wg_core/checks.cpp b/clean/installer/src/wg_core/checks.cpp index 322fdeb1..48fb7917 100644 --- a/clean/installer/src/wg_core/checks.cpp +++ b/clean/installer/src/wg_core/checks.cpp @@ -11,7 +11,37 @@ namespace wg { // ------------------------------------------------------------------------------------------------ // System requirements // ------------------------------------------------------------------------------------------------ +wstring LinuxOsName(const string& osRelease) { + string name, plain, version; + for (size_t at = 0; at < osRelease.size();) { + size_t nl = osRelease.find('\n', at); + if (nl == string::npos) nl = osRelease.size(); + string line = osRelease.substr(at, nl - at); + at = nl + 1; + const size_t eq = line.find('='); + if (eq == string::npos) continue; + string val = line.substr(eq + 1); + while (!val.empty() && (val.back() == '\r' || val.back() == ' ')) val.pop_back(); + if (val.size() >= 2 && (val.front() == '"' || val.front() == '\'') && val.back() == val.front()) val = val.substr(1, val.size() - 2); + const string key = line.substr(0, eq); + if (key == "PRETTY_NAME") name = val; + else if (key == "NAME") plain = val; + else if (key == "VERSION") version = val; + } + if (name.empty() && !plain.empty()) name = plain + (version.empty() ? string() : " " + version); + return FromUtf8(name.c_str()); +} WinInfo WindowsInfo() { + if (NativeLinux()) { // a Linux program: the system is the distribution, which Proton's Windows 10 stand-in is not + WinInfo w; + string text; + w.label = L"Linux"; + ReadAll(L"Z:\\etc\\os-release", text); + w.text = LinuxOsName(text); + if (w.text.empty()) w.text = L"unknown distribution"; + w.ok = true; + return w; + } using RtlGetVersionFn = LONG(WINAPI*)(OSVERSIONINFOW*); auto fn = reinterpret_cast(reinterpret_cast(GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "RtlGetVersion"))); OSVERSIONINFOW v{}; v.dwOSVersionInfoSize = sizeof(v); @@ -30,7 +60,8 @@ WinInfo WindowsInfo() { wstring NeedsRx9000Sentence() { return L"WrongGPU's models need an RX 9000-series GPU; using AMD FSR"; } wstring GpuToolbarLine(const wstring& shortName, const GpuInfo& gpu) { if (shortName.empty()) return L"No graphics card detected \u00b7 " + NeedsRx9000Sentence(); - return shortName + L" (detected) \u00b7 " + (gpu.rdna4 ? wstring(L"Direct3D 12") : NeedsRx9000Sentence()); + // natively on Linux the games reach Direct3D 12 through Proton (the first-run sheet says the same) + return shortName + L" (detected) \u00b7 " + (gpu.rdna4 ? wstring(NativeLinux() ? L"Direct3D 12 (through Proton)" : L"Direct3D 12") : NeedsRx9000Sentence()); } bool IsRdna4Name(const wstring& name) { return Contains(name, L"RX 90") || Contains(name, L"PRO R97") || Contains(name, L"PRO R96"); } // Under Wine, Wine's own DXGI can name an RDNA 4 card after an old Radeon ("ATI Radeon HD 5600 Series"); the PCI ids of @@ -69,14 +100,25 @@ static bool HexId(const string& text, unsigned long& id) { while (end && (*end == '\n' || *end == '\r' || *end == ' ')) ++end; return end && end != s && *end == '\0'; } +// The RDNA 4 PCI device ids and the card each is, from the RR runtime's list (rdna4_device_id) and the names its tests give +// the boards (clean/runtime/interop/tests/test_executor_select.cpp). One list: the Wine fallback and the native path read it. +struct Rdna4Card { unsigned long device; const wchar_t* name; }; +static const Rdna4Card kRdna4Cards[] = { + {0x7550, L"AMD Radeon RX 9070 XT"}, {0x7551, L"AMD Radeon RX 9070 GRE"}, {0x7590, L"AMD Radeon RX 9060 XT"}, {0x7591, L"AMD Radeon RX 9060"}}; +static const Rdna4Card* FindRdna4Card(unsigned long vendor, unsigned long device) { + if (vendor != 0x1002) return nullptr; + for (const auto& c : kRdna4Cards) if (c.device == device) return &c; + return nullptr; +} +static bool CardIds(const wstring& card, unsigned long& v, unsigned long& d) { + string vendor, device; + return ReadSysfs(Join(card, L"device\\vendor"), vendor) && ReadSysfs(Join(card, L"device\\device"), device) && HexId(vendor, v) && HexId(device, d); +} wstring LinuxRdna4Name(const wstring& drmRoot) { for (const auto& card : DrmCards(drmRoot)) { - string vendor, device; unsigned long v = 0, d = 0; - if (!ReadSysfs(Join(card.second, L"device\\vendor"), vendor) || !ReadSysfs(Join(card.second, L"device\\device"), device) || - !HexId(vendor, v) || !HexId(device, d)) - continue; - if (v == 0x1002 && (d == 0x7550 || d == 0x7551 || d == 0x7590 || d == 0x7591)) { + if (!CardIds(card.second, v, d)) continue; + if (FindRdna4Card(v, d)) { wchar_t b[160]; swprintf(b, 160, L"AMD Radeon RDNA 4 (PCI 1002:%04lX, found in Linux's device list; not confirmed as the adapter the game uses)", d); return b; @@ -84,14 +126,56 @@ wstring LinuxRdna4Name(const wstring& drmRoot) { } return L""; } +// What Linux's device list says about the graphics cards, with no Windows graphics layer: a native Linux launcher has no DXGI. +// The name comes from the card's PCI ids (an RDNA 4 board by name, any other card as " (code vvvv:dddd)"); the driver is the +// name of the kernel driver bound to the card (the `driver` link). An AMD RDNA 4 card wins over any other; otherwise the first AMD +// card, otherwise the first card. Connectors, unreadable cards and a missing folder count as no card. Only RDNA 4 sets `rdna4` +// (an RX 7000-series card is AMD, not supported). +GpuInfo GpuFromDrm(const wstring& drmRoot) { + GpuInfo best; + for (const auto& card : DrmCards(drmRoot)) { + unsigned long v = 0, d = 0; + if (!CardIds(card.second, v, d)) continue; + const Rdna4Card* known = FindRdna4Card(v, d); + const bool amd = v == 0x1002; + if (!best.name.empty() && !(amd && !best.amd) && !(known && !best.rdna4)) continue; + wchar_t b[96]; + wstring name; + if (known) name = known->name; + else { + swprintf(b, 96, L"%ls (code %04lX:%04lX)", amd ? L"AMD Radeon" : v == 0x10de ? L"NVIDIA graphics" : v == 0x8086 ? L"Intel graphics" : L"Graphics card", v, d); + name = b; + } + wstring driver; + const HANDLE h = CreateFileW(Join(card.second, L"device\\driver").c_str(), 0, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, nullptr); + if (h != INVALID_HANDLE_VALUE) { + wchar_t path[MAX_PATH]; + if (const DWORD n = GetFinalPathNameByHandleW(h, path, MAX_PATH, 0); n && n < MAX_PATH) driver = BaseName(wstring(path, n)); + CloseHandle(h); + } + best.name = name; best.driver = driver; best.amd = amd; best.rdna4 = known != nullptr; + } + return best; +} +// The device list a native launcher reads. A WRONGGPU_TESTING build takes WRONGGPU_TEST_DRM_ROOT instead (a made-up folder of cards, +// so the tests and the screenshots do not depend on this machine's GPU); a release build never reads it. +static wstring DrmRootForDetect() { +#ifdef WRONGGPU_TESTING + const wstring env = EnvVar(L"WRONGGPU_TEST_DRM_ROOT"); + if (!env.empty()) return env; +#endif + return L"Z:\\sys\\class\\drm"; +} GpuInfo DetectGpu() { GpuInfo best; + // a native Linux launcher has no DXGI: Linux's own device list names the card + const auto noDxgi = [&]() { return NativeLinux() ? GpuFromDrm(DrmRootForDetect()) : best; }; HMODULE dxgi = LoadSystemDll(L"dxgi.dll"); - if (!dxgi) return best; + if (!dxgi) return noDxgi(); using CreateFn = HRESULT(WINAPI*)(REFIID, void**); auto create = reinterpret_cast(reinterpret_cast(GetProcAddress(dxgi, "CreateDXGIFactory1"))); IDXGIFactory1* f = nullptr; - if (!create || FAILED(create(__uuidof(IDXGIFactory1), (void**)&f)) || !f) return best; + if (!create || FAILED(create(__uuidof(IDXGIFactory1), (void**)&f)) || !f) return noDxgi(); IDXGIAdapter1* a = nullptr; for (UINT i = 0; f->EnumAdapters1(i, &a) != DXGI_ERROR_NOT_FOUND; ++i) { DXGI_ADAPTER_DESC1 d{}; diff --git a/clean/installer/src/wg_core/checks.h b/clean/installer/src/wg_core/checks.h index 1ac24d3d..d586a01d 100644 --- a/clean/installer/src/wg_core/checks.h +++ b/clean/installer/src/wg_core/checks.h @@ -7,7 +7,7 @@ namespace wg { -struct WinInfo { bool ok = false; wstring text; }; +struct WinInfo { bool ok = false; wstring text; wstring label = L"Windows"; }; // label: "Windows", or "Linux" for the native launcher struct GpuInfo { bool amd = false, rdna4 = false; wstring name, driver; }; struct HipInfo { bool ran = false, ok = false; int code = -1; wstring dll, device, arch, text; }; enum CheckState { CK_OK, CK_FAIL, CK_WARN, CK_NA }; @@ -27,6 +27,8 @@ struct Checks { struct SystemInfo { WinInfo win; GpuInfo gpu; HipInfo hip; }; WinInfo WindowsInfo(); +// The distribution's name from the text of /etc/os-release (PRETTY_NAME, else NAME and VERSION); empty when it names none. +wstring LinuxOsName(const string& osRelease); bool IsRdna4Name(const wstring& name); // The sentence the runtime logs when it hands a game to AMD FSR on a GPU that is not an RX 9000-series card, or on one it // cannot identify (clean/runtime/interop/executor_select.h needs_rx9000_line); the launcher says the same. @@ -41,6 +43,10 @@ wstring GpuToolbarLine(const wstring& shortName, const GpuInfo& gpu); // when Linux reports no RDNA 4 card (or outside Wine, where Z:\sys does not exist). drmRoot: the folder holding card0, // card1, ... (Linux's /sys/class/drm; tests point it at a made-up folder). Every card is looked at, in number order. wstring LinuxRdna4Name(const wstring& drmRoot = L"Z:\\sys\\class\\drm"); +// A native Linux launcher (no DXGI): the card Linux's device list reports, named from its PCI ids; empty when there is none. Used by +// DetectGpu there; drmRoot as for LinuxRdna4Name. An AMD RDNA 4 card wins over any other, so a laptop's integrated GPU or a second +// card does not hide it. Only RDNA 4 sets `rdna4`. +GpuInfo GpuFromDrm(const wstring& drmRoot = L"Z:\\sys\\class\\drm"); GpuInfo DetectGpu(); bool VersionLess(const wstring& a, const wstring& b); std::vector HipCandidates(); diff --git a/clean/installer/src/wg_core/convert_ignore.cpp b/clean/installer/src/wg_core/convert_ignore.cpp index fc45b821..c8403628 100644 --- a/clean/installer/src/wg_core/convert_ignore.cpp +++ b/clean/installer/src/wg_core/convert_ignore.cpp @@ -144,8 +144,20 @@ static bool DecodeListBytes(const string& bytes, wstring& text, wstring& why) { if (bytes.size() >= 2 && u(0) == 0xFF && u(1) == 0xFE) { // UTF-16 LE with its BOM if ((bytes.size() - 2) % 2 != 0) { why = L"it is UTF-16 with a byte missing"; return false; } if (bytes.size() >= 4 && u(2) == 0 && u(3) == 0) { why = L"it is UTF-32 (save it as UTF-8, or UTF-16 LE with its BOM)"; return false; } - text.resize((bytes.size() - 2) / 2); - if (!text.empty()) std::memcpy(&text[0], bytes.data() + 2, text.size() * 2); + // unit by unit, not a memcpy: wchar_t is UTF-32 on Linux (src/platform/posix), where a surrogate pair is one character + text.clear(); + for (size_t i = 2; i + 1 < bytes.size(); i += 2) { + const unsigned unit = u(i) | (u(i + 1) << 8); + if (sizeof(wchar_t) > 2 && unit >= 0xD800 && unit < 0xDC00 && i + 3 < bytes.size()) { + const unsigned low = u(i + 2) | (u(i + 3) << 8); + if (low >= 0xDC00 && low < 0xE000) { + text += wchar_t(0x10000 + ((unit - 0xD800) << 10) + (low - 0xDC00)); + i += 2; + continue; + } + } + text += wchar_t(unit); + } return true; } if (bytes.size() >= 2 && u(0) == 0xFE && u(1) == 0xFF) { why = L"it is UTF-16 big-endian (save it as UTF-8, or UTF-16 LE with its BOM)"; return false; } diff --git a/clean/installer/src/wg_core/detect.cpp b/clean/installer/src/wg_core/detect.cpp index 7e29c92f..3d822c6d 100644 --- a/clean/installer/src/wg_core/detect.cpp +++ b/clean/installer/src/wg_core/detect.cpp @@ -367,7 +367,7 @@ wstring SignatureInfo(const wstring& path) { } } } - } else if ((unsigned long)r == 0x800B0100u) out = L"no Authenticode signature"; + } else if ((uint32_t)r == 0x800B0100u) out = L"no Authenticode signature"; else out = L"Authenticode check failed (" + Hex32((DWORD)r) + L")"; td.stateAction = 2; // WTD_STATEACTION_CLOSE verify(reinterpret_cast(INVALID_HANDLE_VALUE), &action, &td); @@ -448,6 +448,49 @@ wstring SteamAppId(const wstring& exe) { } return L""; } +// Every library folder a libraryfolders.vdf lists ("path" lines). +static void VdfLibraries(const wstring& vdf, std::vector& libs) { + string raw; + if (!LibraryAccess(vdf) || !ReadAll(vdf, raw)) return; + const wstring t = FromUtf8(raw); + for (size_t pos = 0; pos < t.size();) { + const size_t nl = t.find(L'\n', pos); + const wstring line = t.substr(pos, nl == wstring::npos ? wstring::npos : nl - pos); + pos = nl == wstring::npos ? t.size() : nl + 1; + if (Lower(QuotedAt(line, 0)) != L"path") continue; + const wstring lib = UnescapeJsonLike(QuotedAt(line, 1)); + if (lib.empty()) continue; + bool dup = false; + for (auto& l : libs) dup |= IEq(FullPath(l), FullPath(lib)); + if (!dup) libs.push_back(lib); + } +} +ProtonPrefix FindProtonPrefix(const wstring& exe) { + ProtonPrefix out; + out.appid = SteamAppId(exe); + if (out.appid.empty()) return out; + out.state = ProtonPrefixState::NotStarted; + wstring root = Parent(exe); + while (!root.empty() && !(IEq(BaseName(Parent(root)), L"common") && IEq(BaseName(Parent(Parent(root))), L"steamapps"))) root = Parent(root); + const wstring ownLib = Parent(Parent(Parent(root))); // the library folder: \steamapps\common\ + std::vector libs{ownLib}; + VdfLibraries(Join(Join(ownLib, L"steamapps"), L"libraryfolders.vdf"), libs); + if (LibraryRegistryAccess(L"Steam SteamPath")) { + wstring steam = RegString(HKEY_CURRENT_USER, L"Software\\Valve\\Steam", L"SteamPath"); + for (auto& c : steam) if (c == L'/') c = L'\\'; + if (!steam.empty()) { + bool dup = false; + for (auto& l : libs) dup |= IEq(FullPath(l), FullPath(steam)); + if (!dup) libs.push_back(steam); + VdfLibraries(Join(Join(steam, L"steamapps"), L"libraryfolders.vdf"), libs); + } + } + for (auto& lib : libs) { + const wstring user = Join(Join(Join(Join(Join(Join(lib, L"steamapps"), L"compatdata"), out.appid), L"pfx"), L"drive_c"), L"users\\steamuser"); + if (LibraryAccess(user) && IsDir(user)) { out.state = ProtonPrefixState::Found; out.userDir = user; return out; } + } + return out; +} // The folder with the FidelityFX DLLs the game loads: the exe folder if it has one of them, else the first folder below // the game root that has the FFX API DLL, else the first that has an FSR 3.0 component DLL. wstring FindInstallDir(const wstring& exe) { diff --git a/clean/installer/src/wg_core/detect.h b/clean/installer/src/wg_core/detect.h index 425d44c5..746355c7 100644 --- a/clean/installer/src/wg_core/detect.h +++ b/clean/installer/src/wg_core/detect.h @@ -64,6 +64,14 @@ bool StartsOnPresetK(const wstring& dir, const Record* rec); // The Steam app id of a game in a Steam library (its appmanifest_.acf in the steamapps folder that holds the game's // folder, matched by installdir; any depth of the exe below steamapps\common\); empty elsewhere. wstring SteamAppId(const wstring& exe); +// A Steam game's Proton prefix (Linux, Steam on Proton): \steamapps\compatdata\\pfx. NotSteam: the exe is in no Steam +// library. NotStarted: a Steam game, but Steam has made no Proton folder for it yet (the game was never started under Proton). +// Found: userDir is the prefix's Windows profile, ...\pfx\drive_c\users\steamuser (Documents and AppData\Local are below it). +// The game's own library is searched first, then every library its libraryfolders.vdf and the Steam folder's list name; a test +// build reads only what its library scope allows (LibraryAccess). Read-only. +enum class ProtonPrefixState { NotSteam, NotStarted, Found }; +struct ProtonPrefix { ProtonPrefixState state = ProtonPrefixState::NotSteam; wstring appid, userDir; }; +ProtonPrefix FindProtonPrefix(const wstring& exe); wstring FindInstallDir(const wstring& exe); GameTarget InspectGame(Context& ctx, const wstring& exe, const wstring& displayName = L""); } // namespace wg diff --git a/clean/installer/src/wg_core/install.cpp b/clean/installer/src/wg_core/install.cpp index e67d4ff0..7bf1a718 100644 --- a/clean/installer/src/wg_core/install.cpp +++ b/clean/installer/src/wg_core/install.cpp @@ -934,8 +934,12 @@ std::vector DoInstall(Context& ctx, const GameTarget& target, const Mod WriteFileAtomic(un, ctx.restorer, ctx.restorerSize); if (Sha256File(un) != Sha256Bytes(ctx.restorer, ctx.restorerSize)) Fail(L"Verification failed after writing the uninstaller"); } else { +#ifdef _WIN32 JournalCreate(journal, Join(state, L"uninstall.exe"), false); CopyChecked(SelfPath(), Join(state, L"uninstall.exe")); +#endif + // Linux: no restorer is embedded and a copy of this ELF program would not start in the game's Wine prefix; the + // launcher's own uninstall removes the install (README-linux.md) } if (ctx.perGameEntry) RegisterUninstall(ctx, m, state, target.name); JournalCreate(journal, Join(state, L"owned-files.json"), false); diff --git a/clean/installer/src/wg_core/launcher.cpp b/clean/installer/src/wg_core/launcher.cpp index 6cea53f6..7ae6a533 100644 --- a/clean/installer/src/wg_core/launcher.cpp +++ b/clean/installer/src/wg_core/launcher.cpp @@ -996,7 +996,7 @@ static bool OptInKey(const wstring& exe, const IniKeyChange& c) { // the next seq, written atomically; the caller holds the record's lock. A record that cannot be read is not written over; // every failure is said in the notes and warnings. bool WriteLauncherModelChoice(Context& ctx, const wstring& dir, char model, std::vector& notes, std::vector* warnings) { - const std::filesystem::path path = Join(StateDir(dir), wgchoice::kRecordFile); + const std::filesystem::path path = FsPath(Join(StateDir(dir), wgchoice::kRecordFile)); wgchoice::Record after; std::string why; const wgchoice::Outcome o = wgchoice::RecordChoiceUnlocked(path, model, wgchoice::Source::Launcher, &after, &why); @@ -1103,7 +1103,7 @@ void ApplyProfile(Context& ctx, const wstring& dir, const Profile& p, std::vecto // settings): the front end's upgrade migration, which reads wronggpu.ini's model item under the same lock, comes wholly // before or after this. // Not taken in time (the game is writing its state): nothing is applied. - const std::filesystem::path recordPath = Join(StateDir(dir), wgchoice::kRecordFile); + const std::filesystem::path recordPath = FsPath(Join(StateDir(dir), wgchoice::kRecordFile)); wgchoice::Lock lock(recordPath); if (!lock.ok()) Fail(L"Settings not applied: the game is saving WrongGPU's state right now (" + FromUtf8(wgchoice::OutcomeWords(wgchoice::Outcome::NoLock)) + @@ -1580,7 +1580,11 @@ OpResult RunOp(Context& ctx, const OpRequest& r, Ui& ui) { if (r.dir.empty() || !LoadRecord(RecordPath(r.dir), m) || m.legacy) Fail(L"No WrongGPU installation record was found in " + r.dir + L".", EXIT_NOT_INSTALLED); if (m.regkey.empty()) { m.regkey = RegKeyFor(r.dir); SaveRecord(RecordPath(r.dir), m); } RegisterUninstall(ctx, m, StateDir(r.dir), GameDisplayName(m.exe)); +#ifdef _WIN32 res.message = L"WrongGPU stays in " + r.dir + L" with its own uninstaller"; +#else // no uninstaller is written into a game folder on Linux: the launcher is what removes it + res.message = L"WrongGPU stays in " + r.dir + L"; open the WrongGPU launcher and use Uninstall on the game's page to remove it"; +#endif break; } case Op::Rollback: Rollback(ctx, r.dir, ui, res); break; @@ -2067,12 +2071,12 @@ static void DeleteLeftWhenFree(Context& ctx, const wstring& dir, const wstring& } } -bool RemoveSharedData(Context& ctx, wstring* why, wstring* kept) { +bool RemoveSharedData(Context& ctx, wstring* why, wstring* kept, bool launcherOwnsIt) { if (kept) kept->clear(); try { const SharedDataLook s = LookAtSharedData(ctx); if (!s.there) { LogLine(ctx, L"remove data: no shared data folder: nothing to remove"); return true; } - if (s.installed) { if (why) *why = L"WrongGPU is installed for this user: its own uninstall removes this data. Nothing was removed."; return false; } + if (s.installed && !launcherOwnsIt) { if (why) *why = L"WrongGPU is installed for this user: its own uninstall removes this data. Nothing was removed."; return false; } if (s.anyGame) { if (why) *why = L"a game still has WrongGPU and uses this data. Uninstall WrongGPU from it first. Nothing was removed."; return false; } const wstring shared = AppDataPath(); const DWORD sharedAttrs = GetFileAttributesW(shared.c_str()); @@ -2528,6 +2532,7 @@ UpdateInfo CheckForUpdate(const GlobalSettings& gs, const wstring& currentVersio if (!gs.updateCheck) { u.message = L"Check for new releases is off."; return u; } // the switch's own name (Settings) if (gs.updateUrl.empty()) { u.message = L"Check for new releases is on, but there's no release address to check."; return u; } if (Lower(gs.updateUrl).rfind(L"https://", 0) != 0) { u.message = L"The release address must start with https://."; return u; } + if (!DownloadsAvailable()) { u.message = L"WrongGPU doesn't check for new releases on Linux yet. Get the new AppImage from the release page yourself."; return u; } URL_COMPONENTS uc{}; uc.dwStructSize = sizeof(uc); wchar_t host[256] = {}, path[2048] = {}; uc.lpszHostName = host; uc.dwHostNameLength = 256; uc.lpszUrlPath = path; uc.dwUrlPathLength = 2048; diff --git a/clean/installer/src/wg_core/launcher.h b/clean/installer/src/wg_core/launcher.h index 9c82aa4c..6fdba6da 100644 --- a/clean/installer/src/wg_core/launcher.h +++ b/clean/installer/src/wg_core/launcher.h @@ -315,7 +315,9 @@ LauncherUninstallLook LookBeforeLauncherUninstall(Context& ctx); struct SharedDataLook { bool there = false, anyGame = false, installed = false, modelData = false, rrData = false; }; SharedDataLook LookAtSharedData(Context& ctx); // ignore-files.txt stays (convert_ignore.h): *kept gets "kept ignore-files.txt (...)" and its path when there was one. -bool RemoveSharedData(Context& ctx, wstring* why, wstring* kept = nullptr); +// launcherOwnsIt: the launcher's own settings file in that folder (launcher.ini) does not count as an installed launcher using it +// (the native Linux launcher keeps its settings there and has no install: appimage.h removes both). +bool RemoveSharedData(Context& ctx, wstring* why, wstring* kept = nullptr, bool launcherOwnsIt = false); // The hidden cleanups this process started (SelfUninstall's moved exe and folders) handed again for what is still there, // as the program ends: they try for an hour, and a window may stay open longer than that. The window calls it last. void RetryCleanupsAtExit(Context& ctx); diff --git a/clean/installer/src/wg_core/leftovers.cpp b/clean/installer/src/wg_core/leftovers.cpp index cd46b8de..8944712c 100644 --- a/clean/installer/src/wg_core/leftovers.cpp +++ b/clean/installer/src/wg_core/leftovers.cpp @@ -243,7 +243,9 @@ std::vector AdoptLeftovers(Context& ctx, const wstring& exe, const wstr EnsureDir(state); SaveRecord(RecordPath(dir), m); if (ctx.restorer && ctx.restorerSize) WriteFileAtomic(Join(state, L"uninstall.exe"), ctx.restorer, ctx.restorerSize); +#ifdef _WIN32 else CopyChecked(SelfPath(), Join(state, L"uninstall.exe")); +#endif // Linux: no restorer (install.cpp: the same reason) if (ctx.perGameEntry) RegisterUninstall(ctx, m, state, GameDisplayName(exe)); WriteOwnedFiles(dir, m); AddManagedGame(dir); diff --git a/clean/installer/src/wg_core/logs.cpp b/clean/installer/src/wg_core/logs.cpp index 85a2431b..073b7021 100644 --- a/clean/installer/src/wg_core/logs.cpp +++ b/clean/installer/src/wg_core/logs.cpp @@ -332,7 +332,7 @@ Bundle CollectLogs(Context& ctx, const wstring& dirIn, const wstring& outZip, co string reportWhy; bool modelMatches = reportMapBytes && Sha256Bytes(reportMapBytes, reportMapSize) == MapSha256(ctx, reportK); if (modelMatches) modelMatches = wgc::load_map_bytes(string(static_cast(reportMapBytes), reportMapSize), reportMap, {}).code == wgc::kOk; - if (modelMatches) modelMatches = wgc::verify_model_file(*reportMap.map, std::filesystem::path(reportModelFile), reportWhy); + if (modelMatches) modelMatches = wgc::verify_model_file(*reportMap.map, FsPath(reportModelFile), reportWhy); else reportWhy = "the embedded converter map is invalid"; s += L"Model data: " + (modelMatches ? L"present and matching (" + reportModelFile + L")" : L"not usable (" + FromUtf8(reportWhy) + L")") + L"\r\n"; } // (WrongGPU.exe's lines above: unchanged, kept at their indentation so the diff shows it) @@ -350,7 +350,7 @@ Bundle CollectLogs(Context& ctx, const wstring& dirIn, const wstring& outZip, co wgc::ModelFileInfo mInfo; wstring state; if (!IsFile(mFile)) state = L"no Model M file on this PC"; - else if (!wgc::verify_model_file(*mMap.map, std::filesystem::path(mFile), mWhy, &mInfo)) state = L"the Model M file is not usable (" + FromUtf8(mWhy) + L")"; + else if (!wgc::verify_model_file(*mMap.map, FsPath(mFile), mWhy, &mInfo)) state = L"the Model M file is not usable (" + FromUtf8(mWhy) + L")"; else state = wstring(mInfo.absent_groups.empty() ? L"from the DLSS file (weights in the Model M file)" : L"WrongGPU's own (no weights in the Model M file)") + (mInfo.same_map ? L"; file written with this installer's converter data" : L"; file written with other converter data"); s += L"Model M output filter: " + state + L"\r\n"; @@ -358,7 +358,7 @@ Bundle CollectLogs(Context& ctx, const wstring& dirIn, const wstring& outZip, co if (installed && !m.modelM.empty()) s += L"Model M file at the last install: " + m.modelM + L"\r\n"; } s += L"The in-game provider can differ from the startup choice; the runtime session/context logs identify the actual model and fallback.\r\n"; - s += L"Windows: " + sys.win.text + L"\r\n"; + s += sys.win.label + L": " + sys.win.text + L"\r\n"; s += L"GPU: " + (sys.gpu.name.empty() ? wstring(L"unknown") : sys.gpu.name) + L" (driver " + (sys.gpu.driver.empty() ? wstring(L"unknown") : sys.gpu.driver) + L")\r\n"; auto hips = HipCandidates(); s += L"AMD HIP runtime: " + (hips.empty() ? wstring(L"not found") : hips[0]) + L"\r\n"; diff --git a/clean/installer/src/wg_core/model.cpp b/clean/installer/src/wg_core/model.cpp index 708df5c4..3df6e360 100644 --- a/clean/installer/src/wg_core/model.cpp +++ b/clean/installer/src/wg_core/model.cpp @@ -19,7 +19,7 @@ bool ExistingModelValid(Context& ctx, wstring* why, wgc::ModelFileInfo* info) { if (info) *info = wgc::ModelFileInfo(); if (!LoadEmbeddedMap(ctx) || !IsFile(ModelFile(ctx))) { if (why) *why = L"no converted model on this PC"; return false; } string w; - const bool ok = wgc::verify_model_file(*ctx.map.map, std::filesystem::path(ModelFile(ctx)), w, info); + const bool ok = wgc::verify_model_file(*ctx.map.map, FsPath(ModelFile(ctx)), w, info); if (why) *why = FromUtf8(w); return ok; } @@ -138,7 +138,7 @@ ModelState FindModel(Context& ctx, const GameTarget* t, const wstring& userDll, ModelCandidate chosenCand, withoutCand; for (auto& cand : cands) { auto conv = std::make_shared(); - const wgc::Result r = wgc::convert_file(*ctx.map.map, std::filesystem::path(cand.path), opt, *conv, + const wgc::Result r = wgc::convert_file(*ctx.map.map, FsPath(cand.path), opt, *conv, [&ctx](const string& s) { LogLine(ctx, L"converter: " + FromUtf8(s)); }); if (r.code == wgc::kOk) { if (wgc::has_every_group(*ctx.map.map, *conv)) { chosen = conv; chosenCand = cand; break; } @@ -249,7 +249,7 @@ bool ReplaceModel(Context& ctx, const ModelState& m, wstring& problem) { const wstring previous = ModelFile(ctx) + L".previous"; auto cleanup = [&] { if (IsDir(side)) RemoveTree(side); DeleteFileW(previous.c_str()); }; cleanup(); // what an interrupted earlier run left behind - const wgc::Result r = wgc::write_converted(*ctx.map.map, *m.converted, std::filesystem::path(side), false, + const wgc::Result r = wgc::write_converted(*ctx.map.map, *m.converted, FsPath(side), false, [&ctx](const string& s) { LogLine(ctx, L"converter: " + FromUtf8(s)); }); if (r.code != wgc::kOk) { problem = L"it could not be saved next to the model data in use"; cleanup(); return false; } #ifdef WRONGGPU_TESTING @@ -260,7 +260,7 @@ bool ReplaceModel(Context& ctx, const ModelState& m, wstring& problem) { #endif string w; wgc::ModelFileInfo info; - if (!wgc::verify_model_file(*ctx.map.map, std::filesystem::path(sideFile), w, &info) || (needGroups && !info.absent_groups.empty()) || !info.same_map) { + if (!wgc::verify_model_file(*ctx.map.map, FsPath(sideFile), w, &info) || (needGroups && !info.absent_groups.empty()) || !info.same_map) { problem = L"the new file failed its check" + (w.empty() ? wstring() : L" (" + FromUtf8(w) + L")"); cleanup(); return false; } @@ -308,7 +308,7 @@ ModelResult WriteModel(Context& ctx, const ModelState& m, Ui& ui) { return res; } } else { - const wgc::Result r = wgc::write_converted(*ctx.map.map, *m.converted, std::filesystem::path(ModelDir(ctx)), false, + const wgc::Result r = wgc::write_converted(*ctx.map.map, *m.converted, FsPath(ModelDir(ctx)), false, [&ctx](const string& s) { LogLine(ctx, L"converter: " + FromUtf8(s)); }); if (r.code != wgc::kOk) Fail(FromUtf8(r.message)); wstring why; diff --git a/clean/installer/src/wg_core/optiedition.cpp b/clean/installer/src/wg_core/optiedition.cpp index 267ac95a..3981a7b1 100644 --- a/clean/installer/src/wg_core/optiedition.cpp +++ b/clean/installer/src/wg_core/optiedition.cpp @@ -132,6 +132,12 @@ static bool Download(const EditionInfo& e, const wstring& dest, const std::funct EditionResult GetEdition(Context& ctx, const wstring& dataDir, const std::function& progress) { EditionResult r; try { + if (!DownloadsAvailable()) { // Linux: nothing is downloaded (no HTTP client yet), whatever the build pins + r.detail = L"downloads are off on Linux"; + r.error = L"WrongGPU doesn't download anything on Linux yet. In Settings, under OptiScaler, choose an OptiScaler file or folder of your own, then try again."; + LogLine(ctx, L"OptiScaler: " + r.detail + L"; the player's own OptiScaler download is needed"); + return r; + } const EditionInfo e = PinnedEdition(); if (e.url.empty() || dataDir.empty()) { r.error = L"WrongGPU couldn't download its OptiScaler edition."; diff --git a/clean/installer/src/wg_core/pe.cpp b/clean/installer/src/wg_core/pe.cpp index 19eb890b..7dd1f268 100644 --- a/clean/installer/src/wg_core/pe.cpp +++ b/clean/installer/src/wg_core/pe.cpp @@ -143,6 +143,14 @@ uint32_t ReadPeLinkTime(const uint8_t* b, size_t n) { } uint32_t FileLinkTime(const wstring& path) { MappedFile f(path, 2ull << 30); +#ifndef _WIN32 + // the Linux launcher is an ELF file with no link time of its own: the file's own time stands in (it orders two copies alike) + if (f.size >= 4 && memcmp(f.data, "\x7f" "ELF", 4) == 0) { + WIN32_FILE_ATTRIBUTE_DATA d{}; + if (!GetFileAttributesExW(path.c_str(), GetFileExInfoStandard, &d)) return 0; + return (uint32_t)((((unsigned long long)d.ftLastWriteTime.dwHighDateTime << 32 | d.ftLastWriteTime.dwLowDateTime) - 116444736000000000ull) / 10000000ull); + } +#endif return ReadPeLinkTime(f.data, f.size); } diff --git a/clean/installer/src/wg_core/rr.cpp b/clean/installer/src/wg_core/rr.cpp index 7699aba5..6725c924 100644 --- a/clean/installer/src/wg_core/rr.cpp +++ b/clean/installer/src/wg_core/rr.cpp @@ -241,7 +241,7 @@ bool RrDataValid(Context& ctx, wstring* why) { if (!LoadFMap(ctx)) { if (why) *why = ctx.fMapError; return false; } if (!IsFile(RrDataFile())) { if (why) *why = L"no converted Ray Reconstruction data on this PC"; return false; } string w; - const bool ok = wgc::verify_model_file(*ctx.fMap.map, std::filesystem::path(RrDataFile()), w); + const bool ok = wgc::verify_model_file(*ctx.fMap.map, FsPath(RrDataFile()), w); if (why) *why = FromUtf8(w); return ok; } @@ -353,7 +353,7 @@ RrDataState FindRrData(Context& ctx, const GameTarget* t, const wstring& userDll wgc::SearchOptions opt; for (auto& c : cands) { auto conv = std::make_shared(); - const wgc::Result r = wgc::convert_file(*ctx.fMap.map, std::filesystem::path(c.first), opt, *conv, + const wgc::Result r = wgc::convert_file(*ctx.fMap.map, FsPath(c.first), opt, *conv, [&ctx](const string& s) { LogLine(ctx, L"converter (RR): " + FromUtf8(s)); }); if (r.code == wgc::kOk) { m.ok = true; m.dll = c.first; m.origin = c.second; m.version = FromUtf8(conv->version); m.converted = conv; @@ -388,11 +388,11 @@ bool WriteRrData(Context& ctx, const RrDataState& m, wstring* why) { const wstring side = RrDataDir() + L".new"; if (IsDir(side)) RemoveTree(side); EnsureDir(ModelBaseDir()); - const wgc::Result r = wgc::write_converted(*ctx.fMap.map, *m.converted, std::filesystem::path(side), false, + const wgc::Result r = wgc::write_converted(*ctx.fMap.map, *m.converted, FsPath(side), false, [&ctx](const string& s) { LogLine(ctx, L"converter (RR): " + FromUtf8(s)); }); const wstring sideFile = Join(side, FromUtf8(wgc::kModelFileName)); string w; - if (r.code != wgc::kOk || !wgc::verify_model_file(*ctx.fMap.map, std::filesystem::path(sideFile), w)) { + if (r.code != wgc::kOk || !wgc::verify_model_file(*ctx.fMap.map, FsPath(sideFile), w)) { if (why) *why = r.code != wgc::kOk ? FromUtf8(r.message) : L"the converted Ray Reconstruction data failed its check (" + FromUtf8(w) + L")"; // the converter names no cause: a full disk is the one the player can fix, so it is said when it is the case ULARGE_INTEGER freeBytes{}; diff --git a/clean/installer/src/wg_core/rrconfig.cpp b/clean/installer/src/wg_core/rrconfig.cpp index cc1c6017..7d5c39ad 100644 --- a/clean/installer/src/wg_core/rrconfig.cpp +++ b/clean/installer/src/wg_core/rrconfig.cpp @@ -5,6 +5,7 @@ #include +#include "detect.h" #include "rrconfig_line.h" #include "rr.h" @@ -58,11 +59,79 @@ static wstring LocalAppDataDir() { return l; } -wstring RrConfigFile(Context& ctx, const RrConfigGame& g, wstring* why, bool* known) { +static const wchar_t kWindowsFoldersFile[] = L"windows-folders.txt"; +wstring RememberedWindowsFolder(Context& ctx, const wstring& exe) { + string text; + if (ctx.ownDataDir.empty() || !ReadAll(Join(ctx.ownDataDir, kWindowsFoldersFile), text)) return L""; + for (size_t at = 0; at < text.size();) { + size_t nl = text.find('\n', at); + if (nl == string::npos) nl = text.size(); + string line = text.substr(at, nl - at); + at = nl + 1; + if (!line.empty() && line.back() == '\r') line.pop_back(); + const size_t tab = line.find('\t'); + if (tab != string::npos && IEq(FromUtf8(line.substr(0, tab).c_str()), exe)) return FromUtf8(line.substr(tab + 1).c_str()); + } + return L""; +} +bool RememberWindowsFolder(Context& ctx, const wstring& exe, const wstring& folder, wstring* why) { + if (ctx.ownDataDir.empty()) { if (why) *why = L"the launcher has no data folder to keep it in"; return false; } + if (!folder.empty()) { + if (!IsDir(folder)) { if (why) *why = folder + L" is not a folder"; return false; } + if (!IsDir(Join(folder, L"Documents")) && !IsDir(Join(folder, L"AppData"))) { + if (why) *why = folder + L" has no Documents or AppData folder in it. Choose the Windows user folder inside the game's Wine prefix (drive_c/users/)"; + return false; + } + } + string text, out; + ReadAll(Join(ctx.ownDataDir, kWindowsFoldersFile), text); + for (size_t at = 0; at < text.size();) { + size_t nl = text.find('\n', at); + if (nl == string::npos) nl = text.size(); + string line = text.substr(at, nl - at); + at = nl + 1; + if (!line.empty() && line.back() == '\r') line.pop_back(); + const size_t tab = line.find('\t'); + if (line.empty() || (tab != string::npos && IEq(FromUtf8(line.substr(0, tab).c_str()), exe))) continue; + out += line + "\n"; + } + if (!folder.empty()) out += ToUtf8(exe) + "\t" + ToUtf8(folder) + "\n"; + EnsureDir(ctx.ownDataDir); + try { WriteFileAtomic(Join(ctx.ownDataDir, kWindowsFoldersFile), out.data(), out.size()); } + catch (const SetupError& e) { if (why) *why = L"the choice could not be saved (" + e.msg + L")"; return false; } + return true; +} + +// Natively on Linux: the game's Windows profile folder (its Proton prefix's, or the one the player pointed at). false: not native +// Linux, or a test root is in effect (the roots as always). true with an empty root and *why: not known. +static bool NativeProfileRoot(Context& ctx, const RrConfigGame& g, const wstring& exe, wstring& root, wstring* why) { + if (!NativeLinux()) return false; +#ifdef WRONGGPU_TESTING + if (g.documents ? !PlayerDocumentsDir(ctx).empty() : !LocalAppDataDir().empty()) return false; +#else + if (g.documents && !ctx.playerDocuments.empty()) return false; +#endif + wstring user; + const ProtonPrefix pp = FindProtonPrefix(exe); + if (pp.state == ProtonPrefixState::Found) user = pp.userDir; + else if (pp.state == ProtonPrefixState::NotStarted) { + if (why) *why = L"Steam has not made this game's Proton folder yet. Start the game once from Steam, then try again"; + } else { + const wstring chosen = RememberedWindowsFolder(ctx, exe); + if (chosen.empty()) { if (why) *why = L"WrongGPU cannot find this game's Windows folder, because it is not a Steam game. Point it at the game's Windows user folder once (the folder with Documents and AppData in it, inside the game's Wine prefix). Run: WrongGPU windows-folder \"\" \"\""; } + else if (!IsDir(chosen)) { if (why) *why = L"the Windows folder chosen for this game is gone (" + chosen + L"). Choose it again"; } + else user = chosen; + } + root = user.empty() ? wstring() : Join(user, g.documents ? L"Documents" : L"AppData\\Local"); + return true; +} + +wstring RrConfigFile(Context& ctx, const RrConfigGame& g, const wstring& exe, wstring* why, bool* known) { if (known) *known = false; - const wstring root = g.documents ? PlayerDocumentsDir(ctx) : LocalAppDataDir(); + wstring root; + if (!NativeProfileRoot(ctx, g, exe, root, why)) root = g.documents ? PlayerDocumentsDir(ctx) : LocalAppDataDir(); if (root.empty()) { - if (why) *why = g.documents ? L"the Documents folder could not be found" : L"the local application data folder could not be found"; + if (why && why->empty()) *why = g.documents ? L"the Documents folder could not be found" : L"the local application data folder could not be found"; return L""; } const wstring config = Join(root, g.folder); @@ -104,16 +173,22 @@ wstring RrConfigNotice(const RrConfigGame& g, bool protectedFolder, bool beforeF } wstring RrConfigSteps(const RrConfigGame& g, const wstring& file) { - const wstring folder = !file.empty() ? Parent(file) + const bool lin = NativeLinux(); // a native Linux player: file manager, text editor, file permissions (the game itself is Windows', under Proton) + const wstring folder = !file.empty() ? ShownPath(Parent(file)) + : lin ? (g.documents ? L"Documents/" : L"AppData/Local/") + wstring(g.folder) + L"/Windows, in the game's Windows user folder" : g.documents ? L"Documents\\" + wstring(g.folder) + L"\\Windows" : L"%LOCALAPPDATA%\\" + wstring(g.folder) + L"\\Windows"; wstring t = L"Ray Reconstruction in " + wstring(g.name) + L": the steps\n\n" - L"1. Open this folder in File Explorer (if it isn't there, start the game once: it makes it):\n" + folder + L"\n" - L"2. Open Engine.ini there with Notepad (create the file if it isn't there).\n" + + (lin ? L"1. Open this folder in your file manager (if it isn't there, start the game once: it makes it):\n" + : L"1. Open this folder in File Explorer (if it isn't there, start the game once: it makes it):\n") + folder + L"\n" + + (lin ? L"2. Open Engine.ini there with a text editor (create the file if it isn't there).\n" + : L"2. Open Engine.ini there with Notepad (create the file if it isn't there).\n") + L"3. Find the line [" + FromUtf8(kSection) + L"]. If the file doesn't have it, add it at the end.\n" L"4. Add this line under it (Copy the line puts it on the clipboard):\n" + RrConfigLineW() + L"\n"; if (g.readOnly) - t += L"5. Save the file. Then right-click Engine.ini, choose Properties, tick Read-only and click OK: " + wstring(g.name) + - L" removes the file on every start otherwise."; + t += lin ? L"5. Save the file. Then make Engine.ini read-only: in your file manager open its properties, then Permissions, and set it to read-only " + L"(or run chmod a-w Engine.ini in that folder). " + wstring(g.name) + L" removes the file on every start otherwise." + : L"5. Save the file. Then right-click Engine.ini, choose Properties, tick Read-only and click OK: " + wstring(g.name) + + L" removes the file on every start otherwise."; else t += L"5. Save the file."; return t; @@ -260,7 +335,7 @@ int RrConfigWaiting(Context& ctx, const Record& m, const string& fixSetting) { const RrConfigGame* g = RrConfigGameFor(m.exe); if (!g || fixSetting != "on" || m.rrconfig.present) return 0; bool known = false; - if (RrConfigFile(ctx, *g, nullptr, &known).empty()) return 0; + if (RrConfigFile(ctx, *g, m.exe, nullptr, &known).empty()) return 0; return known ? 1 : -1; } @@ -277,7 +352,7 @@ bool ApplyRrConfig(Context& ctx, const wstring& dir, Record& m, std::vector\steamapps\compatdata\\pfx\drive_c\users\steamuser (empty with +// a plain sentence in *why until Steam has made it: the game was never started), a game that is not a Steam game the Windows +// folder the player pointed at once (RememberWindowsFolder; empty with *why while there is none). A test root (ctx.playerDocuments, +// WRONGGPU_TEST_DOCUMENTS, a LOCALAPPDATA test root) stays first. On Windows and under Wine the roots are as always. +wstring RrConfigFile(Context& ctx, const RrConfigGame& g, const wstring& exe, wstring* why, bool* known = nullptr); +// A game that is not a Steam game (Heroic, Lutris, Bottles): the player's Windows user folder for it (the folder that holds +// Documents and AppData, inside the game's Wine prefix: ...\drive_c\users\), kept in the launcher's data folder +// (windows-folders.txt). Remember: false with *why when the folder is not there or has neither Documents nor AppData in it, or +// the launcher has no data folder; an empty folder forgets the game's. Remembered: empty when there is none. +bool RememberWindowsFolder(Context& ctx, const wstring& exe, const wstring& folder, wstring* why); +wstring RememberedWindowsFolder(Context& ctx, const wstring& exe); // The player's Documents folder (ctx.playerDocuments, else the known folder; test builds: WRONGGPU_TEST_DOCUMENTS only). wstring PlayerDocumentsDir(Context& ctx); @@ -58,7 +69,7 @@ wstring RrConfigLineW(); // then: r2 #7, r2b #1), 0 no line (or no file), 1 the line in [SystemSettings], 2 the line there but the file not read-only in // a game that deletes it unless it is (Borderlands 4), 3 the file is there but couldn't be read (*why: another program has it // open, access denied, saved as UTF-16; r3 #8). Read-only: nothing is created or changed. -int RrConfigLineState(Context& ctx, const RrConfigGame& g, wstring* file, wstring* why = nullptr); +int RrConfigLineState(Context& ctx, const RrConfigGame& g, const wstring& exe, wstring* file, wstring* why = nullptr); // The text edits alone: `in` with the line added (fix says what was done; *changed: the text differs; first: the first // apply, whose key found in the section is the player's), and the fix's edits taken out again. diff --git a/clean/installer/src/wg_core/rrprep.cpp b/clean/installer/src/wg_core/rrprep.cpp index 02cfee1a..1f49b523 100644 --- a/clean/installer/src/wg_core/rrprep.cpp +++ b/clean/installer/src/wg_core/rrprep.cpp @@ -133,10 +133,10 @@ wstring RrRuntimeSha(Context& ctx) { int RrPassesFor(const string& mode) { return mode.empty() || mode == "accurate" ? 1 : 2; } bool RrKernelsInGame(const wstring& exe) { - // Under Wine (Proton) a game's compiled kernels are kept by vkd3d-proton in the game folder (vkd3d-proton.cache, its + // Under Wine (Proton), and in the native Linux launcher, whose games all run under Proton, a game's compiled kernels are kept by vkd3d-proton in the game folder (vkd3d-proton.cache, its // working folder) and by Mesa in Steam's folder for the game, both under the game's own Proton: a helper in the // launcher's prefix fills neither (measured 2026-11-13, Cyberpunk 2077 under GE-Proton 11-11). - if (UnderWine()) return true; + if (UnderProton()) return true; const GameRule* r = GameRuleFor(exe); return r && r->rrKernelsInGame; } @@ -155,7 +155,7 @@ const wchar_t* RrPrepStateName(RrPrepState s) { RrPrepState RrPrepStateOf(Context& ctx, const wstring& dataDir, const wstring& exe, int passes, wstring* why) { if (RrKernelsInGame(exe)) { - if (why) *why = UnderWine() ? L"the game prepares them at its first start (under Proton its shader caches are its own)" + if (why) *why = UnderProton() ? L"the game prepares them at its first start (under Proton its shader caches are its own)" : L"the game prepares them at its first start (its graphics driver cache is its own)"; return RrPrepState::InGame; } @@ -178,7 +178,7 @@ bool RrPrepared(Context& ctx, const wstring& dataDir, const wstring& exe, int pa int PrepareRr(Context& ctx, const wstring& dataDir, const wstring& exe, const wstring& runtimeDll, int passes, const std::function& progress, wstring* why) { if (RrKernelsInGame(exe)) { - if (UnderWine()) { + if (UnderProton()) { if (why) *why = L"the game prepares them at its first start (under Proton its shader caches are its own)"; LogLine(ctx, L"Ray Reconstruction: " + BaseName(exe) + L" prepares its kernels at its first start (under Proton the game's shader caches are vkd3d-proton's " L"file in the game folder and Steam's folder for the game, which the launcher's helper can't fill); nothing prepared ahead"); diff --git a/clean/installer/src/wg_core/rrprep.h b/clean/installer/src/wg_core/rrprep.h index 35742056..db5c99ce 100644 --- a/clean/installer/src/wg_core/rrprep.h +++ b/clean/installer/src/wg_core/rrprep.h @@ -50,7 +50,7 @@ RrPrepState RrPrepStateOf(Context& ctx, const wstring& dataDir, const wstring& e const wchar_t* RrPrepStateName(RrPrepState s); // "ready", "not-prepared", "driver-changed", ... (JSON, logs) // What the launcher's start prepares again in the background: prepared before, and the driver or the runtime changed. inline bool RrStaleAfterUpdate(RrPrepState s) { return s == RrPrepState::DriverChanged || s == RrPrepState::RuntimeChanged; } -// gamerules.h, or any game under Wine (Proton): the game prepares RR's kernels at its own first start (the launcher's helper +// gamerules.h, or any game under Proton (the launcher under Wine, or the native Linux launcher): the game prepares RR's kernels at its own first start (the launcher's helper // can't reach its cache) bool RrKernelsInGame(const wstring& exe); // The helper run: the launcher's own program copied as rr-prepare\run\, started with --rr-prepare diff --git a/clean/installer/src/wg_core/util.cpp b/clean/installer/src/wg_core/util.cpp index 4977f294..9b4a0b41 100644 --- a/clean/installer/src/wg_core/util.cpp +++ b/clean/installer/src/wg_core/util.cpp @@ -673,11 +673,21 @@ wstring NowStamp(bool forFileName) { wstring EnvVar(const wchar_t* name) { wchar_t b[MAX_PATH * 2]; DWORD n = GetEnvironmentVariableW(name, b, (DWORD)std::size(b)); - return n && n < std::size(b) ? wstring(b, n) : wstring(); + if (n && n < std::size(b)) return wstring(b, n); + if (n < std::size(b)) return wstring(); + // longer than the stack buffer (n is the size it needs, with the end mark): a Linux path may be 4096 bytes + wstring big(n, L'\0'); + const DWORD m = GetEnvironmentVariableW(name, big.data(), n); + if (!m || m >= n) return wstring(); + big.resize(m); + return big; } // System DLLs this exe uses only sometimes are loaded from System32 only, never from the download folder. HMODULE LoadSystemDll(const wchar_t* name) { return LoadLibraryExW(name, nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); } bool UnderWine() { return GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "wine_get_version") != nullptr; } +bool NativeLinux() { return GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "wronggpu_native_posix") != nullptr; } +bool UnderProton() { return UnderWine() || NativeLinux(); } +bool DownloadsAvailable() { return !NativeLinux(); } wstring PathForGamePrefix(const wstring& path) { if (path.empty() || !UnderWine()) return path; // Wine's kernel32: the Unix name of a DOS path, allocated on the process heap (UTF-8). It fails when more than the last @@ -703,6 +713,21 @@ wstring PathForGamePrefix(const wstring& path) { if (c == L'/') c = L'\\'; return z; } -wstring SelfPath() { wchar_t b[MAX_PATH * 2]; DWORD n = GetModuleFileNameW(nullptr, b, (DWORD)std::size(b)); return wstring(b, n); } +wstring ShownPath(const wstring& in) { + if (!NativeLinux()) return in; + wstring p = in; + if (p.size() >= 3 && (p[0] == L'Z' || p[0] == L'z') && p[1] == L':' && (p[2] == L'\\' || p[2] == L'/')) p.erase(0, 2); + for (auto& c : p) if (c == L'\\') c = L'/'; + return p; +} +// The buffer grows until the whole name fits: a truncated name (GetModuleFileNameW returns the buffer's size) names a file that is not there +wstring SelfPath() { + for (DWORD size = MAX_PATH * 2; size <= 65536; size *= 2) { + std::vector b(size); + const DWORD n = GetModuleFileNameW(nullptr, b.data(), size); + if (n < size) return wstring(b.data(), n); + } + return wstring(); +} } // namespace wg diff --git a/clean/installer/src/wg_core/util.h b/clean/installer/src/wg_core/util.h index 8abf156c..cc02744e 100644 --- a/clean/installer/src/wg_core/util.h +++ b/clean/installer/src/wg_core/util.h @@ -2,6 +2,7 @@ // WrongGPU launcher core: small helpers (strings, paths, files, SHA-256), moved unchanged from setup.cpp. Written for // this project. #pragma once +#include #include #include "constants.h" @@ -9,6 +10,14 @@ namespace wg { +// A std::filesystem::path for a Windows-style path, for the converter, which takes host paths: on Linux "Z:\..." and '\' become +// the host's spelling (win32_posix.cpp), on Windows it is the path as it is. +#ifdef _WIN32 +inline std::filesystem::path FsPath(const wstring& p) { return std::filesystem::path(p); } +#else +std::filesystem::path FsPath(const wstring& p); +#endif + struct SetupError { wstring msg; int code = EXIT_FAILED; }; // Read-only view of a whole file (large files are scanned without copying them). struct MappedFile { @@ -169,8 +178,19 @@ wstring EnvVar(const wchar_t* name); HMODULE LoadSystemDll(const wchar_t* name); // The launcher under Wine (Linux): Wine's ntdll exports wine_get_version. bool UnderWine(); +// The launcher as a native Linux program (the POSIX layer's ntdll stand-in exports a marker; Windows' and Wine's ntdll do not). +bool NativeLinux(); +// A game that runs under Proton: the launcher is itself under Wine, or it is the native Linux launcher (whose games are Windows +// games under Proton). Ray Reconstruction's shader caches are the game's own there (rrprep.h). +bool UnderProton(); +// The launcher can fetch from the internet (OptiScaler's edition, the release check). Off in the native Linux launcher for now: it +// has no HTTP client (the POSIX layer answers WinHTTP as not available), so what needs one says so in words instead of failing. +bool DownloadsAvailable(); // A path for a game in another Wine prefix (Proton gives every game its own): under Wine the Z: path of the same file // (Z: maps the Linux root in every prefix, C: does not), otherwise the path unchanged. wstring PathForGamePrefix(const wstring& path); wstring SelfPath(); +// A path as the player reads it: on the native Linux launcher the core's Z:\home\x\... is /home/x/... (the core keeps its own +// spelling for the files themselves); Windows and Wine show the path as it is. +wstring ShownPath(const wstring& p); } // namespace wg diff --git a/clean/installer/tests/canary.cpp b/clean/installer/tests/canary.cpp index ee522884..07b981ca 100644 --- a/clean/installer/tests/canary.cpp +++ b/clean/installer/tests/canary.cpp @@ -24,3 +24,7 @@ int wmain() { return 0; #endif } + +#ifndef _WIN32 +int main() { return wmain(); } // Linux: wmain through the POSIX layer, as the launcher's own main (src/app/main.cpp) +#endif diff --git a/clean/installer/tests/canary_dll_linux.cpp b/clean/installer/tests/canary_dll_linux.cpp new file mode 100644 index 00000000..c7ce8b7f --- /dev/null +++ b/clean/installer/tests/canary_dll_linux.cpp @@ -0,0 +1,17 @@ +// SPDX-License-Identifier: MIT +// Linux: the launcher suite's load marker (tests/canary_dll.cpp on Windows): a shared library that writes .loaded +// when it is loaded, so the suite can prove a planted stand-in was never loaded. Written for this project. +#include +#include +#include + +#include + +static void Marker() {} + +__attribute__((constructor)) static void Loaded() { + Dl_info info{}; + if (!dladdr(reinterpret_cast(&Marker), &info) || !info.dli_fname) return; + const int fd = open((std::string(info.dli_fname) + ".loaded").c_str(), O_CREAT | O_WRONLY | O_TRUNC | O_CLOEXEC, 0644); + if (fd >= 0) close(fd); +} diff --git a/clean/installer/tests/convert_ignore_tests.cpp b/clean/installer/tests/convert_ignore_tests.cpp index 8957b327..d337e6c7 100644 --- a/clean/installer/tests/convert_ignore_tests.cpp +++ b/clean/installer/tests/convert_ignore_tests.cpp @@ -106,8 +106,8 @@ int main() { IgnoreLists lf = Parse("\xEF\xBB\xBF" + U8(a) + "\n" + U8(b) + "\n"); require(lf.warnings.empty() && lf.entries.size() == 2 && lf.entries[0].path == a, "UTF-8 with a BOM, LF line ends"); const wstring w16 = L"\xFEFF" + a + L"\r\n" + b + L" sha256=" + shaB + L"\r\n"; - string bytes(w16.size() * 2, '\0'); - std::memcpy(&bytes[0], w16.data(), bytes.size()); + string bytes; // UTF-16 LE written out unit by unit (wchar_t is not 2 bytes everywhere: src/platform/posix) + for (wchar_t ch : w16) bytes += string{char(ch & 0xFF), char((ch >> 8) & 0xFF)}; IgnoreLists lw = Parse(string("\xFF\xFE", 2) + bytes.substr(2)); require(lw.warnings.empty() && lw.entries.size() == 2 && lw.entries[0].path == a && lw.entries[1].path == b && lw.entries[1].sha256 == shaB, "UTF-16 LE with its BOM"); IgnoreLists ln = Parse("wronggpu-ignore-files 7\n" + U8(a) + "\n"); diff --git a/clean/installer/tests/gfx_linux_smoke.cpp b/clean/installer/tests/gfx_linux_smoke.cpp new file mode 100644 index 00000000..0b4dc584 --- /dev/null +++ b/clean/installer/tests/gfx_linux_smoke.cpp @@ -0,0 +1,229 @@ +// SPDX-License-Identifier: MIT +// Linux: draws a fixed sample through Gfx (Cairo and Pango, src/app/ui_gfx_cairo.cpp) offscreen at scale 1 and 2, writes the +// PNGs to the folder given as argument, and checks what a picture alone would not tell a test: the measurements, the dry pass, +// the fonts being the vendored ones, a fade, a clip, an unmapped icon. Looking at the PNGs is still the real check of the look. +#include "app/ui_shell.h" + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace wg::app::lui { +Theme pal; // the real one is ui_widgets.cpp's (Windows); the drawing here needs only the colours it reads +} +using namespace wg::app::lui; +using std::wstring; + +static int fails = 0; +#define CHECK(c) do { if (!(c)) { std::fprintf(stderr, "FAIL line %d: %s\n", __LINE__, #c); ++fails; } } while (0) + +static ImageP GradientImage(int w, int h) { + auto im = std::make_shared(); + im->w = w; im->h = h; + im->px.resize((size_t)w * h * 4); + for (int y = 0; y < h; ++y) + for (int x = 0; x < w; ++x) { + uint8_t* p = &im->px[((size_t)y * w + x) * 4]; + p[0] = (uint8_t)(255 * x / (w - 1)); p[1] = (uint8_t)(255 * y / (h - 1)); p[2] = 90; p[3] = 255; // BGRA, opaque + } + return im; +} + +static bool Same(const std::vector& a, const std::vector& b) { return a.size() == b.size() && std::equal(a.begin(), a.end(), b.begin()); } + +// The sample: every call the pages make a lot of, on a 480 x 360 DIP page +static void Draw(Gfx& gx, const ImageP& img) { + gx.Clear(Hex(0xF3F3F3)); + // cards with a shadow, per-corner radii, a stroke + gx.Shadow(Rc{20, 20, 200, 90}, 10, 16, 0.18f, 4); + gx.FillRound(Rc{20, 20, 200, 90}, 10, Hex(0xFFFFFF)); + gx.StrokeRound(Rc{20, 20, 200, 90}, 10, Hex(0x000000, 0.12f), 1); + gx.FillRound4(Rc{240, 20, 100, 90}, 20, 4, 20, 4, Hex(0x2D7D46)); + gx.Grad(Rc{350, 20, 110, 90}, 12, Hex(0x3B82F6), Hex(0xA855F7), 0, 0, 1, 1); + gx.GradStops(Rc{20, 124, 200, 14}, 7, {{0.f, Hex(0xEF4444)}, {0.5f, Hex(0xF59E0B)}, {1.f, Hex(0x22C55E)}}, 0, 0, 1, 0, 0.8f); + gx.Line(240, 131, 340, 131, Hex(0x111111), 2); + gx.Circle(364, 131, 6, Hex(0x2D7D46)); + gx.Ring(388, 131, 6, Hex(0x2D7D46), 2); + gx.Glow(440, 131, 26, 12, Hex(0x3B82F6, 0.8f)); + // text: each face and weight, wrapped, trimmed, centred + TS t; + t.color = Hex(0x111111); + t.size = 13; gx.Text(L"Regular text, Selawik 13", Rc{20, 150, 220, 18}, t); + t.weight = 600; gx.Text(L"Semibold text", Rc{20, 170, 220, 18}, t); + t.weight = 700; gx.Text(L"Bold text", Rc{20, 190, 220, 18}, t); + t.weight = 300; gx.Text(L"Light text", Rc{20, 210, 220, 18}, t); + t.weight = 400; t.face = F_MONO; gx.Text(L"mono 0123456789", Rc{20, 230, 220, 18}, t); + t.face = F_DISPLAY; t.size = 22; t.weight = 600; gx.Text(L"Display 22", Rc{250, 146, 220, 30}, t); + t = TS{}; t.color = Hex(0x111111); t.wrap = true; + gx.Text(L"Wrapped text breaks at the box's width and carries on to as many lines as it needs.", Rc{250, 180, 210, 60}, t); + t.trim = true; t.color = Hex(0x444444); + gx.Text(L"Trimmed wrapped text keeps the lines that fit the box and ends the last one with an ellipsis sign.", Rc{250, 250, 210, 34}, t); + t = TS{}; t.color = Hex(0x111111); + gx.Text(L"One line is cut with an ellipsis when it is too long for its box", Rc{20, 252, 200, 18}, t); + t.align = 1; gx.Text(L"Centred", Rc{20, 272, 200, 18}, t); + t.align = 2; t.underline = true; gx.Text(L"Right, underlined", Rc{20, 292, 200, 18}, t); + t = TS{}; t.color = Hex(0x555555); t.spacing = 2; t.lineH = 20; t.wrap = true; + gx.Text(L"Spaced and tall lines of text", Rc{20, 312, 140, 40}, t); + t = TS{}; t.color = Hex(0x111111); t.wrap = true; + gx.TextLead(L"Ready. The files are in place and nothing else needs doing.", 6, Hex(0x2D7D46), 700, Rc{170, 312, 290, 40}, t); + // icons + const wchar_t icons[] = {ic::check, ic::warn, ic::gear, ic::search, ic::folder, ic::download, ic::trash, ic::chevron}; + for (int i = 0; i < 8; ++i) gx.Icon(icons[i], 30 + i * 26.f, 350.f, 16, Hex(0x111111)); + // an image: cover in a rounded box, contain with a shadow, nearest + gx.ImageCover(img, Rc{20, 360, 100, 60}, 8, 0.5f); + gx.ImageContain(img, Rc{130, 360, 90, 60}, 1, 1, 1, 10); + gx.ImageNearest(img, Rc{230, 360, 60, 60}, 6); + // a clip and a fade + gx.PushClip(Rc{300, 360, 50, 50}); + gx.Fill(Rc{280, 340, 90, 90}, Hex(0x3B82F6)); + gx.PopClip(); + gx.PushRoundClip(Rc{360, 360, 50, 50}, 25); + gx.Fill(Rc{350, 350, 100, 100}, Hex(0xA855F7)); + gx.PopRoundClip(); + gx.PushFade(0.5f); + gx.FillRound(Rc{420, 360, 50, 50}, 8, Hex(0x000000)); + gx.PopFade(); +} + +int main(int argc, char** argv) { + const std::string out = argc > 1 ? argv[1] : "gfx-smoke"; + mkdir(out.c_str(), 0755); + pal.black = Hex(0x000000); + pal.artShade = Hex(0x000000); + pal.text = Hex(0x111111); + + // No system fonts: an empty fontconfig set, so only the vendored fonts exist (a bare machine, the AppImage's worst case) + const std::string conf = out + "/fonts.conf"; + std::filesystem::remove_all(out + "/fc-cache"); // a stale cache would hide a font added or taken away + if (FILE* f = std::fopen(conf.c_str(), "w")) { + std::fprintf(f, "\n\n%s/fc-cache\n", out.c_str()); + std::fclose(f); + setenv("FONTCONFIG_FILE", conf.c_str(), 1); + } + Gfx gx; + CHECK(gx.Init()); + CHECK(gx.iconFont); // the vendored Fluent System Icons were found and registered + const ImageP img = GradientImage(64, 40); + const int W = 480, H = 430; + + // measurements (no target needed) + TS t; + t.size = 13; + CHECK(gx.TextW(L"Hello", t) > 0); + CHECK(gx.TextW(L"Hello world", t) > gx.TextW(L"Hello", t)); + CHECK(gx.TextW(L"Hello", TS{}) > 0 && gx.TextW(L"W", t) > gx.TextW(L"i", t)); + // The arrow the pages use ("0.4.5 \u2192 0.6.0") is a glyph of the vendored Noto Sans Math, not Pango's hex box for a missing + // one: a box is as wide as the box of any other code of four digits (U+FDD0 is a noncharacter no font has) + CHECK(std::fabs(gx.TextW(L"\u2192", t) - gx.TextW(L"\uFDD0", t)) > 1.f); + CHECK(gx.TextW(L"\u2192", t) > 0.5f * t.size && gx.TextW(L"\u2192", t) < 1.5f * t.size); + TS big = t; big.size = 26; + CHECK(gx.TextW(L"Hello", big) > 1.8f * gx.TextW(L"Hello", t)); + TS bold = t; bold.weight = 700; + CHECK(gx.TextW(L"Hello world", bold) > gx.TextW(L"Hello world", t)); // Selawik Bold is really used, not a fallback + TS wrap = t; wrap.wrap = true; + const wstring para = L"A paragraph of words that must wrap when the box is narrow but fits on one line when it is wide."; + const float wide = gx.TextH(para, 2000, wrap), narrow = gx.TextH(para, 120, wrap); + CHECK(wide > 0 && narrow > 1.9f * wide); + TS tall = wrap; tall.lineH = 30; + CHECK(gx.TextH(para, 120, tall) > narrow); + float ex = 0, ey = 0, ex2 = 0, ey2 = 0; + gx.TextEnd(L"abc", 200, t, ex, ey); + gx.TextEnd(L"abcdef", 200, t, ex2, ey2); + CHECK(ex > 0 && ex2 > ex); + gx.TextEnd(para, 120, wrap, ex, ey); + CHECK(ey > 0); // the last character is on a later line + + for (float s : {1.f, 2.f}) { + CHECK(gx.BeginOffscreen(W, H, s)); + Draw(gx, img); + gx.EndFrame(); + std::vector before; + UINT pw = 0, ph = 0; + CHECK(gx.Pixels(before, pw, ph)); + CHECK(pw == (UINT)(W * s) && ph == (UINT)(H * s)); + char name[64]; + std::snprintf(name, sizeof name, "/smoke-%dx.png", (int)s); + const wstring path = wstring(out.begin(), out.end()) + wstring(name, name + std::strlen(name)); + CHECK(gx.SavePng(path)); + struct stat st{}; + CHECK(stat((out + name).c_str(), &st) == 0 && st.st_size > 5000); + + auto at = [&](float x, float y) { const uint8_t* p = &before[((size_t)(y * s) * pw + (size_t)(x * s)) * 4]; return std::array{p[0], p[1], p[2], p[3]}; }; + CHECK(at(2, 2)[0] == 0xF3 && at(2, 2)[3] == 255); // the cleared page + CHECK(at(120, 100)[0] == 255 && at(120, 100)[1] == 255); // the card's white + CHECK(at(120, 114)[0] < 0xF3 && at(120, 114)[0] > 0xC0); // the card's shadow darkens the page under it, softly + CHECK(at(120, 122)[0] > at(120, 114)[0]); // and fades with the distance + CHECK(at(290, 60)[1] > at(290, 60)[0]); // the green card (BGRA: G over B) + CHECK(at(325, 385)[0] > 200 && at(325, 385)[2] < 120); // inside the clip: blue (B high, R low) + CHECK(at(290, 385)[0] == 0xF3); // the clip kept the blue off the page outside it + CHECK(at(445, 385)[2] > 100 && at(445, 385)[2] < 150); // black at half opacity over 0xF3: about 121 + CHECK(at(364, 131)[1] > 100 && at(364, 131)[2] < 100); // the circle + + // the dry pass draws nothing and an unmapped icon draws nothing + gx.dry = true; + Draw(gx, img); + gx.dry = false; + std::vector after; + CHECK(gx.Pixels(after, pw, ph) && Same(before, after)); + gx.Icon(0xE000, 30, 30, 16, Hex(0xFF0000)); + CHECK(gx.Pixels(after, pw, ph) && Same(before, after)); + } + + // a rotation stays open through a clip, a round clip and a fade that are popped inside it (the matrix is not rebuilt from identity) + for (int kind = 0; kind < 3; ++kind) { + CHECK(gx.BeginOffscreen(100, 100, 1)); + gx.Clear(Hex(0xFFFFFF)); + gx.PushRotate(50, 50, 90); // clockwise: a bar to the right of the centre turns to below it + if (kind == 0) { gx.PushClip(Rc{0, 0, 100, 100}); gx.PopClip(); } + else if (kind == 1) { gx.PushRoundClip(Rc{0, 0, 100, 100}, 4); gx.PopRoundClip(); } + else { gx.PushFade(1.f); gx.PopFade(); } + gx.Fill(Rc{70, 45, 20, 10}, Hex(0x000000)); + gx.PopRotate(); + std::vector rp; + UINT rw = 0, rh = 0; + CHECK(gx.Pixels(rp, rw, rh)); + auto dark = [&](int x, int y) { return rp[((size_t)y * rw + x) * 4] < 64; }; + CHECK(dark(50, 80)); // the bar at the bottom: the rotation survived the pop + CHECK(!dark(80, 50)); // and not where it would be unrotated + gx.EndFrame(); + } + + // text and icons really leave ink: a blank page, then one glyph + CHECK(gx.BeginOffscreen(60, 40, 2)); + gx.Clear(Hex(0xFFFFFF)); + gx.Icon(ic::check, 30, 20, 20, Hex(0x000000)); + std::vector px; + UINT w = 0, h = 0; + CHECK(gx.Pixels(px, w, h)); + int ink = 0; + for (size_t i = 0; i < px.size(); i += 4) if (px[i] < 200) ++ink; + CHECK(ink > 20); + gx.EndFrame(); + + // a backdrop blur softens a hard edge, keeps the page outside the rounded shape, and a fade/clip open makes it decline + CHECK(gx.BeginOffscreen(100, 60, 1)); + gx.Fill(Rc{0, 0, 50, 60}, Hex(0x000000)); + gx.Fill(Rc{50, 0, 50, 60}, Hex(0xFFFFFF)); + CHECK(gx.Backdrop(Rc{20, 10, 60, 40}, 8, 4, 1)); + CHECK(gx.Pixels(px, w, h)); + const int mid = px[((size_t)30 * w + 50) * 4], edge = px[((size_t)30 * w + 30) * 4], outside = px[((size_t)30 * w + 10) * 4]; + CHECK(mid > 60 && mid < 200 && edge < mid && outside == 0); + gx.PushFade(0.5f); + CHECK(!gx.Backdrop(Rc{20, 10, 60, 40}, 8, 4, 1)); + gx.PopFade(); + gx.Freeze(7); + gx.Fill(Rc{0, 0, 100, 60}, Hex(0xFF0000)); + CHECK(gx.DrawFrozen(7) && !gx.DrawFrozen(8)); + CHECK(gx.Pixels(px, w, h) && px[((size_t)30 * w + 10) * 4 + 2] == 0); // the frozen picture is back: no red + gx.EndFrame(); + + if (fails) { std::fprintf(stderr, "gfx-linux-smoke: %d failure(s)\n", fails); return 1; } + std::printf("gfx-linux-smoke: ok (PNGs in %s)\n", out.c_str()); + return 0; +} diff --git a/clean/installer/tests/jpeg_linux_tests.cpp b/clean/installer/tests/jpeg_linux_tests.cpp new file mode 100644 index 00000000..c2f9f30d --- /dev/null +++ b/clean/installer/tests/jpeg_linux_tests.cpp @@ -0,0 +1,140 @@ +// SPDX-License-Identifier: MIT +// Linux: the JPEG decoder (src/app/jpeg_decode_linux.cpp). The test makes its own JPEGs with libjpeg (no art is stored in the +// repo): four colour blocks, so size, orientation and colours are all visible. JPEG is lossy, so colours are checked within a +// tolerance at the middle of each block, away from the edges where chroma bleeds. +// Usage: jpeg-linux-tests (writes its files under $TMPDIR, or the current folder) +// jpeg-linux-tests --make only writes that picture (run_linux_ui_tests.py's synthetic Steam art) +#include "app/jpeg_decode_linux.h" + +#include +#include +#include +#include + +#include + +using namespace wg::app::lui; + +static int fails = 0; +#define CHECK(c) do { if (!(c)) { std::fprintf(stderr, "FAIL line %d: %s\n", __LINE__, #c); ++fails; } } while (0) + +struct Rgb { int r, g, b; }; +// top left, top right, bottom left, bottom right +static const Rgb kBlocks[4] = {{220, 30, 30}, {30, 200, 40}, {40, 50, 230}, {240, 240, 240}}; + +static bool MakeJpeg(const std::string& path, int w, int h, bool progressive, bool grey) { + FILE* f = std::fopen(path.c_str(), "wb"); + if (!f) return false; + jpeg_compress_struct c; + jpeg_error_mgr e; + c.err = jpeg_std_error(&e); + jpeg_create_compress(&c); + jpeg_stdio_dest(&c, f); + c.image_width = (JDIMENSION)w; + c.image_height = (JDIMENSION)h; + c.input_components = grey ? 1 : 3; + c.in_color_space = grey ? JCS_GRAYSCALE : JCS_RGB; + jpeg_set_defaults(&c); + jpeg_set_quality(&c, 92, TRUE); + if (progressive) jpeg_simple_progression(&c); + jpeg_start_compress(&c, TRUE); + std::vector row((size_t)w * c.input_components); + while (c.next_scanline < c.image_height) { + const int y = (int)c.next_scanline; + for (int x = 0; x < w; ++x) { + const Rgb& k = kBlocks[(y >= h / 2 ? 2 : 0) + (x >= w / 2 ? 1 : 0)]; + if (grey) row[x] = (unsigned char)((k.r * 30 + k.g * 59 + k.b * 11) / 100); + else { row[(size_t)x * 3] = (unsigned char)k.r; row[(size_t)x * 3 + 1] = (unsigned char)k.g; row[(size_t)x * 3 + 2] = (unsigned char)k.b; } + } + JSAMPROW r = row.data(); + jpeg_write_scanlines(&c, &r, 1); + } + jpeg_finish_compress(&c); + jpeg_destroy_compress(&c); + std::fclose(f); + return true; +} + +static bool Near(const std::vector& px, int w, int x, int y, const Rgb& want, int tol) { + const uint8_t* p = &px[((size_t)y * w + x) * 4]; // BGRA + auto d = [](int a, int b) { return a > b ? a - b : b - a; }; + return d(p[0], want.b) <= tol && d(p[1], want.g) <= tol && d(p[2], want.r) <= tol && p[3] == 255; +} + +static void CheckBlocks(const std::vector& px, int w, int h, int tol, const char* what) { + for (int i = 0; i < 4; ++i) { + const int x = (i % 2 ? 3 * w / 4 : w / 4), y = (i / 2 ? 3 * h / 4 : h / 4); + if (!Near(px, w, x, y, kBlocks[i], tol)) { + const uint8_t* p = &px[((size_t)y * w + x) * 4]; + std::fprintf(stderr, "FAIL %s: block %d at %d,%d is B%d G%d R%d A%d, want R%d G%d B%d within %d\n", what, i, x, y, p[0], p[1], p[2], p[3], + kBlocks[i].r, kBlocks[i].g, kBlocks[i].b, tol); + ++fails; + } + } +} + +int main(int argc, char** argv) { + if (argc == 5 && std::string(argv[1]) == "--make") return MakeJpeg(argv[2], std::atoi(argv[3]), std::atoi(argv[4]), false, false) ? 0 : 1; + const char* t = std::getenv("TMPDIR"); + const std::string dir = (t && *t) ? t : "."; + const std::string base = dir + "/jpeg-linux-test-", plain = base + "plain.jpg", prog = base + "prog.jpg", grey = base + "grey.jpg"; + CHECK(MakeJpeg(plain, 192, 128, false, false)); + CHECK(MakeJpeg(prog, 192, 128, true, false)); + CHECK(MakeJpeg(grey, 192, 128, false, true)); + + int w = 0, h = 0; + std::vector px; + CHECK(LooksLikeJpeg(plain.c_str())); + // full size: the asked width is the image's own + CHECK(DecodeJpegFile(plain.c_str(), 192, w, h, px)); + CHECK(w == 192 && h == 128 && px.size() == (size_t)192 * 128 * 4); + if (px.size() == (size_t)192 * 128 * 4) CheckBlocks(px, w, h, 14, "full size"); + // a progressive file gives the same picture + CHECK(DecodeJpegFile(prog.c_str(), 192, w, h, px)); + CHECK(w == 192 && h == 128); + if (px.size() == (size_t)192 * 128 * 4) CheckBlocks(px, w, h, 14, "progressive"); + // the DCT scaling: never narrower than asked, by 2, 4 or 8 + CHECK(DecodeJpegFile(plain.c_str(), 90, w, h, px)); + CHECK(w == 96 && h == 64); + if (px.size() == (size_t)96 * 64 * 4) CheckBlocks(px, w, h, 14, "half size"); + CHECK(DecodeJpegFile(plain.c_str(), 40, w, h, px)); + CHECK(w == 48 && h == 32); + CHECK(DecodeJpegFile(plain.c_str(), 1, w, h, px)); + CHECK(w == 24 && h == 16); + // grey becomes opaque BGRA with equal channels + CHECK(DecodeJpegFile(grey.c_str(), 192, w, h, px)); + CHECK(w == 192 && h == 128 && px.size() == (size_t)192 * 128 * 4); + if (px.size() == (size_t)192 * 128 * 4) { const uint8_t* p = &px[((size_t)96 * 192 + 150) * 4]; CHECK(p[0] == p[1] && p[1] == p[2] && p[3] == 255 && p[0] > 200); } + + // failures leave the outputs alone and do not crash + w = h = 7; px.assign(3, 9); + CHECK(!DecodeJpegFile((base + "missing.jpg").c_str(), 100, w, h, px) && w == 7 && px.size() == 3); + const std::string cut = base + "cut.jpg", junk = base + "junk.jpg", late = base + "late.jpg"; + { + FILE* in = std::fopen(plain.c_str(), "rb"); + std::vector all(1 << 20); + const size_t n = in ? std::fread(all.data(), 1, all.size(), in) : 0; + if (in) std::fclose(in); + CHECK(n > 400); + FILE* o = std::fopen(cut.c_str(), "wb"); + if (o) { std::fwrite(all.data(), 1, 300, o); std::fclose(o); } // headers only, no picture + o = std::fopen(junk.c_str(), "wb"); + if (o) { std::fputs("not a picture at all", o); std::fclose(o); } + // a whole picture, then a Huffman table marker with length 0 before the end: libjpeg fails in + // jpeg_finish_decompress, after the pixel buffer exists (the error path that has to free it) + o = std::fopen(late.c_str(), "wb"); + const unsigned char bad[4] = {0xFF, 0xC4, 0x00, 0x00}; + if (o && n > 2) { std::fwrite(all.data(), 1, n - 2, o); std::fwrite(bad, 1, 4, o); std::fwrite(all.data() + n - 2, 1, 2, o); } + if (o) std::fclose(o); + } + CHECK(!DecodeJpegFile(late.c_str(), 100, w, h, px) && w == 7 && px.size() == 3); + CHECK(LooksLikeJpeg(cut.c_str())); + CHECK(!DecodeJpegFile(cut.c_str(), 100, w, h, px) || w > 0); // libjpeg pads a truncated file grey: either answer is a clean one + CHECK(!LooksLikeJpeg(junk.c_str())); + CHECK(!DecodeJpegFile(junk.c_str(), 100, w, h, px)); + CHECK(!LooksLikeJpeg((base + "missing.jpg").c_str())); + + for (const std::string* f : {&plain, &prog, &grey, &cut, &junk, &late}) std::remove(f->c_str()); + std::printf(fails ? "jpeg-linux: %d failure(s)\n" : "jpeg-linux: all checks passed\n", fails); + return fails ? 1 : 0; +} diff --git a/clean/installer/tests/launcher_appimage_cases.py b/clean/installer/tests/launcher_appimage_cases.py new file mode 100644 index 00000000..f6adba3e --- /dev/null +++ b/clean/installer/tests/launcher_appimage_cases.py @@ -0,0 +1,131 @@ +# SPDX-License-Identifier: MIT +"""Uninstall WrongGPU in the native Linux launcher (S5): the AppImage file ($APPIMAGE) and WrongGPU's data folder go after the +player's confirmation, and nothing else. The suite never points APPIMAGE at the program under test: it uses a fake file with an +AppImage's header, in the work folder, a fake data folder (the suite's LOCALAPPDATA test root) and a made-up process folder +(WRONGGPU_TEST_PROC_ROOT) holding what the real AppImage mount leaves: a mount table line for $APPDIR, a process started from the +AppImage file and its /dev/fuse descriptor naming the mount. Every refusal leaves both +untouched; a game that still has WrongGPU stops it; files next to the AppImage, in the data folder's parent and in the games +stay. For run_launcher_tests.py (--native-linux). Written for this project.""" +import os +import shutil + +import launcher_proton_cases as pc +from native_linux import host +from run_installer_tests import read, write + +HEAD = b"\x7fELF\x02\x01\x01\x00AI\x02\x00\x00\x00\x00\x00" + + +def run(t, opti): + print("\n[appimage] native Linux: Uninstall WrongGPU deletes the AppImage and WrongGPU's data folder, nothing else") + base = os.path.join(t.work, "appimage-case") + shutil.rmtree(host(base), ignore_errors=True) + apps = os.path.join(base, "Applications") + image = os.path.join(apps, "WrongGPU-0.6.5-x86_64.AppImage") + sibling = os.path.join(apps, "OtherApp.AppImage") + write(image, HEAD + b"fake payload") + write(sibling, HEAD + b"another program's AppImage") + other = os.path.join(apps, "WrongGPU-old.AppImage") # a real WrongGPU AppImage, but not the one that is running + write(other, HEAD + b"an older WrongGPU AppImage") + data = os.path.join(t.env["LOCALAPPDATA"], "WrongGPU") # the core's AppDataPath() in this run + neighbour = os.path.join(t.env["LOCALAPPDATA"], "OtherProgram", "keep.txt") + write(neighbour, b"not WrongGPU's") + write(os.path.join(data, "launcher.ini"), b"[settings]\r\n") + write(os.path.join(data, "model", "M", "model.wgcm"), b"converted data") + appdir = os.path.realpath(os.path.dirname(host(t.exe))) # this program stands in for the one inside the AppImage's mount + saved = t.env + st = os.stat(appdir) + proc = os.path.join(host(base), "proc") + + def make_proc(server_exe=None, connection=None): + """The process folder after a runtime mounted $APPDIR: the mount's own device number is its FUSE connection number.""" + shutil.rmtree(proc, ignore_errors=True) + os.makedirs(os.path.join(proc, "self")) + with open(os.path.join(proc, "self", "mountinfo"), "w") as f: + f.write("22 1 0:5 / /sys rw - sysfs sysfs rw\n1003 60 %d:%d / %s ro,nosuid,nodev - fuse.WrongGPU-0.6.5-x86_64.AppImage WrongGPU-0.6.5-x86_64.AppImage ro\n" % + (os.major(st.st_dev), os.minor(st.st_dev), appdir.replace(" ", "\\040"))) + if server_exe: + os.makedirs(os.path.join(proc, "4242", "fdinfo")) + os.symlink(server_exe, os.path.join(proc, "4242", "exe")) + with open(os.path.join(proc, "4242", "fdinfo", "5"), "w") as f: + f.write("pos:\t0\nflags:\t02100002\nmnt_id:\t43\nino:\t136\nfuse_connection:\t%d\n" % (os.minor(st.st_dev) if connection is None else connection)) + make_proc(host(image)) + + def with_env(**kw): + e = dict(saved) + for k in ("APPIMAGE", "APPDIR"): + e.pop(k, None) + e["WRONGGPU_TEST_PROC_ROOT"] = proc + e.update({k: v for k, v in kw.items() if v is not None}) + return e + + def untouched(): + return os.path.isfile(image) and os.path.isfile(other) and os.path.isfile(os.path.join(data, "model", "M", "model.wgcm")) and os.path.isfile(neighbour) + try: + # refusals: nothing is deleted whatever the reason + for tag, env, want in ( + ("no $APPIMAGE", with_env(APPDIR=appdir), "not running from an AppImage"), + ("a name that is not WrongGPU's", with_env(APPIMAGE=host(sibling), APPDIR=appdir), "not WrongGPU"), + ("a program that is not inside it", with_env(APPIMAGE=host(image), APPDIR=os.path.join(host(base), "elsewhere")), "not inside"), + ("a valid WrongGPU AppImage that is not the one running (the real $APPDIR)", with_env(APPIMAGE=host(other), APPDIR=appdir), "cannot prove"), + ("a mount that no process started from the file serves", with_env(APPIMAGE=host(image), APPDIR=appdir, WRONGGPU_TEST_PROC_ROOT=os.path.join(host(base), "proc-empty")), "not a mounted AppImage"), + ("no AppImage header", None, "not an AppImage file")): + if env is None: + bare = os.path.join(apps, "WrongGPU-bare.AppImage") + write(bare, b"just text") + env = with_env(APPIMAGE=host(bare), APPDIR=appdir) + t.env = env + rc = t.run("uninstall-appimage", "--confirm") + t.check("appimage: refused for " + tag + ", in words, nothing deleted", rc != 0 and want in t.j.get("error", "") and untouched(), (rc, t.j)) + good = with_env(APPIMAGE=host(image), APPDIR=appdir) + # a mount that something else serves: the case of the folder is the disk's + t.env = with_env(APPIMAGE=host(image), APPDIR=appdir.upper()) + rc = t.run("uninstall-appimage", "--confirm") + t.check("appimage: $APPDIR in another letter case is not the folder: refused, nothing deleted", rc != 0 and "not inside" in t.j.get("error", "") and untouched(), (rc, t.j)) + t.env = good + rc = t.run("uninstall-appimage") + t.check("appimage: without --confirm it says what would go and deletes nothing", rc == 0 and t.j.get("appimage", {}).get("removed") is False and + t.j["appimage"].get("file", "").endswith("WrongGPU-0.6.5-x86_64.AppImage") and t.j["appimage"].get("data", "").endswith("WrongGPU") and untouched(), (rc, t.j)) + # a game that still has WrongGPU stops it: both stay (its record reads the data) + gb, gexe = pc._game(t, os.path.join(base, "games", "Some Game"), "Game.exe") + t.env = saved + rc = t.run("install", gexe, "--opti=" + opti, "--noscan", "--force", "--experimental") + t.env = good + rc = t.run("uninstall-appimage", "--confirm", "--noscan") + t.check("appimage: a game still has WrongGPU: refused, nothing deleted", rc != 0 and "still has WrongGPU" in t.j.get("error", "") and untouched(), (rc, t.j)) + t.env = saved + rc = t.run("uninstall", gexe) + game_files = sorted(os.listdir(os.path.dirname(gexe))) + t.env = good + rc = t.run("uninstall-appimage", "--confirm", "--noscan") + t.check("appimage: confirmed: the AppImage file and the data folder are gone, exit 0", rc == 0 and t.j.get("appimage", {}).get("removed") is True and + not os.path.exists(image) and not os.path.exists(data), (rc, t.j, os.path.exists(data))) + t.check("appimage: nothing else went: another AppImage next to it, another program's data folder, the game's files", + os.path.isfile(sibling) and os.path.isfile(neighbour) and os.path.isdir(apps) and os.path.isfile(gexe) and + sorted(os.listdir(os.path.dirname(gexe))) == game_files, (os.listdir(apps), os.path.isfile(neighbour))) + rc = t.run("uninstall-appimage", "--confirm", "--noscan") + t.check("appimage: a second run finds no file and refuses", rc != 0 and not os.path.exists(data), (rc, t.j)) + # links in the data folder are removed, never followed: what they lead to stays + keep_dir = os.path.join(base, "outside-data") + write(os.path.join(keep_dir, "keep.txt"), b"keep") + write(os.path.join(keep_dir, "launcher.ini"), b"[settings]\r\n") + write(image, HEAD + b"fake payload") + os.symlink(host(keep_dir), host(data)) # the data folder itself is a link + rc = t.run("uninstall-appimage", "--confirm", "--noscan") + t.check("appimage: a data folder that is a link: the link goes, its target and what is in it stay", + rc == 0 and not os.path.lexists(host(data)) and not os.path.exists(image) and + read(os.path.join(keep_dir, "keep.txt")) == b"keep" and os.path.isfile(os.path.join(keep_dir, "launcher.ini")), (rc, t.j)) + nested_dir = os.path.join(base, "outside-nested") + write(os.path.join(nested_dir, "keep.txt"), b"keep") + write(os.path.join(base, "outside-file.txt"), b"keep") + write(image, HEAD + b"fake payload") + write(os.path.join(data, "launcher.ini"), b"[settings]\r\n") + write(os.path.join(data, "model", "M", "model.wgcm"), b"converted data") + os.symlink(host(nested_dir), os.path.join(host(data), "model", "linkdir")) + os.symlink(host(os.path.join(base, "outside-file.txt")), os.path.join(host(data), "linkfile")) + rc = t.run("uninstall-appimage", "--confirm", "--noscan") + t.check("appimage: links inside the data folder are removed, their targets stay", + rc == 0 and not os.path.lexists(host(data)) and not os.path.exists(image) and + read(os.path.join(nested_dir, "keep.txt")) == b"keep" and read(os.path.join(base, "outside-file.txt")) == b"keep", (rc, t.j)) + finally: + t.env = saved diff --git a/clean/installer/tests/launcher_build_facts.py b/clean/installer/tests/launcher_build_facts.py index ba207a2e..2689dd62 100644 --- a/clean/installer/tests/launcher_build_facts.py +++ b/clean/installer/tests/launcher_build_facts.py @@ -2,12 +2,20 @@ """What the launcher under test was built with, for run_launcher_tests.py: checks that follow the build instead of assuming a release build (a fresh clone's suite build differs from a release in its version, its payload and its direct route). Kept out of run_launcher_tests.py, which stays below the 256 KB source limit. Written for this project.""" +import importlib.util import os import re import shutil from run_installer_tests import read, write, STAND_IN_RUNTIME +# the Linux testing build's identity sum (tools/elf_testing_identity.py: what the PE checksum is on Windows); loaded by its +# path now, before native_linux gives this module Windows-spelled paths +_spec = importlib.util.spec_from_file_location( + "elf_testing_identity", os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "tools", "elf_testing_identity.py")) +elf_identity = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(elf_identity) + def restorer_ok(un, exe): """uninstall.exe is the restorer, not the launcher: byte for byte the restorer built next to the launcher @@ -68,11 +76,37 @@ def pe_checksum(data, at): return (s + len(data)) & 0xFFFFFFFF +def elf_testing_identity(data): + """testing_identity for a Linux program (ELF): the identity section with the identity text, its SHA-256 sum matching the + file (nothing changed or appended after its link; tools/elf_testing_identity.py), and the test hooks' strings (wide + strings are UTF-32 on Linux) inside its sections.""" + import struct + try: + sections = elf_identity.sections(data) + end = max((off + size for _, off, size, kind in sections if kind != elf_identity.SHT_NOBITS), default=0) + if [m for m in TEST_HOOKS if m.encode("utf-32-le") not in data[:end]]: + return "the test hooks' strings are not in its sections" + try: + _, body = elf_identity.identity_section(data) + except ValueError: + return "no %s section (not a WRONGGPU_TESTING build)" % elf_identity.SECTION.decode() + if not body.startswith(IDENTITY_TEXT + b"\0"): + return "its %s section does not hold the identity text" % elf_identity.SECTION.decode() + slot = elf_identity.sum_slot(data) + if data[slot:slot + 32] != elf_identity.expected_sum(data, slot): + return "its identity sum is missing or does not match (changed after its link, or not a testing build)" + return "" + except (struct.error, ValueError, IndexError) as e: + return "not a readable ELF file (%s)" % e + + def testing_identity(data): """Why data is not a WRONGGPU_TESTING build's program, read from its structure ('' when it is one): a valid PE whose checksum matches (nothing changed or appended after its link), the identity resource in its resource directory, and the - test hooks' strings inside its sections (not in data appended to it).""" + test hooks' strings inside its sections (not in data appended to it). A Linux program: elf_testing_identity.""" import struct + if data[:4] == b"\x7fELF": + return elf_testing_identity(data) try: if data[:2] != b"MZ": return "not a program (no MZ header)" @@ -214,10 +248,17 @@ def new_run_folder(root, prefix="run"): CANARIES = ("wg-test-canary.exe", "wg-test-canary-strings.exe") -LOAD_MARKER = "wg-test-canary-dll.dll" # writes .loaded when loaded (tests/canary_dll.cpp) +LOAD_MARKER = "wg-test-canary-dll.dll" # writes .loaded when loaded (tests/canary_dll.cpp; Linux: canary_dll_linux.cpp) BUILD_LIST = "wg-test-build.sha256" # written by the build next to the launcher: SHA-256 of WrongGPU.exe and the canaries +def build_names(exe): + """The launcher's and the canaries' names in the build list for the launcher's platform: Linux programs have no .exe.""" + if read(exe)[:4] == b"\x7fELF": + return "WrongGPU", tuple(n[:-len(".exe")] for n in CANARIES) + return "WrongGPU.exe", CANARIES + + def verified_canaries(exe): """The canaries built in THIS build: their names in \\wg-test-build.sha256 (written by the testing build after it links WrongGPU.exe, CMakeLists.txt), whose WrongGPU.exe line is this launcher's SHA-256 and whose canary lines @@ -229,10 +270,11 @@ def verified_canaries(exe): except (OSError, UnicodeDecodeError) as e: return {}, "no build list %s (%s)" % (BUILD_LIST, e) listed = dict(zip(lines[1::2], lines[0::2])) - if listed.get("WrongGPU.exe") != hashlib.sha256(read(exe)).hexdigest(): + launcher, canaries = build_names(exe) + if listed.get(launcher) != hashlib.sha256(read(exe)).hexdigest(): return {}, "the build list is not this launcher's (another build)" out = {} - for name in CANARIES + (LOAD_MARKER,): + for name in canaries + (LOAD_MARKER,): p = os.path.join(d, name) data = read(p) if os.path.isfile(p) else b"" if not data or listed.get(name) != hashlib.sha256(data).hexdigest(): @@ -276,7 +318,25 @@ def self_checks(t): d = os.path.join(t.work, "self-checks") shutil.rmtree(d, ignore_errors=True) os.makedirs(d) - t.check("preflight: the launcher under test is a WRONGGPU_TESTING build (its identity resource, a matching PE checksum, the hooks)", + # Linux (--native-linux): the same guards on the Linux build (an identity section and its sum for the PE resource and + # checksum, canaries without .exe, a symbolic link for a junction); paths given to a program or a child suite are host paths + native = t.native + if native: + import ctypes + import native_linux + hp, entry_flag = native_linux.host, "--native-linux" + + def link_folder(link, target): + os.symlink(target, link) + return True + else: + hp, entry_flag = (lambda p: p), "--launcher" + + def link_folder(link, target): + return subprocess.run(["cmd.exe", "/d", "/c", "mklink", "/J", link, target], stdout=subprocess.PIPE, stderr=subprocess.PIPE).returncode == 0 + remove_link = os.remove if native else os.rmdir # (the link or junction only, never its target) + t.check("preflight: the launcher under test is a WRONGGPU_TESTING build " + + ("(its identity section, a matching identity sum, the hooks)" if native else "(its identity resource, a matching PE checksum, the hooks)"), not missing_test_hooks(t.exe), missing_test_hooks(t.exe)) # programs that are not testing builds, each leaving .started when it starts (tests/canary.cpp; built with the # launcher in a testing build): one plain, one carrying the hooks' strings. Only the canaries THIS build made are ever @@ -287,15 +347,18 @@ def self_checks(t): canaries, why_not = verified_canaries(t.exe) t.check("negative controls: the canaries are this build's (wg-test-build.sha256 next to the launcher names this launcher " "and the canaries' bytes)", bool(canaries), why_not) - for name in [n for n in CANARIES if n in canaries]: + canary_names = build_names(t.exe)[1] + for name in [n for n in canary_names if n in canaries]: data = canaries[name] canary = os.path.join(d, name) write(canary, data) + if native: + os.chmod(canary, 0o755) # (a program on Linux) started = canary + ".started" if hashlib.sha256(read(canary)).digest() != hashlib.sha256(data).digest(): t.check("negative control %s: the copy is the verified file" % name, False) continue - subprocess.run([canary], env=t.env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=60) + subprocess.run([hp(canary)], env=t.env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=60) runs = os.path.isfile(started) if runs: os.remove(started) @@ -314,13 +377,13 @@ def self_checks(t): rwhy = str(e) entry = [] suite = os.path.join(os.path.dirname(os.path.abspath(__file__)), "run_launcher_tests.py") - for args in (["--launcher", canary], ["--launcher", t.exe, "--no-direct-launcher", canary]): # the suite's entry points - p = subprocess.run([sys.executable, suite] + args + ["--work", os.path.join(d, "entry")], env=dict(os.environ), + for args in ([entry_flag, hp(canary)], [entry_flag, hp(t.exe), "--no-direct-launcher", hp(canary)]): # the suite's entry points + p = subprocess.run([sys.executable, hp(suite)] + args + ["--work", hp(os.path.join(d, "entry"))], env=dict(os.environ), stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=300) entry.append(p.returncode != 0 and b"not a WRONGGPU_TESTING build" in p.stderr + p.stdout) t.check("negative control %s: it starts when run directly (its start marker); the suite never starts it (a launcher call, " - "the junction test's call, a program run as it is, --launcher, --no-direct-launcher): refused before it runs, no start " - "marker, nothing logged" % name, + "the junction test's call, a program run as it is, %s, --no-direct-launcher): refused before it runs, no start " + "marker, nothing logged" % (name, entry_flag), runs and all("not a WRONGGPU_TESTING build" in w for w in (why, jwhy, rwhy)) and entry == [True, True] and not os.path.exists(started) and size() == before, (runs, why, jwhy, rwhy, entry)) # the real launcher changed after its link: one byte, or data appended (the hooks' strings and the identity text) @@ -328,6 +391,8 @@ def self_checks(t): mid = len(data) // 2 mixed = {"one byte changed": data[:mid] + bytes([data[mid] ^ 0xFF]) + data[mid + 1:], "data appended": data + b"".join(m.encode("utf-16-le") for m in TEST_HOOKS) + IDENTITY_TEXT} + if native and "wg-test-canary-strings" in canaries: # the hooks' strings (Linux: no sum without an identity section) + mixed["the hooks' strings, no identity section"] = canaries["wg-test-canary-strings"] if "wg-test-canary-strings.exe" in canaries: # the hooks' strings and a valid checksum, but no identity resource import struct c = bytearray(canaries["wg-test-canary-strings.exe"]) @@ -336,8 +401,8 @@ def self_checks(t): mixed["the hooks' strings and a valid checksum, no identity resource"] = bytes(c) refused = {k: bool(testing_identity(v)) for k, v in mixed.items()} t.check("preflight: a launcher changed after its link (a byte, or the hooks' strings and the identity appended), or a program " - "with the strings and a valid checksum but no identity resource, is refused", - all(refused.values()), refused) + "with the strings " + ("but no identity section" if native else "and a valid checksum but no identity resource") + ", is refused", + all(refused.values()) and len(refused) == 3, refused) # the HIP check: only the --hip mock, or in a default run a file that is not there, is ever tried (never the system's, # PATH's or ROCm's runtime), and an inherited WRONGGPU_HIP_RUNTIME / WRONGGPU_TEST_HIP_CANDIDATES is never tried: a safe # stand-in file at those paths (the --hip mock's copy, else not a library), and the probe's own log line per candidate @@ -361,15 +426,15 @@ def self_checks(t): # --work: a junction (to another folder) is refused before the isolation self-test writes or removes anything in it target, jroot = os.path.join(d, "work-target"), os.path.join(d, "work-junction") write(os.path.join(target, "library-access.log"), b"keep") - jlinked = subprocess.run(["cmd.exe", "/d", "/c", "mklink", "/J", jroot, target], stdout=subprocess.PIPE, stderr=subprocess.PIPE).returncode == 0 + jlinked = link_folder(jroot, target) suite = os.path.join(os.path.dirname(os.path.abspath(__file__)), "run_launcher_tests.py") - p = subprocess.run([sys.executable, suite, "--launcher", t.exe, "--work", jroot], env=dict(os.environ), + p = subprocess.run([sys.executable, hp(suite), entry_flag, hp(t.exe), "--work", hp(jroot)], env=dict(os.environ), stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=300) t.check("--work: a junction is refused before the isolation self-test or any create or delete in it (its target untouched)", jlinked and p.returncode != 0 and b"junction or link" in p.stderr + p.stdout and sorted(os.listdir(target)) == ["library-access.log"] and read(os.path.join(target, "library-access.log")) == b"keep", (jlinked, p.returncode, (p.stderr + p.stdout)[-300:], os.listdir(target))) if os.path.lexists(jroot): - os.rmdir(jroot) # (the junction only) + remove_link(jroot) # (the junction only) # --work holding ';', and an explicit empty --hip=: refused before anything is made, anywhere (the work path stays absent, # and nothing in the tests folder changes: no bytecode either) here = os.path.dirname(os.path.abspath(__file__)) @@ -387,7 +452,7 @@ def tree(top): child.pop("PYTHONDONTWRITEBYTECODE", None) # (the suite itself must keep its source tree clean) for name, args, folder in (("--work with ';'", ["--work", os.path.join(d, "semi;colon")], os.path.join(d, "semi;colon")), ("--hip=", ["--work", os.path.join(d, "hip-empty"), "--hip="], os.path.join(d, "hip-empty"))): - p = subprocess.run([sys.executable, suite, "--launcher", t.exe] + args, env=child, + p = subprocess.run([sys.executable, hp(suite), entry_flag, hp(t.exe)] + [hp(a) if os.sep in a or "/" in a else a for a in args], env=child, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=300) entry[name] = p.returncode != 0 and b"not run" in p.stderr + p.stdout and not os.path.exists(folder) changed = sorted(k for k in set(before_tree) | set(tree(here)) if before_tree.get(k) != tree(here).get(k)) @@ -412,13 +477,17 @@ def tree(top): if marker_dll: probe = os.path.join(d, "marker-probe", "amdhip64_7.dll") # the marker works: loaded here, it writes .loaded write(probe, marker_dll) - import ctypes - h = ctypes.WinDLL(probe) - ctypes.windll.kernel32.FreeLibrary(ctypes.c_void_p(h._handle)) + if native: + h = ctypes.CDLL(hp(probe)) + ctypes.CDLL(None).dlclose(ctypes.c_void_p(h._handle)) + else: + import ctypes + h = ctypes.WinDLL(probe) + ctypes.windll.kernel32.FreeLibrary(ctypes.c_void_p(h._handle)) loads = os.path.isfile(probe + ".loaded") write(stand_in, marker_dll) planted = sorted(os.listdir(sim)) - p = subprocess.run([sys.executable, suite, "--launcher", t.exe, "--work", sim, "--startup-only"], env=child, + p = subprocess.run([sys.executable, hp(suite), entry_flag, hp(t.exe), "--work", hp(sim), "--startup-only"], env=child, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=600) after = sorted(os.listdir(sim)) runs = [n for n in after if n not in planted] @@ -434,8 +503,7 @@ def tree(top): jw = os.path.join(d, "junction-work") os.makedirs(os.path.join(d, "elsewhere")) os.makedirs(jw) - linked = subprocess.run(["cmd.exe", "/d", "/c", "mklink", "/J", os.path.join(jw, "tmp"), os.path.join(d, "elsewhere")], - stdout=subprocess.PIPE, stderr=subprocess.PIPE).returncode == 0 + linked = link_folder(os.path.join(jw, "tmp"), os.path.join(d, "elsewhere")) jwhy = "" try: fresh_temp(jw) @@ -444,7 +512,7 @@ def tree(top): t.check("the suite's temporary folder: a junction in its place (or above it) is refused, never followed or emptied", linked and "junction or link" in jwhy and os.path.isdir(os.path.join(d, "elsewhere")), (linked, jwhy)) if os.path.lexists(os.path.join(jw, "tmp")): - os.rmdir(os.path.join(jw, "tmp")) # (removes the junction only) + remove_link(os.path.join(jw, "tmp")) # (removes the junction only) b = os.path.join(d, "Game", "bin") write(os.path.join(b, "wronggpu", "kernels", "enc.hsaco"), b"kernel") ok_kernels = rr_free(b, "file wronggpu\\kernels\\enc.hsaco") diff --git a/clean/installer/tests/launcher_core_tests.cpp b/clean/installer/tests/launcher_core_tests.cpp index eb3dae9d..d3f86703 100644 --- a/clean/installer/tests/launcher_core_tests.cpp +++ b/clean/installer/tests/launcher_core_tests.cpp @@ -2405,6 +2405,109 @@ int main() { require(StartsOnPresetK(pk, &rk) && !StartsOnPresetK(pk, &rm), "Preset K: the record's model file in the K cache"); } + // ---- S3: natively on Linux the game's profile is its Proton prefix, or the Windows folder the player pointed at ------------ + if (NativeLinux()) { + Context pc; + pc.ownDataDir = Join(dir, L"s3-data"); + const wstring savedDocs = EnvVar(L"WRONGGPU_TEST_DOCUMENTS"), savedLocal = EnvVar(L"LOCALAPPDATA"); + SetEnvironmentVariableW(L"WRONGGPU_TEST_DOCUMENTS", nullptr); // no test root: the roots the game really reads + SetEnvironmentVariableW(L"LOCALAPPDATA", nullptr); + const RrConfigGame* bl4 = RrConfigGameFor(L"Borderlands4.exe"); + const RrConfigGame* hl = RrConfigGameFor(L"HogwartsLegacy.exe"); + const wstring lib = Join(dir, L"s3-steam"); + const wstring common = Join(Join(lib, L"steamapps"), L"common"); + auto manifest = [&](const wstring& id, const wstring& installdir) { + const string t = "\"AppState\"\n{\n\t\"appid\"\t\t\"" + ToUtf8(id) + "\"\n\t\"installdir\"\t\t\"" + ToUtf8(installdir) + "\"\n}\n"; + EnsureDir(Join(lib, L"steamapps")); + WriteFileAtomic(Join(Join(lib, L"steamapps"), L"appmanifest_" + id + L".acf"), t.data(), t.size()); + }; + const wstring blExe = Join(Join(common, L"Borderlands 4"), L"OakGame\\Binaries\\Win64\\Borderlands4.exe"); + const wstring hlExe = Join(Join(common, L"Hogwarts Legacy"), L"Phoenix\\Binaries\\Win64\\HogwartsLegacy.exe"); + for (const wstring& e : {blExe, hlExe}) { EnsureDir(Parent(e)); WriteFileAtomic(e, "MZ", 2); } + manifest(L"4242", L"Borderlands 4"); + manifest(L"5151", L"Hogwarts Legacy"); + const wstring compat = Join(Join(lib, L"steamapps"), L"compatdata"); + wstring f, why; + // a Steam game Steam has made no Proton folder for: refused in plain words, nothing written, nothing made + require(bl4 && hl && FindProtonPrefix(blExe).state == ProtonPrefixState::NotStarted && FindProtonPrefix(blExe).appid == L"4242", + "Proton prefix: a Steam game with no compatdata is found as such"); + require(RrConfigLineState(pc, *bl4, blExe, &f, &why) == -1 && f.empty() && Contains(why, L"Proton folder") && Contains(why, L"Start the game once"), + "native Engine.ini: no Proton folder yet: unknown, with the plain sentence"); + require(!IsDir(compat), "native Engine.ini: nothing was made in Steam's folder"); + // the prefix exists: Documents (Borderlands 4) and AppData\Local (Hogwarts Legacy) below its steamuser + const wstring user = Join(compat, L"4242\\pfx\\drive_c\\users\\steamuser"); + EnsureDir(Join(user, L"Documents")); + require(FindProtonPrefix(blExe).state == ProtonPrefixState::Found && IEq(FindProtonPrefix(blExe).userDir, user), "Proton prefix: found by app id"); + const wstring cfgDir = Join(user, L"Documents\\My Games\\Borderlands 4\\Saved\\Config\\Windows"); + EnsureDir(cfgDir); + { const string gus = "[ScalabilityGroups]\r\n"; WriteFileAtomic(Join(cfgDir, L"GameUserSettings.ini"), gus.data(), gus.size()); } + bool known = false; + why.clear(); + require(IEq(RrConfigFile(pc, *bl4, blExe, &why, &known), Join(cfgDir, L"Engine.ini")) && known && RrConfigLineState(pc, *bl4, blExe, &f, &why) == 0, + "native Engine.ini: Borderlands 4's file is in the prefix's Documents, its folder known"); + // Hogwarts Legacy in the same library: its own app id's prefix, AppData\Local + const wstring hlUser = Join(compat, L"5151\\pfx\\drive_c\\users\\steamuser"); + const wstring hlDir = Join(hlUser, L"AppData\\Local\\Hogwarts Legacy\\Saved\\Config\\WindowsNoEditor"); + EnsureDir(hlDir); + { const string gus = "[x]\r\n"; WriteFileAtomic(Join(hlDir, L"GameUserSettings.ini"), gus.data(), gus.size()); } + require(IEq(RrConfigFile(pc, *hl, hlExe, &why, &known), Join(hlDir, L"Engine.ini")) && known, "native Engine.ini: Hogwarts Legacy's file is in its own prefix's AppData\\Local"); + // the prefix is in another library the game's own library list names (a game moved to a drive that has none) + const wstring other = Join(dir, L"s3-other-lib"); + EnsureDir(Join(Join(other, L"steamapps"), L"compatdata\\4343\\pfx\\drive_c\\users\\steamuser")); + manifest(L"4343", L"Moved Game"); + const wstring movedExe = Join(Join(common, L"Moved Game"), L"Game.exe"); + EnsureDir(Parent(movedExe)); WriteFileAtomic(movedExe, "MZ", 2); + // Steam's own spelling on Linux: "/home/..." (the vdf has no drive letter) + auto steamPath = [](const wstring& p) { string t = ToUtf8(p.size() > 2 && p[1] == L':' ? p.substr(2) : p); for (auto& c : t) if (c == '\\') c = '/'; return t; }; + const string vdf = "\"libraryfolders\"\n{\n\t\"0\"\n\t{\n\t\t\"path\"\t\t\"" + steamPath(lib) + "\"\n\t}\n\t\"1\"\n\t{\n\t\t\"path\"\t\t\"" + steamPath(other) + "\"\n\t}\n}\n"; + WriteFileAtomic(Join(Join(lib, L"steamapps"), L"libraryfolders.vdf"), vdf.data(), vdf.size()); + require(FindProtonPrefix(movedExe).state == ProtonPrefixState::Found && StartsWithI(FullPath(FindProtonPrefix(movedExe).userDir), FullPath(other)), + "Proton prefix: found in another Steam library the list names"); + // a libraryfolders.vdf that is cut off or is not text: nothing found (no crash, no guess), and the good list works again after + for (const string& bad : {string("\"libraryfolders\"\n{\n\t\"0\"\n\t{\n\t\t\"path\"\t\t\""), string("\x00\x01\xff{{{\"path\" \"", 12), string("")}) { + WriteFileAtomic(Join(Join(lib, L"steamapps"), L"libraryfolders.vdf"), bad.data(), bad.size()); + require(FindProtonPrefix(movedExe).state == ProtonPrefixState::NotStarted && FindProtonPrefix(movedExe).userDir.empty(), + "Proton prefix: a malformed libraryfolders.vdf finds nothing and does not break the search"); + } + WriteFileAtomic(Join(Join(lib, L"steamapps"), L"libraryfolders.vdf"), vdf.data(), vdf.size()); + require(FindProtonPrefix(movedExe).state == ProtonPrefixState::Found, "Proton prefix: the good list finds it again"); + // a pfx whose Windows user is not steamuser: not a prefix WrongGPU knows, nothing made in it + manifest(L"4444", L"Other User Game"); + const wstring otherUserExe = Join(Join(common, L"Other User Game"), L"Game.exe"); + EnsureDir(Parent(otherUserExe)); WriteFileAtomic(otherUserExe, "MZ", 2); + EnsureDir(Join(compat, L"4444\\pfx\\drive_c\\users\\someoneelse")); + require(FindProtonPrefix(otherUserExe).state == ProtonPrefixState::NotStarted && FindProtonPrefix(otherUserExe).userDir.empty() && + !IsDir(Join(compat, L"4444\\pfx\\drive_c\\users\\steamuser")), "Proton prefix: a pfx without drive_c\\users\\steamuser is not found, and none is made"); + // not a Steam game: no folder known until the player points at one once; it is remembered and checked each time + const wstring plain = Join(dir, L"s3-epic\\Game\\Borderlands4.exe"); + EnsureDir(Parent(plain)); WriteFileAtomic(plain, "MZ", 2); + require(FindProtonPrefix(plain).state == ProtonPrefixState::NotSteam && RrConfigFile(pc, *bl4, plain, &why).empty() && Contains(why, L"not a Steam game") && + Contains(why, L"once"), "native Engine.ini: a game that is not from Steam: no folder, asks for the Windows folder once"); + const wstring win = Join(dir, L"s3-wine-user"); + require(!RememberWindowsFolder(pc, plain, win, &why) && Contains(why, L"is not a folder"), "Windows folder: one that is not there is refused"); + EnsureDir(win); + require(!RememberWindowsFolder(pc, plain, win, &why) && Contains(why, L"no Documents or AppData"), "Windows folder: one with neither Documents nor AppData is refused"); + require(RememberedWindowsFolder(pc, plain).empty() && !IsFile(Join(pc.ownDataDir, L"windows-folders.txt")), "Windows folder: a refused choice remembers nothing"); + EnsureDir(Join(win, L"Documents")); + require(RememberWindowsFolder(pc, plain, win, &why) && IEq(RememberedWindowsFolder(pc, plain), win), "Windows folder: remembered"); + Context again; // another run of the launcher: the same data folder + again.ownDataDir = pc.ownDataDir; + known = true; + const wstring chosenCfg = Join(win, L"Documents\\My Games\\Borderlands 4\\Saved\\Config\\Windows"); + require(IEq(RrConfigFile(again, *bl4, plain, &why, &known), Join(chosenCfg, L"Engine.ini")) && !known, "native Engine.ini: the remembered folder is used again (its game folder not made yet)"); + require(RrConfigFile(again, *bl4, plain + L"2", &why).empty(), "Windows folder: remembered for that game only"); + RemoveDirectoryW(Join(win, L"Documents").c_str()); + RemoveDirectoryW(win.c_str()); + require(RrConfigFile(again, *bl4, plain, &why).empty() && Contains(why, L"is gone"), "native Engine.ini: a remembered folder that went away is said so"); + require(RememberWindowsFolder(again, plain, L"", &why) && RememberedWindowsFolder(again, plain).empty(), "Windows folder: forgotten with an empty folder"); + // a test root stays first, as before + Context rooted; + rooted.playerDocuments = Join(dir, L"s3-root-docs"); + require(IEq(RrConfigFile(rooted, *bl4, blExe, &why).substr(0, rooted.playerDocuments.size()), rooted.playerDocuments), "native Engine.ini: the test's Documents root is still first"); + if (!savedDocs.empty()) SetEnvironmentVariableW(L"WRONGGPU_TEST_DOCUMENTS", savedDocs.c_str()); + if (!savedLocal.empty()) SetEnvironmentVariableW(L"LOCALAPPDATA", savedLocal.c_str()); + } + // ---- the Engine.ini file check: a file it can't read is "couldn't read", never "no line" (r3 #8) ------------------- { Context rc; @@ -2415,27 +2518,27 @@ int main() { { const string gus = "[ScalabilityGroups]\r\n"; WriteFileAtomic(Join(cfg, L"GameUserSettings.ini"), gus.data(), gus.size()); } const wstring ini = Join(cfg, L"Engine.ini"); wstring f, rwhy; - require(bl4 && RrConfigLineState(rc, *bl4, &f, &rwhy) == 0 && IEq(f, ini), "Engine.ini check: no file is no line (0)"); + require(bl4 && RrConfigLineState(rc, *bl4, Join(dir, L"Borderlands4.exe"), &f, &rwhy) == 0 && IEq(f, ini), "Engine.ini check: no file is no line (0)"); const string utf16("\xFF\xFE[\0S\0", 6); WriteFileAtomic(ini, utf16.data(), utf16.size()); rwhy.clear(); - require(RrConfigLineState(rc, *bl4, &f, &rwhy) == 3 && rwhy.find(L"UTF-16") != wstring::npos, "Engine.ini check: UTF-16 is couldn't read (3), why says so"); + require(RrConfigLineState(rc, *bl4, Join(dir, L"Borderlands4.exe"), &f, &rwhy) == 3 && rwhy.find(L"UTF-16") != wstring::npos, "Engine.ini check: UTF-16 is couldn't read (3), why says so"); const string line = RrConfigNewFile(); WriteFileAtomic(ini, line.data(), line.size()); HANDLE held = CreateFileW(ini.c_str(), GENERIC_READ, 0, nullptr, OPEN_EXISTING, 0, nullptr); // another program has it, no sharing rwhy.clear(); - const int st = RrConfigLineState(rc, *bl4, &f, &rwhy); + const int st = RrConfigLineState(rc, *bl4, Join(dir, L"Borderlands4.exe"), &f, &rwhy); if (held != INVALID_HANDLE_VALUE) CloseHandle(held); require(held != INVALID_HANDLE_VALUE && st == 3 && rwhy.find(L"another program") != wstring::npos, "Engine.ini check: a file held open is couldn't read (3)"); - require(RrConfigLineState(rc, *bl4, &f, &rwhy) == 2, "Engine.ini check: readable again, the line there, not read-only (2)"); + require(RrConfigLineState(rc, *bl4, Join(dir, L"Borderlands4.exe"), &f, &rwhy) == 2, "Engine.ini check: readable again, the line there, not read-only (2)"); // r4 #5: saved as UTF-8 with a byte order mark (Notepad's "UTF-8 with BOM"): the section right after it is found const string bom = "\xEF\xBB\xBF"; const string withLine = bom + line; WriteFileAtomic(ini, withLine.data(), withLine.size()); - require(RrConfigLineState(rc, *bl4, &f, &rwhy) == 2, "Engine.ini check with a BOM: the line in its [SystemSettings] is there (2), not missing (r4 #5)"); + require(RrConfigLineState(rc, *bl4, Join(dir, L"Borderlands4.exe"), &f, &rwhy) == 2, "Engine.ini check with a BOM: the line in its [SystemSettings] is there (2), not missing (r4 #5)"); const string noLine = bom + "[SystemSettings]\r\nr.Other=1\r\n\r\n[Core.Log]\r\nLogNet=Log\r\n"; WriteFileAtomic(ini, noLine.data(), noLine.size()); - require(RrConfigLineState(rc, *bl4, &f, &rwhy) == 0, "Engine.ini check with a BOM, the section without the line: no line (0) (r4 #5)"); + require(RrConfigLineState(rc, *bl4, Join(dir, L"Borderlands4.exe"), &f, &rwhy) == 0, "Engine.ini check with a BOM, the section without the line: no line (0) (r4 #5)"); // adding: into that section (no second [SystemSettings]), the BOM kept; taking it out again: byte for byte as it was RrConfigFix fx; bool changed = false; diff --git a/clean/installer/tests/launcher_ignore_cases.py b/clean/installer/tests/launcher_ignore_cases.py index b5602faa..a7234e10 100644 --- a/clean/installer/tests/launcher_ignore_cases.py +++ b/clean/installer/tests/launcher_ignore_cases.py @@ -71,15 +71,18 @@ def said(): src = read(src_txt).decode("utf-8", "replace") if os.path.isfile(src_txt) else "" t.check("convert-ignore: a second game's install converts again from its own (allowed) file; the listed conversion is replaced, the new SHA-256 recorded", rc == 0 and ("source\t" + dll_b).lower() in src.lower() and ("sha256\t" + hashlib.sha256(read(dll_b)).hexdigest()) in src, (rc, said(), src)) - let_go = _hold(lst) - try: - t0 = time.time() - rc = t.run("repair", exe_b, *flags) - took = time.time() - t0 - finally: - let_go() - t.check("convert-ignore: the well-known list held open: the repair exits 10 after the retries, the file and the reason named", - rc == 10 and lst.lower() in said().lower() and "another program holds it open" in said() and took >= 0.75, (rc, round(took, 2), said())) + if base.native: + base.skip("lock", "convert-ignore: the well-known list held open: the repair exits 10 after the retries, the file and the reason named") + else: + let_go = _hold(lst) + try: + t0 = time.time() + rc = t.run("repair", exe_b, *flags) + took = time.time() - t0 + finally: + let_go() + t.check("convert-ignore: the well-known list held open: the repair exits 10 after the retries, the file and the reason named", + rc == 10 and lst.lower() in said().lower() and "another program holds it open" in said() and took >= 0.75, (rc, round(took, 2), said())) list_bytes = read(lst) rc_a = t.run("uninstall", exe_a) rc_b = t.run("uninstall", exe_b) diff --git a/clean/installer/tests/launcher_proton_cases.py b/clean/installer/tests/launcher_proton_cases.py new file mode 100644 index 00000000..4c33aaf6 --- /dev/null +++ b/clean/installer/tests/launcher_proton_cases.py @@ -0,0 +1,115 @@ +# SPDX-License-Identifier: MIT +"""Engine.ini for Ray Reconstruction on the native Linux launcher (S3): the game runs under Proton, so the line goes into the game's +own Wine prefix. A Steam game: /steamapps/compatdata//pfx/drive_c/users/steamuser/{Documents,AppData/Local}, refused in +plain words (nothing written) until Steam has made it. A game that is not from Steam: the Windows folder the player points at once +(the windows-folder verb), remembered. Only a fake Steam tree under the suite's work folder is read or written; the suite's +Documents / LOCALAPPDATA test roots are taken away for these runs, as the real launcher has none. For run_launcher_tests.py +(--native-linux), after test_rr_config_fix. Written for this project.""" +import os +import shutil + +import mockpe +import run_installer_tests as suite +from run_installer_tests import read, write + + +def _game(t, root, exe_name, appid=None): + """A game folder with the layout an install needs and, with an appid, its appmanifest in the library above it.""" + shutil.rmtree(root, ignore_errors=True) + b = os.path.join(root, "bin", "x64") + write(os.path.join(b, exe_name), "mock game exe " * 200 + exe_name) + write(os.path.join(b, "amd_fidelityfx_dx12.dll"), suite.AMD_V1) + write(os.path.join(b, "nvngx_dlss.dll"), t.model.file) + write(os.path.join(b, "steam_api64.dll"), "untouched game file") + write(os.path.join(root, "Engine", "Plugins", "Runtime", "Vendor", "RR", "Binaries", "ThirdParty", "Win64", "nvngx_dlssd.dll"), + mockpe.make_dll({"ProductName": "RR library (test stand-in)"}, (310, 5, 0, 0), extra=b"synthetic, never loaded", dll_name="nvngx_dlssd.dll")) + if appid: + steamapps = os.path.dirname(os.path.dirname(root)) + write(os.path.join(steamapps, "appmanifest_%s.acf" % appid), + '"AppState"\n{\n\t"appid"\t\t"%s"\n\t"installdir"\t\t"%s"\n}\n' % (appid, os.path.basename(root))) + return b, os.path.join(b, exe_name) + + +def _tree(p): + out = [] + for d, _, fs in os.walk(p): + out += [os.path.relpath(os.path.join(d, f), p) for f in fs] + [os.path.relpath(d, p) + "/" for _ in [0]] + return sorted(out) + + +def run(t, opti): + print("\n[proton] native Linux: Engine.ini goes into the game's Proton prefix (or the Windows folder the player chose)") + base = os.path.join(t.work, "proton-steam") + shutil.rmtree(base, ignore_errors=True) + home_docs = os.path.join(t.env["HOME"], "Documents") + saved_env = t.env + t.env = {k: v for k, v in saved_env.items() if k not in ("WRONGGPU_TEST_DOCUMENTS", "LOCALAPPDATA")} + try: + steamapps = os.path.join(base, "steamapps") + root = os.path.join(steamapps, "common", "Borderlands 4") + b, exe = _game(t, root, "Borderlands4.exe", appid="4242") + compat = os.path.join(steamapps, "compatdata") + rc = t.run("install", exe, "--opti=" + opti, "--noscan", "--force", "--experimental") + t.check("proton: install into a Steam game folder", rc == 0, (rc, t.j.get("message"))) + # 1. Steam has made no Proton folder: refused in plain words, nothing written anywhere + rc = t.run("set", exe, "rr_config_fix=on") + warn = " ".join(t.j.get("warnings", [])) + t.check("proton: no Proton folder yet: the choice is refused with a plain sentence (start the game once so Steam makes it), nothing written", + rc == 0 and "Steam has not made this game's Proton folder yet" in warn and "Start the game once" in warn and not os.path.exists(compat) and + not os.path.exists(home_docs), (rc, t.j.get("warnings"), t.j.get("notes"))) + rc = t.run("get", exe, "rr_config_fix") + info = t.j.get("rr_config", {}) + t.check("proton: get says no file is known, and why", rc == 0 and info.get("file") == "" and "Proton folder" in info.get("file_why", "") and info.get("fixed") is False, info) + # 2. the prefix exists (the game was started once): the line goes into its Documents, the file read-only as before + user = os.path.join(compat, "4242", "pfx", "drive_c", "users", "steamuser") + cfg = os.path.join(user, "Documents", "My Games", "Borderlands 4", "Saved", "Config", "Windows") + write(os.path.join(cfg, "GameUserSettings.ini"), b"[ScalabilityGroups]\r\n") + ini = os.path.join(cfg, "Engine.ini") + rc = t.run("set", exe, "rr_config_fix=on") + data = read(ini) if os.path.isfile(ini) else b"" + t.check("proton: with the prefix there: Engine.ini is in the prefix's Documents with the line, read-only, nothing in this account's Documents", + rc == 0 and data.startswith(b"[SystemSettings]\r\n") and len(data) == 45 and not os.access(ini, os.W_OK) and not os.path.exists(home_docs), + (rc, data, t.j.get("warnings"))) + rc = t.run("get", exe, "rr_config_fix") + info = t.j.get("rr_config", {}) + t.check("proton: get names the file in the prefix, fixed", rc == 0 and info.get("fixed") is True and info.get("file", "").replace("\\", "/").lower().endswith( + "compatdata/4242/pfx/drive_c/users/steamuser/documents/my games/borderlands 4/saved/config/windows/engine.ini"), info) + # 3. uninstall takes the same line out of the same file + rc = t.run("uninstall", exe) + t.check("proton: uninstall takes the line out of the same file (the file it made is gone, the game's settings folder stays)", + rc == 0 and not os.path.exists(ini) and os.listdir(cfg) == ["GameUserSettings.ini"], (rc, os.listdir(cfg))) + # 4. a game that is not from Steam: it asks once for the Windows folder and remembers it + plain_root = os.path.join(t.work, "proton-epic", "Borderlands 4") + pb, pexe = _game(t, plain_root, "Borderlands4.exe") + rc = t.run("install", pexe, "--opti=" + opti, "--noscan", "--force", "--experimental") + rc = t.run("set", pexe, "rr_config_fix=on") + warn = " ".join(t.j.get("warnings", [])) + t.check("proton: a game that is not from Steam: refused in plain words, asking for its Windows folder once", + rc == 0 and "not a Steam game" in warn and "once" in warn and not os.path.exists(home_docs), (rc, t.j.get("warnings"))) + wine_user = os.path.join(t.work, "proton-wine-user") + shutil.rmtree(wine_user, ignore_errors=True) + rc = t.run("windows-folder", pexe, wine_user) + t.check("proton: windows-folder with a folder that is not there is refused, nothing remembered", rc != 0 and "is not a folder" in t.j.get("error", ""), (rc, t.j)) + os.makedirs(wine_user) + rc = t.run("windows-folder", pexe, wine_user) + t.check("proton: windows-folder with neither Documents nor AppData in it is refused", rc != 0 and "no Documents or AppData" in t.j.get("error", ""), (rc, t.j)) + os.makedirs(os.path.join(wine_user, "Documents")) + rc = t.run("windows-folder", pexe, wine_user) + t.check("proton: windows-folder remembers the Windows folder", rc == 0 and t.j.get("windows_folder", {}).get("folder", "").replace("\\", "/").endswith("proton-wine-user"), (rc, t.j)) + rc = t.run("windows-folder", pexe) + t.check("proton: it is remembered by the next run of the launcher", rc == 0 and t.j.get("windows_folder", {}).get("folder", "").replace("\\", "/").endswith("proton-wine-user"), t.j) + pcfg = os.path.join(wine_user, "Documents", "My Games", "Borderlands 4", "Saved", "Config", "Windows") + rc = t.run("set", pexe, "rr_config_fix=on") + t.check("proton: the remembered folder before the game made its settings folder: nothing written, added after the first start", + rc == 0 and any("will be added after you start the game once" in n for n in t.j.get("notes", [])) and not os.path.exists(os.path.join(pcfg, "Engine.ini")), + (rc, t.j.get("notes"), t.j.get("warnings"))) + write(os.path.join(pcfg, "GameUserSettings.ini"), b"[ScalabilityGroups]\r\n") + rc = t.run("set", pexe, "rr_config_fix=on") + t.check("proton: the settings folder is there: Engine.ini written in the remembered folder", rc == 0 and os.path.isfile(os.path.join(pcfg, "Engine.ini")) and + len(read(os.path.join(pcfg, "Engine.ini"))) == 45, (rc, t.j.get("warnings"))) + rc = t.run("uninstall", pexe) + t.check("proton: uninstall takes it out of the remembered folder too", rc == 0 and not os.path.exists(os.path.join(pcfg, "Engine.ini")), rc) + rc = t.run("windows-folder", pexe, "--clear") + t.check("proton: --clear forgets it", rc == 0 and t.j.get("windows_folder", {}).get("folder") == "", t.j) + finally: + t.env = saved_env diff --git a/clean/installer/tests/launcher_rr_prepare_cases.py b/clean/installer/tests/launcher_rr_prepare_cases.py index 412d96df..9f4e117c 100644 --- a/clean/installer/tests/launcher_rr_prepare_cases.py +++ b/clean/installer/tests/launcher_rr_prepare_cases.py @@ -25,6 +25,39 @@ def _helper_gone(run_dir): return not os.path.isdir(run_dir) or not os.listdir(run_dir) +def _native(t, exe, b, prep_dir): + """The native Linux launcher: a game runs under Proton, whose shader caches are the game's own, so RR's kernels are prepared by + the game at its first start (rrprep.h): every verb answers "in-game" in plain words, no helper is copied or started (even with + a driver version and the test's permission), nothing fails and nothing is written to the game's folder. The Windows launcher's + cases (a helper, a driver, no card) do not apply.""" + game_before = sorted(os.listdir(b)) + rc = t.run("rr-prepare", exe, "--check") + rp = t.j.get("rr_prepare", {}) + t.check("native rr-prepare --check: prepared by the game at its first start (state in-game, the Proton words, not an error)", + rc == 0 and rp.get("ready") is False and rp.get("state") == "in-game" and "Proton" in rp.get("not_ready_why", "") and + "no AMD graphics card" not in rp.get("not_ready_why", ""), t.j) + rc = t.run("rr-recheck", exe) + rq = t.j.get("rr_recheck", {}) + t.check("native rr-recheck: not stale, state in-game, nothing run", rc == 0 and rq.get("stale") is False and rq.get("state_before") == "in-game" and + rq.get("result") == -1, t.j) + envlog = os.path.join(t.work, "rr-helper-env.log") + if os.path.exists(envlog): + os.remove(envlog) + t.env.update(WRONGGPU_TEST_RR_DRIVER="99.0.0.1", WRONGGPU_TEST_HELPER_ENV_LOG=envlog, WRONGGPU_TEST_ALLOW_RR_HELPER="1") + try: + rc = t.run("rr-prepare", exe, "--passes=1") + finally: + for k in ("WRONGGPU_TEST_RR_DRIVER", "WRONGGPU_TEST_HELPER_ENV_LOG", "WRONGGPU_TEST_ALLOW_RR_HELPER"): + t.env.pop(k, None) + rp = t.j.get("rr_prepare", {}) + t.check("native rr-prepare with a driver and the test's permission: result 4 (the game prepares them), exit 0, said why, no helper " + "started, nothing prepared, nothing new in the game's folder", + rc == 0 and rp.get("result") == 4 and "Proton" in rp.get("why", "") and not os.path.exists(envlog) and + _helper_gone(os.path.join(prep_dir, "run")) and not os.path.isfile(os.path.join(prep_dir, "prepared.txt")) and + sorted(os.listdir(b)) == game_before, (rc, rp, os.listdir(b))) + print(" skipped: the Windows launcher's rr-prepare cases (a helper under a driver, no card): natively the game prepares RR's kernels") + + def run(t, exe, b, gpu_opt_in=False): """rr-prepare --check, rr-recheck, rr-prepare's no-card path, the helper with the stand-in runtime and, with the opt-in, a real runtime and an RDNA 4 card, the prepared state across a driver or runtime change. exe: the RR game's exe, b: its folder.""" @@ -32,6 +65,8 @@ def run(t, exe, b, gpu_opt_in=False): # under the game's program name, which loads the installed wronggpu_runtime.dll (the real runtime of this payload, RR # built in) and creates RR's pipelines on the GPU; the driver keeps them per program name, so the game finds them ready prep_dir = os.path.join(t.data, "rr-prepare") # the launcher data folder (the suite runs with --data) + if t.native: + return _native(t, exe, b, prep_dir) rc = t.run("rr-prepare", exe, "--check") t.check("rr-prepare --check before: not prepared yet", rc == 0 and t.j.get("rr_prepare", {}).get("ready") is False and "not prepared yet" in t.j.get("rr_prepare", {}).get("not_ready_why", ""), t.j) diff --git a/clean/installer/tests/launcher_state_cases.py b/clean/installer/tests/launcher_state_cases.py index fa18be24..de2d93af 100644 --- a/clean/installer/tests/launcher_state_cases.py +++ b/clean/installer/tests/launcher_state_cases.py @@ -10,6 +10,7 @@ The install's seed files (wronggpu-asi.ini, WrongGPU\\wronggpu.ini) are created only where nothing is: a file that appears at either boundary (after the check, after the record: WRONGGPU_TEST_CREATE_AT) is the player's. Written for this project.""" import os +import re import shutil import subprocess import sys @@ -33,6 +34,22 @@ """ +# Linux (--native-linux): the game under Wine, as the Linux launcher sees one: a process named like a Windows program (Wine +# sets the command line so) with the file mapped. "load-unreadable": the same, made not dumpable, so its maps cannot be read. +HOLD_LINUX = r""" +import ctypes, mmap, sys +path, how = sys.argv[1], sys.argv[2] +f = open(path, "rb") +m = mmap.mmap(f.fileno(), 0, prot=mmap.PROT_READ) +f.close() # only the mapping holds it, as a loaded DLL +if how == "load-unreadable": + ctypes.CDLL(None).prctl(4, 0, 0, 0, 0) # PR_SET_DUMPABLE 0 +print("held", flush=True) +sys.stdin.read() +""" +WINE_GAME = "C:\\Games\\State Game\\GameHelper.exe" # (not the game's Game.exe: the guard decides, not the name check) + + STAMP = b"; wronggpu-written " @@ -192,9 +209,14 @@ def same(): shutil.rmtree(root, ignore_errors=True) -def hold(path, how): - p = subprocess.Popen([sys.executable, "-c", HOLD, path, how], stdin=subprocess.PIPE, stdout=subprocess.PIPE, - creationflags=0x08000000) +def hold(path, how, native=False): + if native: + import native_linux + p = subprocess.Popen([WINE_GAME, "-c", HOLD_LINUX, native_linux.host(path), how], executable=sys.executable, + stdin=subprocess.PIPE, stdout=subprocess.PIPE) + else: + p = subprocess.Popen([sys.executable, "-c", HOLD, path, how], stdin=subprocess.PIPE, stdout=subprocess.PIPE, + creationflags=0x08000000) return p, p.stdout.readline().decode().strip() @@ -214,6 +236,10 @@ def asi_seed_cases(t, opti, m): if rc != 0 or not os.path.isfile(asi): t.check("install (hosted route)", rc == 0, (rc, t.j.get("message"))) print(" skipped: the plugin's wronggpu-asi.ini (a build without Preset K writes none)") + if rc == 0: + rc = t.run("uninstall", exe) + t.check("(no Preset K) the uninstall after that install works", rc == 0, (rc, t.j.get("message"), t.j.get("error"))) + shutil.rmtree(root, ignore_errors=True) # (as below: the later sections see only their own games) return seeded = read(asi) t.check("Preset K build: the plugin's wronggpu-asi.ini is one of the install's recorded files, with its hash", @@ -325,18 +351,26 @@ def run(t, opti, m): t.j.get("game")) # 4. uninstall, repair and update refused while another program has a WrongGPU file open or the game has it loaded - for rel, how in (("plugins\\WrongGPU-RR.asi", "open"), ("wronggpu_runtime.dll", "load")): - p, state = hold(os.path.join(b, rel), how) + holds = (("plugins\\WrongGPU-RR.asi", "open"), ("wronggpu_runtime.dll", "load")) + if t.native: # Linux sees a game under Wine that has the file loaded (win32_posix.h CreateFileW), not another program's open + t.skip("lock", "[state] uninstall, repair and update refused while another program has a WrongGPU file open") + holds = (("wronggpu_runtime.dll", "load"), ("wronggpu_runtime.dll", "load-unreadable")) + said = {"open": "open in another program", "load": "loaded", "load-unreadable": "loaded by a game whose files cannot be read"} + for rel, how in holds: + p, state = hold(os.path.join(b, rel), how, t.native) try: if state != "held": print(" skipped: %s %s (%s)" % (how, rel, state)) continue snap = snapshot(root) + words = "could not tell whether the game is using its files" if how == "load-unreadable" else "in use by the game or another program" + # cannot be ruled out for any binary (that process could have any loaded): the first one the guard tries is named + named = (lambda msg: re.search(r"\(\S+\.(dll|asi)\)", msg)) if how == "load-unreadable" else (lambda msg: os.path.basename(rel) in msg) for op in ("uninstall", "repair", "update"): rc = t.run(op, exe, *(() if op == "uninstall" else inst)) msg = t.j.get("message", "") + t.j.get("error", "") - t.check("%s while %s is %s: refused (exit 2), nothing changed, the file named" % (op, rel, "open in another program" if how == "open" else "loaded"), - rc == 2 and "in use by the game or another program" in msg and os.path.basename(rel) in msg and snapshot(root) == snap, + t.check("%s while %s is %s: refused (exit 2), nothing changed, the file named, the words say to close the game" % (op, rel, said[how]), + rc == 2 and words in msg and "lose the game" in msg and named(msg) and snapshot(root) == snap, (rc, msg, diff(snap, snapshot(root)))) finally: release(p) diff --git a/clean/installer/tests/native_linux.py b/clean/installer/tests/native_linux.py new file mode 100644 index 00000000..33e69f62 --- /dev/null +++ b/clean/installer/tests/native_linux.py @@ -0,0 +1,310 @@ +# SPDX-License-Identifier: MIT +"""What run_launcher_tests.py --native-linux needs to run the launcher suite against the Linux WrongGPU binary. + +Written for this project; Python standard library only. The suite's checks stay the same; this module gives them the +Linux equivalents of what the Windows runs get from Windows: the safe environment (every folder the program writes to +sits under the work folder, SDL opens no window, the registry is a file of the run's own), HKCU as that file, and the +list of checks that only mean something on Windows.""" +import ntpath +import os +import re +import shutil +import stat +import sys + +# Windows-only features of the launcher suite: each is skipped on Linux with its reason printed (see skip()) +WINDOWS_ONLY = { + "shortcut": "the launcher's self-install is a Windows feature: a Start menu .lnk shortcut, an Apps & features entry, Mark of the Web", + "elevation": "the elevated worker is Windows UAC; Linux has no elevation prompt", + "restorer": "the per-game restorer (uninstall.exe) is a Windows program that Linux does not build or embed", + "gpu": "this check needs the Windows graphics driver and an RDNA 4 card, which a native Linux run has neither of", + "http": "the Linux launcher has no HTTP client yet (WinHTTP is answered as not available; HTTPS needs a TLS library)", + "lock": "a file another process holds open with no sharing (Windows share mode 0) is not emulated: the POSIX layer's sharing rules are per process", + "junction": "NTFS junctions do not exist on Linux (the section tests the data folder reached through one)", + "baseline": "the 0.5.1 baseline installer is a Windows program", +} + +# Checks that fail on main's own Windows launcher as well (reproduced under Wine), so not the Linux port's: skipped while they +# fail, with the issue that reports them (check name prefix -> reason) +KNOWN_ON_MAIN = { + "uninstall: exit 0, the RR game's folder as before except the two RR settings files": + "fails on main too: a repair after an in-game edit records WrongGPU\\wronggpu.ini as the player's (issue #219)", +} + + +def environment(work, base): + """The environment of every run of the app under test: its XDG folders, HOME, temp folder and registry file under `work`, + SDL on its offscreen driver and no runtime or display variable (an earlier run opened real windows on a desktop that way). + LOCALAPPDATA is a folder of its own, spelled as the program spells it (Z:\\...), and not XDG_DATA_HOME: the program takes XDG_DATA_HOME + for the PC's real local application data folder and refuses to write a game's Engine.ini there (rrconfig.cpp), as on Windows. + `work` may be either spelling.""" + env = {k: v for k, v in base.items() if k not in ("DISPLAY", "WAYLAND_DISPLAY", "XDG_RUNTIME_DIR", "WRONGGPU_UI_SCRIPT", "APPIMAGE", "APPDIR")} + work = host(work) + run = os.path.join(work, "native") + for d in ("home", "config", "cache", "state", "tmp", "xdg-data"): + os.makedirs(os.path.join(run, d), exist_ok=True) + data = os.path.join(work, "localappdata") + os.makedirs(data, exist_ok=True) + env.update(HOME=os.path.join(run, "home"), XDG_DATA_HOME=os.path.join(run, "xdg-data"), XDG_CONFIG_HOME=os.path.join(run, "config"), + XDG_CACHE_HOME=os.path.join(run, "cache"), XDG_STATE_HOME=os.path.join(run, "state"), TMPDIR=os.path.join(run, "tmp"), + WRONGGPU_REGISTRY_FILE=os.path.join(run, "registry.ini"), LOCALAPPDATA=win_path(data), + ProgramData=win_path(os.path.join(work, "programdata")), SDL_VIDEO_DRIVER="offscreen", SDL_AUDIODRIVER="dummy") + return env + + +def host(p): + """The Linux path of a path the suite spells as Windows does (Z:\\home\\...\\name, or a relative one with '\\'). A name that is + not there is looked for in another case, as NTFS (and so every Windows run of the suite) finds it.""" + if not isinstance(p, str): + return p + if len(p) >= 2 and p[:2].upper() == "Z:" and (len(p) == 2 or p[2] in "\\/"): + p = p[2:] or "/" + p = p.replace("\\", "/") + if os.path.lexists(p) or not p: + return p + cur, parts = ("/" if p.startswith("/") else "."), [x for x in p.split("/") if x] + for i, name in enumerate(parts): + nxt = os.path.join(cur, name) + if not os.path.lexists(nxt): + try: + same = [n for n in os.listdir(cur) if n.lower() == name.lower()] + except OSError: + return p + if not same: + return p + nxt = os.path.join(cur, same[0]) + cur = nxt + return cur + + +def win_path(p): + """How a Linux path is spelled in the Windows way the suite (and the program) use: Z:\\ plus the path, as in Wine.""" + p = os.path.abspath(p) + return "Z:" + p.replace("/", "\\") + + +def _hostfn(fn): + return lambda *a, **k: fn(*[host(x) for x in a], **{n: host(v) for n, v in k.items()}) + + +class _WinPath: + """os.path as the suite sees it on Windows: Windows spellings (ntpath), existence checks on the Linux files behind them.""" + sep, altsep, pathsep = "\\", "/", ";" + def __init__(self): + for n in ("join", "split", "splitext", "dirname", "basename", "normpath", "isabs", "normcase", "splitdrive", "commonpath"): + setattr(self, n, getattr(ntpath, n)) + for n in ("exists", "lexists", "isfile", "isdir", "islink", "getsize", "getmtime", "realpath", "samefile", "ismount"): + setattr(self, n, _hostfn(getattr(os.path, n))) + + def abspath(self, p): + p = os.fspath(p) + if p[:2].upper() == "Z:": + return ntpath.normpath(p) + return ntpath.normpath(win_path(p) if p.startswith("/") else ntpath.join(win_path(os.getcwd()), p)) + + def relpath(self, p, start=None): + return ntpath.relpath(self.abspath(p), self.abspath(start or os.getcwd())) + + +class _Stat: + """os.stat's result plus the Windows st_file_attributes, from the mode the way the program maps it (read-only: no write bit).""" + + def __init__(self, st): + self._st = st + self.st_file_attributes = (0x10 if stat.S_ISDIR(st.st_mode) else 0x20) | (0x1 if not st.st_mode & 0o222 else 0) + + def __getattr__(self, name): + return getattr(self._st, name) + + +class WinOs: + """Stands in for `os` in the suite's modules: paths are Windows spellings (Z:\\... roots, backslashes), as the program under test + prints them, so every check compares what it compares on Windows; the files behind them are the Linux ones.""" + + def __init__(self): + self.path, self.sep, self.altsep = _WinPath(), "\\", "/" + for n in ("listdir", "makedirs", "mkdir", "remove", "unlink", "rmdir", "rename", "replace", "chmod", "utime", + "symlink", "link", "readlink", "access", "truncate", "chdir"): # stat and lstat: below + setattr(self, n, _hostfn(getattr(os, n))) + + def __getattr__(self, name): + return getattr(os, name) + + def stat(self, p, **k): + return _Stat(os.stat(host(p), **k)) + + def lstat(self, p, **k): + return _Stat(os.lstat(host(p), **k)) + + def getcwd(self): + return win_path(os.getcwd()) + + def walk(self, top, topdown=True, onerror=None, followlinks=False): + for d, dirs, files in os.walk(host(top), topdown, onerror, followlinks): + yield win_path(d), dirs, files + + +class WinShutil: + def __getattr__(self, name): + fn = getattr(shutil, name) + return _hostfn(fn) if callable(fn) else fn + + +def windows_paths(*modules): + """Give each module Windows-style os, shutil and open (see WinOs).""" + for m in modules: + for n, v in (("os", WinOs()), ("shutil", WinShutil())): + if hasattr(m, n): + setattr(m, n, v) + m.open = lambda f, *a, **k: open(host(f), *a, **k) + + +def _unescape(s): + return re.sub(r"%([0-9A-Fa-f]{2})", lambda m: chr(int(m.group(1), 16)), s) + + +def _escape(s): + return "".join("%%%02X" % ord(c) if ord(c) < 0x20 or c in "%=]" else c for c in s) + + +class Registry: + """HKCU as the program keeps it (src/platform/posix/win32_posix_registry.cpp): a text file, one [key path] section per key, + `name=s:value` lines. The tests read the Apps & features entries through it and set up and remove stale ones.""" + + def __init__(self, file): + self.file = file + + def load(self): + keys, cur = {}, None + try: + lines = open(self.file, encoding="utf-8").read().splitlines() + except OSError: + return keys + for line in lines: + if len(line) >= 2 and line[0] == "[" and line[-1] == "]": + cur = keys.setdefault(_unescape(line[1:-1]), {}) + elif cur is not None and "=" in line: + name, body = line.split("=", 1) + if body[:2] in ("s:", "e:"): + cur[_unescape(name)] = _unescape(body[2:]) + elif body[:2] in ("d:", "q:"): + cur[_unescape(name)] = body[2:] + return keys + + def save(self, keys): + tmp = self.file + ".test" + with open(tmp, "w", encoding="utf-8") as f: + for path, values in keys.items(): + f.write("[%s]\n" % _escape(path)) + for n, v in values.items(): + f.write("%s=s:%s\n" % (_escape(n), _escape(v))) + os.replace(tmp, self.file) + + @staticmethod + def _path(path): + return re.sub(r"^HKCU\\", "", path, flags=re.I) + + def subkeys(self, root): + """{subkey name: {value name: text}} directly under root (an HKCU\\... path), like the Windows suite's reg query parse.""" + base = self._path(root).lower() + out = {} + for path, values in self.load().items(): + head, _, name = path.rpartition("\\") + if head.lower() == base: + out[name] = dict(values) + return out + + def add(self, path, name, value): + keys = self.load() + keys.setdefault(self._path(path), {})[name] = value + self.save(keys) + + def delete(self, path): + base = self._path(path).lower() + keys = {p: v for p, v in self.load().items() if p.lower() != base and not p.lower().startswith(base + "\\")} + self.save(keys) + + +def setup(main_module, suite, tests_dir): + """Called by run_launcher_tests.main for --native-linux: the checks see Windows spellings of paths (WinOs), as the program prints + them; what the suite built at import time with the host's separator is made again.""" + import launcher_build_facts + import launcher_edition_cases + import launcher_ignore_cases + import launcher_isolation + import launcher_appimage_cases + import launcher_proton_cases + import launcher_rr_prepare_cases + import launcher_state_cases + windows_paths(main_module, suite, launcher_ignore_cases, launcher_edition_cases, launcher_build_facts, launcher_isolation, + launcher_appimage_cases, launcher_proton_cases, launcher_rr_prepare_cases, launcher_state_cases) + sys.path.insert(0, host(tests_dir + "/../tools")) # the tests add it with a Windows separator, which sys.path cannot use + main_module.RR_SETTINGS = main_module.os.path.join("WrongGPU", "wronggpu.ini") + main_module.T = native_class(main_module.T, suite) + + +def native_class(T, suite): + """The suite's T for the Linux binary: the safe environment, the registry file for HKCU, host paths for the program and + the Windows-only checks skipped with their reasons (kept here so the suite file stays below the 256 KB source limit).""" + class NativeT(T): + native = True + + def __init__(self, exe, work, model, hip): + super().__init__(exe, work, model, hip) + self.skipped = [] + guard = self.env + self.env = environment(work, os.environ) + for k in ("WRONGGPU_TEST_LIBRARIES", "WRONGGPU_TEST_ACCESS_LOG", "WRONGGPU_TEST_RUN_ID"): # the store-access guard's (#243) + self.env[k] = guard[k] + if hip: + self.env["WRONGGPU_HIP_RUNTIME"] = hip + for k in [k for k in self.env if k.upper().startswith("WG_") or k.upper() in ("HIP_PATH", "ROCM_PATH", "LLVM_PATH", "HIP_DEVICE_LIB_PATH")]: + self.env.pop(k) + self.uninstall = suite.uninstall_root(self.env["LOCALAPPDATA"]) + self.registry = Registry(self.env["WRONGGPU_REGISTRY_FILE"]) + + def check(self, name, cond, detail=""): + """A check that fails on main's own launcher too (issue #219) is skipped with that reason while it fails; once it + passes it counts again, and the run says to drop it from KNOWN_ON_MAIN.""" + known = next((k for k in KNOWN_ON_MAIN if name.startswith(k)), None) + if known and not cond: + self.skipped.append(name) + return skip(name, KNOWN_ON_MAIN[known]) + if known: + print(" NOTE passes now, remove it from native_linux.KNOWN_ON_MAIN:", known) + return super().check(name, cond, detail) + + def skip(self, feature, what): + """A check that only means something on Windows: not run, and the log says which and why.""" + self.skipped.append(what) + skip(what, WINDOWS_ONLY[feature]) + + def run(self, *args, exe=None, cwd=None, **k): + return super().run(*args, exe=host(exe or self.exe), cwd=host(cwd), **k) + + def raw(self, cmd, timeout=600): + return super().raw([host(cmd[0])] + list(cmd[1:]), timeout) + + def reg_keys(self, root=None): + return self.registry.subkeys(root or self.uninstall) + + def reg_add(self, path, name, value): + return self.registry.add(path, name, value) + + def reg_delete(self, path): + return self.registry.delete(path) + + return NativeT + + +def skip(name, reason): + print(" SKIP ", name, "-", reason) + + +def check_steps_words(t, steps, ini): + """A native Linux player's Engine.ini steps are in Linux terms (file manager, text editor, file permissions), never File Explorer, + Notepad or Properties, and the folder is a /path.""" + t.check("native Linux: the steps say file manager, text editor and permissions, never File Explorer, Notepad or Properties, and the folder is a /path", + "file manager" in steps and "text editor" in steps and "Permissions" in steps and "set it to read-only" in steps and + not any(w in steps for w in ("File Explorer", "Notepad", "Properties", "right-click")) and "Z:\\" not in steps and + os.path.dirname(host(ini)) + "\n" in steps, steps) diff --git a/clean/installer/tests/run_launcher_tests.py b/clean/installer/tests/run_launcher_tests.py index 973e5edb..7ba75650 100644 --- a/clean/installer/tests/run_launcher_tests.py +++ b/clean/installer/tests/run_launcher_tests.py @@ -25,6 +25,7 @@ HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) import mockpe # noqa: E402 (synthetic PE files with a version resource) +import native_linux # noqa: E402 (--native-linux) import launcher_build_facts as facts # noqa: E402 (what the launcher under test was built with) import run_installer_tests as suite # noqa: E402 (mock content, snapshots, the synthetic model case) from run_installer_tests import read, sha, snapshot, diff, write, kept_runtime, unrecorded_wronggpu_files # noqa: E402 @@ -35,6 +36,8 @@ class T: + native, skipped = False, () + def __init__(self, exe, work, model, hip): self.exe, self.work, self.model = exe, work, model self.passed, self.failures = 0, [] @@ -78,6 +81,12 @@ def check(self, name, cond, detail=""): self.failures.append(name + (": " + str(detail)[:1500] if detail else "")) print(" FAIL ", name, str(detail)[:1500]) + def reg_add(self, path, name, value): + subprocess.run(["reg", "add", path, "/v", name, "/t", "REG_SZ", "/d", value, "/f"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + + def reg_delete(self, path): + subprocess.run(["reg", "delete", path, "/f"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + def run(self, *args, exe=None, data=True, timeout=600, cwd=None): """WrongGPU.exe --data --log --out; the JSON result in self.j; returns the exit code. cwd: its current directory.""" if os.path.exists(self.out): @@ -365,7 +374,8 @@ def test_install_settings_uninstall(t, opti): t.check("owned-files.json: valid JSON, every recorded file with its owner", owned.get("format") == "wronggpu-owned-files/1" and any(f["path"] == "wronggpu_runtime.dll" and f["owner"] == "wg" for f in owned.get("files", [])), owned) un = os.path.join(b, "wronggpu-setup", "uninstall.exe") - t.check("uninstall.exe is the restorer (the build's WrongGPU-Restore.exe), not the launcher", facts.restorer_ok(un, t.exe), + t.check("uninstall.exe is the restorer (the build's WrongGPU-Restore.exe), not the launcher" + (" (Linux: none written)" if t.native else ""), + not os.path.exists(un) if t.native else facts.restorer_ok(un, t.exe), (os.path.getsize(un) if os.path.isfile(un) else None, os.path.getsize(t.exe))) t.check("profile.ini written", os.path.isfile(os.path.join(b, "wronggpu-setup", "profile.ini"))) t.check("the game is on the managed list", b.lower() in managed_list(t), managed_list(t)) @@ -454,7 +464,7 @@ def test_install_settings_uninstall(t, opti): t.check("an older record: an older version, not \"another build\" (other_build false, no such words)", t.j.get("game", {}).get("other_build") is False and "another build" not in t.j.get("game", {}).get("status_text", ""), t.j.get("game", {})) # a build without Preset K: an older install set up to start on Preset K (the plugin's choice) moves to Model M, said in the log - no_k = "Preset K isn't in this version".encode("utf-16-le") in read(t.exe) + no_k = any("Preset K isn't in this version".encode(e) in read(t.exe) for e in ("utf-16-le", "utf-32-le")) # (wchar_t: 4 bytes on Linux) if no_k: write(os.path.join(b, "wronggpu-asi.ini"), "; WrongGPU OptiScaler plugin\r\nselection=wronggpu-k\r\n") rc = t.run("update", exe, "--opti=" + opti, "--noscan", "--force") @@ -544,10 +554,10 @@ def test_install_settings_uninstall(t, opti): and not t.entries_for(b)) # again, uninstalled by the restorer in the game folder rc = t.run("install", exe, "--opti=" + opti, "--noscan", "--force") - rc2 = t.raw([os.path.join(b, "wronggpu-setup", "uninstall.exe"), "/S", "/LOG=" + t.log]) + rc2 = t.run("uninstall", exe) if t.native else t.raw([os.path.join(b, "wronggpu-setup", "uninstall.exe"), "/S", "/LOG=" + t.log]) wait_gone(os.path.join(b, "wronggpu-setup")) after = snapshot(root) - t.check("the restorer (uninstall.exe /S): exit 0, as before except the unrecorded wronggpu-* files (left in place)", rc == 0 and rc2 == 0 and after == left, (rc, rc2, diff(left, after))) + t.check(("the launcher's uninstall (Linux)" if t.native else "the restorer (uninstall.exe /S)") + ": exit 0, as before except the unrecorded wronggpu-* files (left in place)", rc == 0 and rc2 == 0 and after == left, (rc, rc2, diff(left, after))) shutil.rmtree(root, ignore_errors=True) @@ -682,10 +692,9 @@ def test_experimental_and_shared_model(t, opti): t.check("first uninstalled: the model stays (the other game is on the managed list)", rc == 0 and os.path.isfile(model) and snapshot(r1) == s1, diff(s1, snapshot(r1))) # a stale Apps & features entry (its game folder deleted by hand, so no record) is no game that still uses the data stale = t.uninstall + "\\WrongGPU-00000000" - subprocess.run(["reg", "add", stale, "/v", "InstallLocation", "/t", "REG_SZ", "/d", os.path.join(t.work, "games", "Deleted Game", "bin", "x64"), "/f"], - stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + t.reg_add(stale, "InstallLocation", os.path.join(t.work, "games", "Deleted Game", "bin", "x64")) rc = t.run("uninstall", e2) - subprocess.run(["reg", "delete", stale, "/f"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + t.reg_delete(stale) t.check("last uninstalled (a stale entry of a deleted game left): byte for byte; the shared model data goes", rc == 0 and snapshot(r2) == s2 and not os.path.isfile(model), (rc, diff(s2, snapshot(r2)))) shutil.rmtree(r1, ignore_errors=True) @@ -765,7 +774,7 @@ def test_rc6_hunt(t, opti): rc == 0 and rc2 == 0 and rc3 != 0 and not os.path.isfile(rp) and not os.path.isfile(os.path.join(b, "wronggpu_runtime.dll")), (rc, rc2, rc3, t.j.get("message"))) t.check("L4: profile.ini, previous\\ (Roll back) and all the failed run did not make stay (the earlier uninstaller too)", os.path.isfile(os.path.join(state, "profile.ini")) and os.path.isfile(os.path.join(state, "previous", "previous.txt")) and - os.path.isfile(os.path.join(state, "uninstall.exe")), sorted(os.listdir(state)) if os.path.isdir(state) else None) + (t.native or os.path.isfile(os.path.join(state, "uninstall.exe"))), sorted(os.listdir(state)) if os.path.isdir(state) else None) # (Linux: no restorer) rc = t.run("install", exe, "--opti=" + opti, "--noscan", "--force") rc2 = t.run("get", exe) t.check("L4: the next install starts with the kept settings", rc == 0 and rc2 == 0 and @@ -1013,7 +1022,7 @@ def test_launcher_uninstall(t, opti): t.check("...while it is on the list, the last reachable game's own uninstall keeps the shared model data (the game byte for byte)", had and rc2 == 0 and snapshot(root) == before and os.path.isdir(model_dir), (had, rc2, diff(before, snapshot(root)), t.logtail())) for k in own: - subprocess.run(["reg", "delete", t.uninstall + "\\" + k, "/f"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) + t.reg_delete(t.uninstall + "\\" + k) wait_removed(t) shutil.rmtree(shared, ignore_errors=True) else: @@ -1840,6 +1849,12 @@ def changed_keys(before, after): return sorted(k for k in set(before) | set(after) if before.get(k) != after.get(k)) +def test_rr_config_proton(t, opti): + if t.native: # S3: Engine.ini in the game's Proton prefix (launcher_proton_cases.py) + __import__("launcher_proton_cases").run(t, opti) + __import__("launcher_appimage_cases").run(t, opti) # S5 + + def test_rr_config_fix(t, opti): """Brief 16 (owner 2026-11-04): Borderlands 4 and Hogwarts Legacy need one line in the player's own Engine.ini for Ray Reconstruction, and Borderlands 4 deletes that file unless it is read-only. An install asks (the result's @@ -1904,8 +1919,10 @@ def rr_page(tag, env=None, extra=()): "WrongGPU can add the line" in text and "on the game's page at any time" in text and "uninstalling WrongGPU takes it out" in text, (rc, t.j.get("message"), q)) t.check("the question's steps have the line, the game's folder and read-only; the fix and myself commands name the setting", - line.decode() in q.get("steps", "") and os.path.dirname(bl4_ini) in q.get("steps", "") and "Read-only" in q.get("steps", "") and + line.decode() in q.get("steps", "") and (os.path.dirname(native_linux.host(bl4_ini)) if t.native else os.path.dirname(bl4_ini)) in q.get("steps", "") and + ("read-only" if t.native else "Read-only") in q.get("steps", "") and q.get("fix", "").endswith("rr_config_fix=on") and q.get("myself", "").endswith("rr_config_fix=off"), q) + if t.native: native_linux.check_steps_words(t, q.get("steps", ""), bl4_ini) # review fix: Linux terms bad = [p for p in check_wording.PHRASES if p in (text + q.get("steps", "")).lower()] # the line's own words (its key's parts) appear nowhere but in the line itself words = [w for w in line.split(b"=")[0].decode().split(".") if len(w) >= 3] @@ -2307,10 +2324,11 @@ def set_no_docs(*kv): any(k.startswith("Open the settings folder of") for k in p0) and "Check Engine.ini again" in p0 and any(k.startswith("Step 4: Paste this line under [SystemSettings]") and line.decode() in k for k in p0) and # every step spelled out, read-only last (UI review r2 #5) - any(k.startswith("Step 2: Create or open Engine.ini there with Notepad") for k in p0) and + any(k.startswith("Step 2: Create or open Engine.ini there with " + ("a text editor" if t.native else "Notepad")) for k in p0) and any(k.startswith("Step 3: If the file has no [SystemSettings] line, add it at the end") for k in p0) and any(k.startswith("Step 5: Save the file") for k in p0) and - any(k.startswith("Step 6: Right-click Engine.ini, choose Properties, tick Read-only and click OK") for k in p0) and + any(k.startswith("Step 6: Make Engine.ini read-only: in your file manager" if t.native + else "Step 6: Right-click Engine.ini, choose Properties, tick Read-only and click OK") for k in p0) and any(k.startswith("The game's settings folder isn't there yet") for k in p0) and not os.listdir(docs), (rc2, [k for k in p0 if "ngine" in k or "Step" in k])) rg = [gp.get("rrconfig") for gp in d.get("games", []) if gp.get("rrconfig")] # the game never started (no settings folder): the check says so (-1), Open folder makes nothing and says to start the @@ -2375,7 +2393,7 @@ def set_no_docs(*kv): "UTF-16" in rcf.get("check_toast", ""), (rx, rcf, [k for k in pg if "ngine" in k])) rx, pg, rcf = on_states["unknown"] t.check("window, WrongGPU's choice: a folder it can't check says so (not Added by WrongGPU), with Check again (state -1)", - rx == 0 and row(pg, "Couldn't check. Start the game once, then check again") and "Check Engine.ini again" in pg and + rx == 0 and row(pg, "Can't find the game's Windows folder" if t.native else "Couldn't check. Start the game once, then check again") and "Check Engine.ini again" in pg and not row(pg, "Added by WrongGPU") and rcf.get("state") == -1, (rx, rcf, [k for k in pg if "ngine" in k or "check" in k])) # Myself, the game's folder there: the file check in each state (UI review r2 #6, #7): no line (0), the line in a file that # isn't read-only (2), read-only (1); the folder made as the game makes it (GameUserSettings.ini in it) @@ -2402,7 +2420,8 @@ def set_no_docs(*kv): t.check("window, Myself, an Engine.ini saved as UTF-16: WrongGPU's check couldn't read it, check it by hand in Notepad (the line, read-only); " "no Save as / Encoding step; Check again; its toast says the same (r4 #6)", rx == 0 and rcf.get("state") == 3 and cr and "WrongGPU's check couldn't read it: it is saved as UTF-16" in cr[0] and - "open Engine.ini in Notepad and look for the line under [SystemSettings]" in cr[0] and "Read-only is ticked" in cr[0] and + ("open Engine.ini in a text editor and look for the line under [SystemSettings]" if t.native else "open Engine.ini in Notepad and look for the line under [SystemSettings]") in cr[0] and + ("that the file is read-only" if t.native else "Read-only is ticked") in cr[0] and "Save as" not in cr[0] and "Encoding" not in cr[0] and "Check Engine.ini again" in pg and "WrongGPU's check couldn't read Engine.ini" in rcf.get("check_toast", "") and "by hand" in rcf.get("check_toast", ""), (rx, rcf, cr)) os.remove(bl4_ini) # the player's own file gone again, as before these checks (the game's settings folder stays) @@ -2484,7 +2503,7 @@ def set_no_docs(*kv): q = t.j.get("rr_config_question", {}) t.check("Hogwarts Legacy install: the question (the game named, its menu can't turn it on; no read-only step)", rc == 0 and q.get("text", "").startswith("Hogwarts Legacy needs one more setting for Ray Reconstruction") and - "needs one line in Engine.ini, because the game's own menu can't turn it on" in q.get("text", "") and "read-only" not in q.get("text", "") and "Read-only" not in q.get("steps", ""), + "needs one line in Engine.ini, because the game's own menu can't turn it on" in q.get("text", "") and "read-only" not in q.get("text", "") and "Read-only" not in q.get("steps", "") and "read-only" not in q.get("steps", ""), (rc, t.j.get("message"), q)) hog_ini = os.path.join(hog, "WindowsNoEditor", "Engine.ini") # before the game's first start: no guessed Windows folder (the game uses WindowsNoEditor): nothing made, waits (r2b #1) @@ -2880,7 +2899,10 @@ def test_ui_dump(t, opti): t.check("game page: the FPS overlay saved on: step 3 says it is on, no button; without OptiScaler's overlay key: no claim, no button (UI review r2 #9)", "(it is on)" in fp.get("step3_saved", "") and fp.get("button_saved") is False and "FPS overlay shows" not in fp.get("step3_nokey", "x") and "no FPS overlay setting" in fp.get("step3_nokey", "") and fp.get("button_nokey") is False, fp) - t.check("settings page: update check off by default", any(c["text"] == "Check for new releases" and c.get("checked") is False for c in d.get("settings", {}).get("controls", []))) + ctl = d.get("settings", {}).get("controls", []) + t.check("settings page: update check off by default" + (" (Linux: no switch, the row says it is off)" if t.native else ""), + any(c["text"].startswith("Check for new releases") and "Off on Linux" in c["text"] for c in ctl) if t.native else + any(c["text"] == "Check for new releases" and c.get("checked") is False for c in ctl)) bf = d.get("busy_focus", {}) t.check("settings page: a button that goes busy keeps the focus, shown off with its busy name; Return does nothing, Tab goes on from it", bf.get("id", 0) > 0 and bf.get("kept") is True and bf.get("enabled") is False and "Converting" in bf.get("name", "") and @@ -3042,7 +3064,8 @@ def invoke_without_log(exe, verb): # (launcher_build_facts.junction_call: also def main(): ap = argparse.ArgumentParser() - ap.add_argument("--launcher", required=True) + ap.add_argument("--launcher") + ap.add_argument("--native-linux", metavar="WrongGPU", help="the Linux binary instead of --launcher (see native_linux.py)") ap.add_argument("--work", required=True) ap.add_argument("--baseline", help="the 0.5.1 installer (WRONGGPU_TESTING build, same test map) for the adoption cases") ap.add_argument("--hip", help="mock amdhip64_7.dll (WRONGGPU_HIP_RUNTIME)") @@ -3059,10 +3082,14 @@ def main(): ap.add_argument("--synth-f", default=os.environ.get("WGC_SYNTH_BINS", ""), help="folder with the spec team's synthetic preset-F file synth-common-v0.bin (the test build's F map is synth-r0)") a = ap.parse_args() + if not (a.launcher or a.native_linux): + ap.error("--launcher or --native-linux is required") + if a.native_linux: + native_linux.setup(sys.modules[__name__], suite, HERE) global RUN_OLD_BASELINE, NO_DIRECT, RR_PREPARE_GPU RUN_OLD_BASELINE, RR_PREPARE_GPU = a.run_old_baseline, a.rr_prepare_gpu NO_DIRECT = os.path.abspath(a.no_direct_launcher) if a.no_direct_launcher else None - for what, p in (("--launcher", a.launcher), ("--no-direct-launcher", NO_DIRECT)): # before anything runs + for what, p in (("--launcher", a.launcher), ("--native-linux", a.native_linux), ("--no-direct-launcher", NO_DIRECT)): # before anything runs if p: facts.require_test_hooks(p, what) if a.hip is not None: # the mock HIP runtime: an existing plain file (an empty --hip= too is refused), named first @@ -3077,11 +3104,11 @@ def main(): work = facts.new_run_folder(os.path.abspath(a.work)) iso.self_test(work) # (#243) first: no launcher call with a broken guard model = suite.cases.f_mini_case(present=0) # the synthetic source of the test map the launcher was built with - t = T(os.path.abspath(a.launcher), work, model, a.hip) + t = T(os.path.abspath(a.native_linux or a.launcher), work, model, a.hip) # registry entries of an earlier run (test root only) for k, v in t.reg_keys().items(): if (k.startswith("WrongGPU-") and v.get("InstallLocation", "").lower().startswith(work.lower())) or (k == "WrongGPU" and work.lower() in v.get("InstallLocation", "").lower()): - subprocess.run(["reg", "delete", t.uninstall + "\\" + k, "/f"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + t.reg_delete(t.uninstall + "\\" + k) if a.startup_only: # the start of a run and the HIP check only rc = t.run("hipcheck") print("startup-only: run folder %s; hipcheck exit %d" % (work, rc)) @@ -3094,7 +3121,7 @@ def main(): for name in a.only: fn = globals()["test_" + name] fn(*(t, opti, a.baseline if "baseline" in fn.__code__.co_varnames[:3] else a.synth_f)[:fn.__code__.co_argcount]) - print("\n%d checks passed, %d failed (%.0f s)" % (t.passed, len(t.failures), time.time() - t0)) + print("\n%d checks passed, %d failed, %d skipped (%.0f s)" % (t.passed, len(t.failures), len(t.skipped), time.time() - t0)) for f in t.failures: print(" FAILED:", f) return 1 if t.failures else 0 @@ -3108,17 +3135,18 @@ def main(): test_direct_rr(t, opti, a.synth_f) test_sm2_settings(t, opti) test_rr_config_fix(t, opti) - test_edition_download(t, opti) + test_rr_config_proton(t, opti) + t.skip("http", "[edition] the whole section") if t.native else test_edition_download(t, opti) test_players_optiscaler(t, opti) test_experimental_and_shared_model(t, opti) test_orphan(t, opti) test_rc6_hunt(t, opti) __import__("launcher_ignore_cases").run(T, t, opti, game) test_adopt_and_self_install(t, opti, a.baseline) - test_launcher_uninstall(t, opti) - test_data_root_junctions(t) + t.skip("shortcut", "[launcher] self-install / self-uninstall") if t.native else test_launcher_uninstall(t, opti) + t.skip("junction", "[junctions] the whole section") if t.native else test_data_root_junctions(t) test_ui_dump(t, opti) - print("\n%d checks passed, %d failed (%.0f s)" % (t.passed, len(t.failures), time.time() - t0)) + print("\n%d checks passed, %d failed, %d skipped (%.0f s)" % (t.passed, len(t.failures), len(t.skipped), time.time() - t0)) for f in t.failures: print(" FAILED:", f) return 1 if t.failures else 0 diff --git a/clean/installer/tests/run_linux_ui_codexfix_tests.py b/clean/installer/tests/run_linux_ui_codexfix_tests.py new file mode 100644 index 00000000..a123e85b --- /dev/null +++ b/clean/installer/tests/run_linux_ui_codexfix_tests.py @@ -0,0 +1,279 @@ +# SPDX-License-Identifier: MIT +"""The native Linux launcher's Codex review fixes (launcher step 4): each finding as a real UI state, with the complete string. + + run_linux_ui_codexfix_tests.py --exe [--work ] + +Same setup as run_linux_ui_tests.py (a home of its own, a fake Steam library, SDL's offscreen driver, a made-up process folder for +the AppImage proof). Needs a WRONGGPU_TESTING build of the Linux launcher. Written for this project.""" +import argparse +import json +import os +import shutil +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +import run_linux_ui_tests as base # noqa: E402 + +check = base.check +IMAGE = "WrongGPU-test-x86_64.AppImage" +CAVEAT = "System should follow the desktop's light or dark setting, but WrongGPU can't read it on Linux yet, so it uses light for now." +HEAD = b"\x7fELF\x02\x01\x01\x00AI\x02\x00\x00\x00\x00\x00fake" +LIST = b"wronggpu-ignore-files 1\r\n" + + +def shell(p): + return "'" + str(p).replace("'", "'\\''") + "'" + + +def dump(exe, work, home, tag, *, image=None, proven=True, appdir=None, env_extra=None, args=(), setup=None, dirname="Apps"): + """One ui-dump. image: the AppImage file to make (named IMAGE in `dirname`); proven: the made-up process folder backs it.""" + env, run_dir = base.environment(work, home, tag) + path = None + appdir = Path(appdir) if appdir else Path(exe).resolve().parent + if image: + path = run_dir / dirname / IMAGE + path.parent.mkdir(parents=True) + path.write_bytes(HEAD) + env.update(APPIMAGE=str(path), APPDIR=str(appdir)) + if proven: + base.fake_proc(run_dir / "proc", appdir, path) + env["WRONGGPU_TEST_PROC_ROOT"] = str(run_dir / "proc") + env.update(env_extra or {}) + if setup: + setup(run_dir) + out = work / tag + r = base.run(exe, ["ui-dump", f"--dump={out / 'dump.json'}", *args], env, 300) + check(r.returncode == 0, f"{tag}: ui-dump exits 0 (got {r.returncode}: {r.stderr[-300:]})") + return json.loads((out / "dump.json").read_text()), path, run_dir + + +def names(d, page="settings"): + return [c["text"] for c in d[page]["controls"]] + + +def launcher_row(d): + return next((n for n in names(d) if n.startswith("Launcher install")), "") + + +def sentence(image, data, keep=False, games=False): + return (f"The file: {image}. Uninstall deletes that file and WrongGPU's data folder ({data}) after you confirm. " + + ("Your ignore-files.txt list is kept. " if keep else "") + "Nothing else is deleted." + + (" Uninstall WrongGPU from your games first." if games else "")) + + +def question(image, data, keep): + return ("Uninstall WrongGPU?\n\nThis deletes two things and cannot be undone:\n\n• The program file:\n " + str(image) + + "\n• WrongGPU's data folder (the converted Model M and Ray Reconstruction data, the games' list, settings and logs):\n " + str(data) + + "\n\n" + ("Your ignore-files.txt list is kept. " if keep else "") + "Nothing else is deleted. Your games and their files are not touched.") + + +def put_list(folder, link=False): + folder.mkdir(parents=True, exist_ok=True) + if link: + (folder / "my-list.txt").write_bytes(LIST) + (folder / "ignore-files.txt").symlink_to("my-list.txt") + else: + (folder / "ignore-files.txt").write_bytes(LIST) + + +def test_uninstall_words(exe, work, home): + print("findings 2, 3, 4: the warning, the folder and the list in the Settings row and the dialog") + games = [] + + def with_game(run_dir): # a game WrongGPU is installed in, on the managed list, in no library the launcher scans + game = run_dir / "elsewhere" / "Ghost Game" + (game / "wronggpu-setup").mkdir(parents=True) + (game / "wronggpu-setup" / "install.record").write_bytes(b"x") + put_list(run_dir / "data" / "WrongGPU") + (run_dir / "data" / "WrongGPU" / "managed-games.txt").write_text("Z:" + str(game) + "\n") + games.append(game) + + d, image, run = dump(exe, work, home, "w-plain", image=True, setup=lambda r: put_list(r / "data" / "WrongGPU")) + data = run / "data" / "WrongGPU" + want = f"Launcher install: Runs from an AppImage. {sentence(image, data, keep=True)} Settings and logs: {data}" + check(launcher_row(d) == want, f"the row, whole ({launcher_row(d)})") + check(d["appimage_question"] == question(image, data, True), f"the live dialog's text, whole ({d['appimage_question']})") + d, image, run = dump(exe, work, home, "w-none", image=True) + check(launcher_row(d) == f"Launcher install: Runs from an AppImage. {sentence(image, run / 'data' / 'WrongGPU')} Settings and logs: {run / 'data' / 'WrongGPU'}", + f"no list: the row has no list sentence and no games sentence ({launcher_row(d)})") + check(d["appimage_question"] == question(image, run / "data" / "WrongGPU", False), "no list: the dialog's text has no list sentence") + # 2: a game outside the scanned libraries still blocks the uninstall, so the row says so (the Library does not list it) + d, image, run = dump(exe, work, home, "w-game", image=True, setup=with_game) + data = run / "data" / "WrongGPU" + check(len(d["rows"]) == 2 and not any("Ghost" in r for r in d["rows"]), f"the Library does not list that game ({d['rows']})") + check(launcher_row(d) == f"Launcher install: Runs from an AppImage. {sentence(image, data, keep=True, games=True)} Settings and logs: {data}", + f"the row warns about the game the uninstall would refuse for ({launcher_row(d)[-160:]})") + # 3: --data names another folder for the launcher's own files; the uninstall still deletes the shared folder + other = work / "other-data" + shutil.rmtree(other, ignore_errors=True) + d, image, run = dump(exe, work, home, "w-override", image=True, args=(f"--data={other}",), setup=lambda r: put_list(other)) + data = run / "data" / "WrongGPU" + check(launcher_row(d) == f"Launcher install: Runs from an AppImage. {sentence(image, data)} Settings and logs: {other}", + f"--data: the row names the folder the uninstall deletes, no list kept there, and the logs label its own ({launcher_row(d)[-200:]})") + check(d["appimage_question"] == question(image, data, False), "--data: the dialog names that folder too") + shutil.rmtree(other, ignore_errors=True) + d, image, run = dump(exe, work, home, "w-override2", image=True, args=(f"--data={other}",), setup=lambda r: put_list(r / "data" / "WrongGPU")) + data = run / "data" / "WrongGPU" + check(launcher_row(d) == f"Launcher install: Runs from an AppImage. {sentence(image, data, keep=True)} Settings and logs: {other}", + "--data: the list in the shared folder is the one that is kept") + shutil.rmtree(other, ignore_errors=True) + # 4: a list that is a link: its target goes with the folder, so nothing is promised + d, image, run = dump(exe, work, home, "w-link", image=True, setup=lambda r: put_list(r / "data" / "WrongGPU", link=True)) + data = run / "data" / "WrongGPU" + check(launcher_row(d) == f"Launcher install: Runs from an AppImage. {sentence(image, data)} Settings and logs: {data}", "a linked list: the row promises nothing") + check(d["appimage_question"] == question(image, data, False), "a linked list: the dialog promises nothing") + + +def test_label(exe, work, home): + print("finding 5: the side label and the row when the AppImage cannot be proven") + appdir = Path(exe).resolve().parent + d, _, _ = dump(exe, work, home, "l-extract", image=True, proven=False, env_extra={"APPIMAGE_EXTRACT_AND_RUN": "1"}) + check("WrongGPU 0.6.5, AppImage" in names(d), f"extract-and-run: the side label says AppImage ({[n for n in names(d) if 'WrongGPU 0' in n]})") + row = launcher_row(d) + check(row.startswith("Launcher install: Runs from an AppImage. Uninstall WrongGPU is not available here. "), f"extract-and-run: the row says so, with no uninstall ({row[:140]})") + check(not any(n.startswith("Uninstall WrongGPU") for n in names(d)), "extract-and-run: no Uninstall button") + d, _, _ = dump(exe, work, home, "l-inherited", image=True, proven=False, appdir=work) # another AppImage's variables, this program is not inside it + check("WrongGPU 0.6.5, AppImage" not in names(d) and "WrongGPU 0.6.5, not installed" in names(d), f"inherited variables: the label stays ({[n for n in names(d) if 'WrongGPU 0' in n]})") + check(launcher_row(d).startswith("Launcher install: Not an AppImage. Uninstall WrongGPU is not available here. "), "inherited variables: the row says it is no AppImage") + d, _, _ = dump(exe, work, home, "l-proven", image=True) + check("WrongGPU 0.6.5, AppImage" in names(d) and "Uninstall WrongGPU…" in names(d), "proven: the label and the button") + del appdir + + +def test_command(exe, work, home): + print("finding 1: the Windows-folder command, and Copy as a click") + me = Path(exe).resolve() + + def command(tag, **kw): + d, image, run = dump(exe, work, home, tag, **kw) + c = d["windows_folder_copy"] + game = c["exe"].replace("Z:", "", 1).replace("\\", "/") + return c, image, game + + c, image, game = command("c-proven", image=True) + check(c["clipboard"] == f"{shell(image)} windows-folder {shell(game)} ''", f"proven AppImage: its file heads the command ({c['clipboard']})") + check(c["toast"] == "The command is on the clipboard. Paste it into a terminal, and put your folder where it says , inside the quotes.", "Copy's toast, whole") + c, image, game = command("c-quote", image=True, dirname="it's here") + check(c["clipboard"] == f"{shell(image)} windows-folder {shell(game)} ''" and "it'\\''s here" in c["clipboard"], f"an apostrophe in the AppImage's folder is quoted ({c['clipboard'][:120]})") + deep = "/".join(["d" * 200] * 3) # a path of more than 600 characters + c, image, game = command("c-long", image=True, dirname=deep) + check(len(str(image)) > 600 and c["clipboard"] == f"{shell(image)} windows-folder {shell(game)} ''", f"a long AppImage path is not cut ({len(str(image))} characters)") + c, _, game = command("c-self") + check(c["clipboard"] == f"{shell(me)} windows-folder {shell(game)} ''", f"no AppImage: this program's own file heads it ({c['clipboard'][:120]})") + c, _, game = command("c-other", env_extra={"APPIMAGE": str(work / "Other.AppImage")}) + check(c["clipboard"] == f"{shell(me)} windows-folder {shell(game)} ''", f"another AppImage's variable, no proof: this program's own file ({c['clipboard'][:120]})") + c, image, game = command("c-unproven", image=True, proven=False) + check(c["clipboard"].startswith(shell(me) + " windows-folder "), "an AppImage file the system does not tie to this process is not used") + + +def placed(exe, where): + """This program's file at another place (a hard link, so /proc/self/exe names that place) with what it finds next to it.""" + src = Path(exe).resolve() + where.mkdir(parents=True, exist_ok=True) + dst = where / src.name + try: + os.link(src, dst) + except OSError: + shutil.copy2(src, dst) + for item in src.parent.iterdir(): + if item.is_dir() and item.name in ("assets", "fonts", "payload", "data"): + (where / item.name).symlink_to(item) + return dst + + +def test_own_file(exe, work, home): + print("blind review: this program's own file from a long path and from a folder with a backslash in its name") + for tag, where in (("o-long", work / "o-long" / "/".join(["e" * 200] * 3)), ("o-backslash", work / "o-backslash" / "literal\\name")): + me = placed(exe, where) + d, _, _ = dump(me, work, home, tag + "-run") + c = d["windows_folder_copy"] + game = c["exe"].replace("Z:", "", 1).replace("\\", "/") + check(c["clipboard"] == f"{shell(me)} windows-folder {shell(game)} ''", f"{tag}: the command names this program's real file ({c['clipboard'][:160]})") + d, _, _ = dump(me, work, home, tag + "-label", image=True, proven=False, appdir=where, env_extra={"APPIMAGE_EXTRACT_AND_RUN": "1"}) + check("WrongGPU 0.6.5, AppImage" in names(d), f"{tag}: inside its AppImage folder the side label says AppImage ({[n for n in names(d) if 'WrongGPU 0' in n]})") + + +LIVE_SCRIPT = """wait 1500 +clickname Settings +wait 800 +clickname Launcher +wait 800 +clickname Uninstall WrongGPU +wait 2500 +dump {o}/dialog.json +clickname Cancel +wait 500 +close +""" + + +def test_live_question(exe, work, home): + print("blind review: the question the live window really shows after a click on Uninstall") + env, run_dir = base.environment(work, home, "q-live") + image = run_dir / "Apps" / IMAGE + image.parent.mkdir(parents=True) + image.write_bytes(HEAD) + appdir = Path(exe).resolve().parent + env.update(APPIMAGE=str(image), APPDIR=str(appdir)) + base.fake_proc(run_dir / "proc", appdir, image) + env["WRONGGPU_TEST_PROC_ROOT"] = str(run_dir / "proc") + data = run_dir / "data" / "WrongGPU" + put_list(data) + (data / "launcher.ini").write_bytes(b"first_run_done=1\r\n") + out = work / "q-live-out" + out.mkdir() + script = work / "q-live-script.txt" + script.write_text(LIVE_SCRIPT.format(o=out)) + env["WRONGGPU_UI_SCRIPT"] = str(script) + r = base.run(exe, [], env, 180) + check(r.returncode == 0, f"the live window exits 0 ({r.returncode}: {r.stderr[-300:]})") + f = out / "dialog.json" + d = json.loads(f.read_text()) if f.is_file() else {} + shown = d.get("dialog_title", "") + "\n\n" + d.get("dialog_body", "") + check(d.get("dialog_open") is True and shown == question(image, data, True), f"the open dialog's words, whole ({shown[:200]!r})") + check(image.is_file() and (data / "ignore-files.txt").is_file(), "Cancel deleted nothing") + + +def test_misc(exe, work, home): + print("findings 7: the pictures and the Settings rows named in the review") + d, _, run = dump(exe, work, home, "m-shots", image=True, args=(f"--shots={work / 'm-shots'}",)) + out = work / "m-shots" + details = (out / "first-run-details.png.texts").read_text(encoding="utf-8").replace("\u00a0", " ").splitlines() # (the sheet keeps its words together with no-break spaces) + plain = (out / "first-run.png.texts").read_text(encoding="utf-8").replace("\u00a0", " ").splitlines() + line = "Graphics card detected: AMD Radeon RX 9070 XT" + check(any(t.endswith("\t" + line) for t in details) and not any(t.endswith("\t" + line) for t in plain) and any(t.endswith("\tHide details") for t in details), + "the Show details picture is really open (a detail row, 'Hide details')") + d, _, _ = dump(exe, work, home, "m-hip", image=True, setup=lambda r: ((r / "libhip.so").write_bytes(b"x"), (r / "data" / "WrongGPU").mkdir(parents=True, exist_ok=True), + (r / "data" / "WrongGPU" / "hip-runtime.txt").write_text(str(r / "libhip.so") + "\n"))) + hip = " ".join(n for n in names(d) if n.startswith("HIP runtime")) + check(hip.startswith("HIP runtime: Found") and "Not used in games: Model M runs through Proton's Direct3D 12." in hip, f"the HIP row, found ({hip})") + (work / "m-light").mkdir() + d, _, _ = dump(exe, work, home, "m-light", image=True, setup=lambda r: ((r / "data" / "WrongGPU").mkdir(parents=True, exist_ok=True), + (r / "data" / "WrongGPU" / "launcher.ini").write_bytes(b"first_run_done=1\r\nappearance=light\r\n"))) + app = " ".join(n for n in names(d) if n.startswith("Appearance:") and n not in ("Appearance: System", "Appearance: Light", "Appearance: Dark")) + check(app == "Appearance: The launcher stays light. " + CAVEAT, f"Light chosen: the caveat follows ({app})") + + +def main(): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--exe", required=True) + ap.add_argument("--work", default=None) + a = ap.parse_args() + work = Path(a.work or "linux-ui-codexfix-tests").resolve() + if work.exists(): + shutil.rmtree(work) + work.mkdir(parents=True) + home = base.make_home(work) + for fn in (test_uninstall_words, test_label, test_command, test_own_file, test_live_question, test_misc): + fn(Path(a.exe), work, home) + if base.failures: + print(f"{len(base.failures)} check(s) failed") + return 1 + print("linux ui codex-fix tests: all checks passed") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/clean/installer/tests/run_linux_ui_tests.py b/clean/installer/tests/run_linux_ui_tests.py new file mode 100644 index 00000000..35ad83cd --- /dev/null +++ b/clean/installer/tests/run_linux_ui_tests.py @@ -0,0 +1,427 @@ +# SPDX-License-Identifier: MIT +"""The launcher's window on Linux (the one WrongGPU binary: src/app on the SDL window layer of src/platform/posix). + + run_linux_ui_tests.py --exe [--work ] + +Every run uses a home of its own under --work, its own XDG folders and registry file, a fake Steam library with two stub games +(PE stand-ins from mockpe.py: nothing of the player's is read or written), and SDL's offscreen video driver (no window opens). + ui-dump the pages as JSON: the structure the launcher tests expect (first run, Library, Settings, a page per game; each widget's + class, text, id, place, state), the games read from the fake library, the PNGs of the pages + ui-render the fixture screenshots (Library, Settings, a game's page) at two scales: PNG files of the sizes asked for + jpeg ui-render of a game whose Steam cache holds a synthetic JPEG hero: its colours are on the page (needs --jpeg-tool) + proton the installed fixture game's page shows the Steam launch option Proton needs for OptiScaler (dxgi=n,b) with Copy + live the real window under the offscreen driver with scripted SDL events (win32_window_sdl.cpp, WRONGGPU_UI_SCRIPT): a click + on Settings, a scroll, a click on the Library's search field and typing in it, Ctrl+A and Backspace; the page each step + left is read back as JSON; the window then closes on WM_CLOSE and the program exits 0 +Needs a WRONGGPU_TESTING build of the Linux launcher. +""" +import argparse +import json +import re +import os +import shutil +import struct +import subprocess +import zlib +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +import mockpe # noqa: E402 + +ROLES = {"Button", "Switch", "Segment", "Item", "Select", "Link", "MenuItem", "Edit", "ScrollBar", "Dialog", "Menu", "Progress", "Text"} +failures = [] + + +def check(cond, what): + if not cond: + failures.append(what) + print(" FAIL:", what) + return cond + + +def png_size(path): + b = Path(path).read_bytes() + if b[:8] != b"\x89PNG\r\n\x1a\n" or b[12:16] != b"IHDR": + return None + return struct.unpack(">II", b[16:24]) + + +def png_pixels(path): + """(width, height, rows of RGB tuples-as-bytes) of an 8-bit RGB or RGBA PNG, from the standard library alone.""" + b = Path(path).read_bytes() + pos, idat, w = 8, b"", 0 + while pos < len(b): + n, kind = struct.unpack(">I4s", b[pos:pos + 8]) + data = b[pos + 8:pos + 8 + n] + if kind == b"IHDR": + w, h, depth, ctype = struct.unpack(">IIBB", data[:10]) + assert depth == 8 and ctype in (2, 6), "8-bit RGB or RGBA only" + elif kind == b"IDAT": + idat += data + pos += 12 + n + bpp = 4 if ctype == 6 else 3 + raw, stride, rows, prev = zlib.decompress(idat), w * bpp, [], bytearray(w * bpp) + for y in range(h): + f, line = raw[y * (stride + 1)], bytearray(raw[y * (stride + 1) + 1:(y + 1) * (stride + 1)]) + for i in range(stride): + a = line[i - bpp] if i >= bpp else 0 + up = prev[i] + c = prev[i - bpp] if i >= bpp else 0 + if f == 1: line[i] = (line[i] + a) & 255 + elif f == 2: line[i] = (line[i] + up) & 255 + elif f == 3: line[i] = (line[i] + (a + up) // 2) & 255 + elif f == 4: + pa, pb, pc = abs(up - c), abs(a - c), abs(a + up - 2 * c) + line[i] = (line[i] + (a if pa <= pb and pa <= pc else up if pb <= pc else c)) & 255 + rows.append(bytes(line)); prev = line + return w, h, rows, bpp + + +def count_near(png, want, tol): + """How many pixels of the PNG are within `tol` of the RGB colour `want`.""" + _, _, rows, bpp = png + n = 0 + for r in rows: + for x in range(0, len(r), bpp): + if abs(r[x] - want[0]) <= tol and abs(r[x + 1] - want[1]) <= tol and abs(r[x + 2] - want[2]) <= tol: + n += 1 + return n + + +def make_home(work): + """A home with a Steam library of two games, each with a DLSS stand-in (what makes the launcher list a game).""" + home = work / "home" + steam = home / ".local" / "share" / "Steam" / "steamapps" + games = [("1091500", "Cyberpunk 2077", "bin/x64/Cyberpunk2077.exe"), ("1086940", "Baldur's Gate 3", "bin/bg3.exe")] + (steam / "common").mkdir(parents=True) + apps = "".join(f'\t\t\t"{i}"\t\t"1"\n' for i, _, _ in games) + (steam / "libraryfolders.vdf").write_text('"libraryfolders"\n{\n\t"0"\n\t{\n\t\t"path"\t\t"%s"\n\t\t"apps"\n\t\t{\n%s\t\t}\n\t}\n}\n' % (home / ".local/share/Steam", apps)) + for appid, name, exe in games: + (steam / f"appmanifest_{appid}.acf").write_text('"AppState"\n{\n\t"appid"\t\t"%s"\n\t"name"\t\t"%s"\n\t"installdir"\t\t"%s"\n\t"StateFlags"\t\t"4"\n}\n' % (appid, name, name)) + d = steam / "common" / name / Path(exe).parent + d.mkdir(parents=True) + (steam / "common" / name / exe).write_bytes(mockpe.make_dll({"ProductName": "stub game"}, (1, 0, 0, 0), dll_name="game.exe")) + (d / "nvngx_dlss.dll").write_bytes(mockpe.make_dll({"ProductName": "DLSS stand-in"}, (310, 5, 0, 0), dll_name="nvngx_dlss.dll")) + return home + + +def environment(work, home, name): + # (APPIMAGE and APPDIR: the program under test is never taken for the AppImage of whatever started this run) + env = {k: v for k, v in os.environ.items() if k not in ("DISPLAY", "WAYLAND_DISPLAY", "XDG_RUNTIME_DIR", "WRONGGPU_UI_SCRIPT", "APPIMAGE", "APPDIR")} + run = work / name + for d in ("data", "config", "cache", "state", "tmp"): + (run / d).mkdir(parents=True, exist_ok=True) + env.update(HOME=str(home), XDG_DATA_HOME=str(run / "data"), XDG_CONFIG_HOME=str(run / "config"), XDG_CACHE_HOME=str(run / "cache"), + XDG_STATE_HOME=str(run / "state"), TMPDIR=str(run / "tmp"), WRONGGPU_REGISTRY_FILE=str(run / "registry.ini"), + SDL_VIDEO_DRIVER="offscreen", SDL_AUDIODRIVER="dummy") + drm = fake_drm(run / "drm", "0x1002", "0x7550") # an RX 9070 XT: the pages do not depend on this PC's GPU + env["WRONGGPU_TEST_DRM_ROOT"] = "Z:" + str(drm) + return env, run + + +def fake_drm(root, vendor, device): + """A made-up /sys/class/drm with one card (no card when vendor is None), for WRONGGPU_TEST_DRM_ROOT.""" + shutil.rmtree(root, ignore_errors=True) + root.mkdir(parents=True) + if vendor: + d = root / "card0" / "device" + d.mkdir(parents=True) + (d / "vendor").write_text(vendor + "\n") + (d / "device").write_text(device + "\n") + return root + + +def run(exe, args, env, timeout): + r = subprocess.run([str(exe), *args], env=env, capture_output=True, text=True, timeout=timeout) + return r + + +def test_dump(exe, work, home): + print("ui-dump") + env, run_dir = environment(work, home, "dump") + out = work / "dump" + r = run(exe, ["ui-dump", f"--dump={out / 'dump.json'}", f"--shots={out / 'shots'}"], env, 300) + check(r.returncode == 0, f"ui-dump exits 0 (got {r.returncode}: {r.stderr[-300:]})") + d = json.loads((out / "dump.json").read_text()) + for k in ("version", "first_run", "list", "settings", "games", "banner", "keyboard"): + check(k in d, f"dump has '{k}'") + for page in ("first_run", "list", "settings"): + ctl = d[page]["controls"] + check(len(ctl) > 5, f"{page} has widgets") + for c in ctl: + if not check(c["class"] in ROLES and isinstance(c["id"], int) and all(isinstance(c[k], int) for k in "xywh") + and isinstance(c["enabled"], bool), f"widget shape in {page}: {c}"): + break + names = {c["text"] for c in d["list"]["controls"]} + classes = {(c["class"], c["text"]) for c in d["list"]["controls"]} + for want in ("Settings", "Minimize", "Maximize", "Close"): + check(want in names, f"Library has '{want}'") + check(("Edit", "Search games") in classes, "Library has the Search games field") + check(any(n.startswith("Library") for n in names), "Library has its tab") + games = d["games"] if isinstance(d["games"], list) else list(d["games"].values()) + check(len(games) == 2, f"two games listed from the fake library (got {len(games)})") + for i in range(2): + p = out / "shots" / f"game-{i}.png" + check(p.is_file() and png_size(p) == (1180, 760), f"game page {i} PNG is 1180x760") + for p in ("first-run", "list", "settings"): + check(png_size(out / "shots" / f"{p}.png") == (1180, 760), f"{p}.png is 1180x760") + return d + + +def test_first_run_words(exe, work, home): + """S4: the first run's checks on Linux speak Linux: the distribution instead of a Windows line, Direct3D 12 through Proton, no + HIP runtime line, and no Install for this user choice (an AppImage runs where it is). Three made-up cards.""" + print("first-run words (Linux)") + for tag, ids, gpu_line, d3d in (("rdna4", ("0x1002", "0x7550"), "AMD Radeon RX 9070 XT", "Direct3D 12 (through Proton): Ready"), + ("rdna3", ("0x1002", "0x744c"), "AMD Radeon (code 1002:744C)", "Direct3D 12 (through Proton): Not available on this card"), + ("none", (None, None), None, "Direct3D 12 (through Proton): Not available on this card")): + env, run_dir = environment(work, home, "words-" + tag) + env["WRONGGPU_TEST_DRM_ROOT"] = "Z:" + str(fake_drm(run_dir / "drm", *ids)) + out = work / ("words-" + tag) + r = run(exe, ["ui-dump", f"--dump={out / 'dump.json'}"], env, 300) + check(r.returncode == 0, f"ui-dump ({tag}) exits 0 (got {r.returncode}: {r.stderr[-300:]})") + d = json.loads((out / "dump.json").read_text()) + lines = d["first_run_lines"] + check(any(l.startswith("Linux: ") and "Windows" not in l for l in lines), f"{tag}: the system line names Linux ({lines[:1]})") + check(not any(l.startswith("Windows:") for l in lines), f"{tag}: no Windows line") + check(d3d in lines, f"{tag}: '{d3d}' ({[l for l in lines if 'Direct3D' in l]})") + check(any(l.startswith("Graphics card detected: " + gpu_line) for l in lines) if gpu_line else any(l.startswith("No graphics card found.") for l in lines), + f"{tag}: the card line says '{gpu_line}'") + check(not any(l.startswith("HIP runtime") for l in lines), f"{tag}: no HIP runtime line") + check(d["first_run_install_offer"] is False and not any(c["text"] == "Install for this user" for c in d["first_run"]["controls"]), + f"{tag}: no Install for this user choice") + + +def fake_proc(root, appdir, image): + """A made-up process folder (WRONGGPU_TEST_PROC_ROOT) with what the AppImage runtime's mount leaves: a mount table line for $APPDIR, + a process started from the AppImage file and its /dev/fuse descriptor naming the mount (image None: no such process).""" + st = os.stat(appdir) + (root / "self").mkdir(parents=True) + (root / "self" / "mountinfo").write_text("1003 60 %d:%d / %s ro,nosuid,nodev - fuse.WrongGPU-test-x86_64.AppImage WrongGPU-test-x86_64.AppImage ro\n" % + (os.major(st.st_dev), os.minor(st.st_dev), str(appdir).replace(" ", "\\040"))) + if image: + (root / "4242" / "fdinfo").mkdir(parents=True) + (root / "4242" / "exe").symlink_to(image) + (root / "4242" / "fdinfo" / "5").write_text("pos:\t0\nflags:\t02100002\nmnt_id:\t43\nino:\t136\nfuse_connection:\t%d\n" % os.minor(st.st_dev)) + + +def test_appimage_settings(exe, work, home): + """S5: Settings on Linux: run from an AppImage it has Uninstall WrongGPU and says which file and folder go; run from anywhere else it + says so and offers nothing (and never Install for this user, which cannot work here).""" + print("Settings > Uninstall WrongGPU (Linux)") + for tag, with_image in (("appimage", True), ("plain", False)): + env, run_dir = environment(work, home, "uninstall-" + tag) + if with_image: + image = run_dir / "Apps" / "WrongGPU-test-x86_64.AppImage" + image.parent.mkdir(parents=True) + image.write_bytes(b"\x7fELF\x02\x01\x01\x00AI\x02\x00\x00\x00\x00\x00fake") + appdir = Path(exe).resolve().parent + fake_proc(run_dir / "proc", appdir, image) + env.update(APPIMAGE=str(image), APPDIR=str(appdir), WRONGGPU_TEST_PROC_ROOT=str(run_dir / "proc")) + out = work / ("uninstall-" + tag) + r = run(exe, ["ui-dump", f"--dump={out / 'dump.json'}"], env, 300) + check(r.returncode == 0, f"ui-dump ({tag}) exits 0 (got {r.returncode}: {r.stderr[-300:]})") + names = [c["text"] for c in json.loads((out / "dump.json").read_text())["settings"]["controls"]] + button = [n for n in names if n.startswith("Uninstall WrongGPU")] + check(bool(button) == with_image, f"{tag}: the Uninstall WrongGPU button is {'there' if with_image else 'not there'} ({button})") + check("Install for this user" not in names and "Remove data\u2026" not in names and "Uninstall launcher\u2026" not in names, f"{tag}: no Windows install or uninstall button") + said = " ".join(names) + # review fix: Linux words on the changed screens (no Windows app mode, no Windows accent colour, the data folder as /path) + dump_text = (out / "dump.json").read_text() + appearance = " ".join(n for n in names if n.startswith("Appearance:") and n not in ("Appearance: System", "Appearance: Light", "Appearance: Dark")) + check("the desktop's light or dark setting" in appearance, f"{tag}: the Appearance row names the desktop's light or dark setting ({appearance[:160]})") + check("Windows" not in appearance, f"{tag}: the Appearance row has no Windows words ({appearance[:160]})") + swatches = [n for n in names if n.startswith("Accent color: ") and n[14:] in ("Green", "Blue", "Purple", "Pink", "Cyan", "Graphite", "Windows")] + check(len(swatches) == 6 and "Accent color: Windows" not in swatches, f"{tag}: six accent swatches, no Windows one ({swatches})") + data_line = re.findall(r"Settings and logs: ([^\"]*)", dump_text) + check(bool(data_line) and data_line[0].startswith("/") and "Z:" not in data_line[0] and "\\\\" not in data_line[0], f"{tag}: the data folder is shown as a /path ({data_line[:1]})") + # S6: no downloads on Linux, said on the page (OptiScaler row, release check row without its switch and address field) + opti = " ".join(n for n in names if n.startswith("OptiScaler:")) + check("Downloads are off on Linux" in opti and "Needs your download" in opti, f"{tag}: the OptiScaler row says downloads are off ({opti[:160]})") + rel = " ".join(n for n in names if n.startswith("Check for new releases")) + check("Off on Linux" in rel and "get the new AppImage" in rel, f"{tag}: the release check row says it is off on Linux ({rel[:160]})") + check(not any(n in ("Check now", "Release address (https)") for n in names), f"{tag}: no release address field or Check now") + check(("Runs from an AppImage" in said and "Nothing else is deleted" in said) if with_image else "not running from an AppImage" in said, + f"{tag}: Settings says what goes, or why nothing can ({[n for n in names if 'AppImage' in n][:3]})") + + +def test_appimage_unproven(exe, work, home): + """A WrongGPU AppImage that is not the one running (the mount has no server started from it): no Uninstall button, and Settings says + WrongGPU cannot prove the file is its own.""" + print("Settings > Uninstall WrongGPU, the file is not the running AppImage (Linux)") + env, run_dir = environment(work, home, "uninstall-unproven") + image = run_dir / "Apps" / "WrongGPU-test-x86_64.AppImage" + image.parent.mkdir(parents=True) + image.write_bytes(b"\x7fELF\x02\x01\x01\x00AI\x02\x00\x00\x00\x00\x00fake") + appdir = Path(exe).resolve().parent + fake_proc(run_dir / "proc", appdir, None) + env.update(APPIMAGE=str(image), APPDIR=str(appdir), WRONGGPU_TEST_PROC_ROOT=str(run_dir / "proc")) + out = work / "uninstall-unproven" + r = run(exe, ["ui-dump", f"--dump={out / 'dump.json'}"], env, 300) + check(r.returncode == 0, f"ui-dump (unproven) exits 0 (got {r.returncode}: {r.stderr[-300:]})") + names = [c["text"] for c in json.loads((out / "dump.json").read_text())["settings"]["controls"]] + check(not any(n.startswith("Uninstall WrongGPU") for n in names), "unproven: no Uninstall WrongGPU button") + check("cannot prove" in " ".join(names), f"unproven: Settings says WrongGPU cannot prove the file is its own ({[n for n in names if 'AppImage' in n][:3]})") + + +def test_rrconfig_myself(exe, work, home): + """Engine.ini "Myself" on a game's page, in Linux terms: file manager, text editor and file permissions (Notepad, File Explorer and + Properties are Windows'); the Steam launch option keeps Steam's own Properties words. The render's fixture is the game.""" + print("Engine.ini Myself steps (Linux words)") + env, _ = environment(work, home, "myself") + out = work / "myself" + r = run(exe, ["ui-render", f"--out-dir={out}", f"--fixture={HERE / 'ui_fixture.ini'}", "--size=1180x1500", "--scales=1", + "--frames=game-rrconfig-myself,game-rrconfig-myself-notro"], env, 600) + check(r.returncode == 0, f"ui-render (myself) exits 0 (got {r.returncode}: {r.stderr[-300:]})") + for frame in ("game-rrconfig-myself", "game-rrconfig-myself-notro"): + texts = (out / f"{frame}@100.png.texts").read_text(encoding="utf-8") + steps = [l.split("\t", 2)[-1] for l in texts.splitlines() if "\tStep " in l or l.split("\t", 2)[-1].startswith("Step ")] + joined = " ".join(steps) + check("Step 2: Create or open Engine.ini there with a text editor" in joined, f"{frame}: step 2 says a text editor ({steps[:2]})") + check("Step 6: Make Engine.ini read-only: in your file manager open its properties, then Permissions, and set it to read-only" in joined, + f"{frame}: step 6 makes the file read-only through the file manager's permissions ({steps[-1:]})") + check(not any(w in joined for w in ("Notepad", "File Explorer", "Right-click", "tick Read-only", "Properties")), f"{frame}: no Windows words in the steps") + notro = (out / "game-rrconfig-myself-notro@100.png.texts").read_text(encoding="utf-8") + check("Do step 6, then check again." in notro, "the not-read-only row still points at step 6") + + +def test_render(exe, work, home): + print("ui-render") + env, _ = environment(work, home, "render") + out = work / "render" + r = run(exe, ["ui-render", f"--out-dir={out}", f"--fixture={HERE / 'ui_fixture.ini'}", "--size=1180x760", "--scales=1,2", + "--frames=library,settings,game"], env, 600) + check(r.returncode == 0, f"ui-render exits 0 (got {r.returncode}: {r.stderr[-300:]})") + for frame in ("library", "settings", "game"): + check(png_size(out / f"{frame}@100.png") == (1180, 760), f"{frame}@100.png is 1180x760") + check(png_size(out / f"{frame}@200.png") == (2360, 1520), f"{frame}@200.png is 2360x1520") + check((out / f"{frame}@100.png").stat().st_size > 20000, f"{frame}@100.png is not blank") + + +def test_jpeg_art(exe, work, home, jpeg_tool): + """Steam's art is JPEG: a fixture game whose cache holds a synthetic hero (jpeg-linux-tests --make: red, green, blue and white + blocks) shows it on its page; the same render without the file shows none of those colours.""" + print("ui-render with JPEG art") + art_home = work / "home-art" + shutil.copytree(home, art_home) + cache = art_home / ".local" / "share" / "Steam" / "appcache" / "librarycache" / "1091500" + cache.mkdir(parents=True) + r = subprocess.run([str(jpeg_tool), "--make", str(cache / "library_hero.jpg"), "1920", "620"], capture_output=True, text=True) + check(r.returncode == 0, "the synthetic hero is written") + shots = {} + for name, h in (("render-noart", home), ("render-jpeg", art_home)): + env, _ = environment(work, h, name) + out = work / name + r = run(exe, ["ui-render", f"--out-dir={out}", f"--fixture={HERE / 'ui_fixture.ini'}", "--size=1180x760", "--scales=1", "--frames=game"], env, 600) + check(r.returncode == 0, f"ui-render ({name}) exits 0 (got {r.returncode}: {r.stderr[-300:]})") + shots[name] = png_pixels(out / "game@100.png") + # the page's own light background is near the white block, so the green block (top right of the picture) is the check + green = (32, 200, 40) + with_art, without = count_near(shots["render-jpeg"], green, 24), count_near(shots["render-noart"], green, 24) + check(with_art > 20000 and without < 500, f"the hero's green block is on the page with the art ({with_art} pixels) and not without ({without})") + + +def test_proton_note(exe, work, home): + """An installed game's page says which Steam launch option Proton needs for OptiScaler's dxgi.dll, with a Copy button + (ui-render writes each frame's controls to .png.texts: id, role, name).""" + print("Steam launch option note") + env, _ = environment(work, home, "proton") + out = work / "proton" + r = run(exe, ["ui-render", f"--out-dir={out}", f"--fixture={HERE / 'ui_fixture.ini'}", "--size=1180x1500", "--scales=1", "--frames=game,library"], env, 600) + check(r.returncode == 0, f"ui-render (proton note) exits 0 (got {r.returncode}: {r.stderr[-300:]})") + game = (out / "game@100.png.texts").read_text(encoding="utf-8").splitlines() + line = 'WINEDLLOVERRIDES="dxgi=n,b" %command%' + check(any(line in t and "Steam launch option" in t for t in game), "the installed game's page shows the dxgi launch option line") + check(any(t.split("\t")[2:] == ["Copy the launch option"] for t in game), "the page has the Copy button of the launch option") + card = next((t for t in game if "Steam launch option" in t), "") + steps = ("1. In Steam, right-click this game", "Properties", "2. On the General tab", "Launch Options", "3. Click Copy here, then paste", "4. Close the window") + check(all(s in card for s in steps), f"the launch option card says where to paste it, step by step ({card[:200]})") + check(not any("WINEDLLOVERRIDES" in t for t in (out / "library@100.png.texts").read_text(encoding="utf-8").splitlines()), + "the Library does not show it") + + +SCRIPT = """# a click on Settings, a scroll, a click on the Library's search field and typing in it +until games 2 +dump {o}/d0.json +shot {o}/s0.png +clickname Settings +wait 500 +dump {o}/d1.json +wheel -5 +wait 800 +dump {o}/d2.json +clickname Library +wait 500 +clickname Search games +wait 300 +text bal +wait 400 +dump {o}/d3.json +shot {o}/s3.png +key ctrl+a +key backspace +wait 400 +dump {o}/d4.json +close +""" + + +def test_live(exe, work, home): + print("live window (offscreen SDL, scripted events)") + env, run_dir = environment(work, home, "live") + (run_dir / "data" / "WrongGPU").mkdir(parents=True, exist_ok=True) + (run_dir / "data" / "WrongGPU" / "launcher.ini").write_bytes(b"first_run_done=1\r\n") # no first-run sheet over the page + out = work / "live" + out.mkdir(exist_ok=True) + script = work / "live-script.txt" + script.write_text(SCRIPT.format(o=out)) + env["WRONGGPU_UI_SCRIPT"] = str(script) + try: + r = run(exe, [], env, 180) + except subprocess.TimeoutExpired: + check(False, "the window closed on its own within 180 s") + return + check(r.returncode == 0, f"the program exits 0 after WM_CLOSE (got {r.returncode}: {r.stderr[-300:]})") + st = [json.loads((out / f"d{i}.json").read_text()) if (out / f"d{i}.json").is_file() else {} for i in range(5)] + check(st[0].get("page_name") == "library" and st[0].get("games") == 2, f"starts on the Library with two games ({st[0].get('page_name')}, {st[0].get('games')})") + check(st[1].get("page_name") == "settings", f"a click on Settings opens Settings ({st[1].get('page_name')})") + check(st[2].get("scroll", 0) > 100, f"the wheel scrolls the page (scroll {st[2].get('scroll')})") + check(st[3].get("page_name") == "library" and st[3].get("search") == "bal", f"typing reaches the search field ({st[3].get('page_name')}, '{st[3].get('search')}')") + check(any(c["class"] == "Item" and c["text"].startswith("Baldur") for c in st[3].get("controls", [])) or + any("Baldur" in c["text"] for c in st[3].get("controls", [])), "the Library is filtered to Baldur's Gate 3") + check(not any("Cyberpunk" in c["text"] for c in st[3].get("controls", [])), "the Library no longer shows Cyberpunk 2077") + check(st[4].get("search") == "", f"Ctrl+A, Backspace empties the field ('{st[4].get('search')}')") + check(png_size(out / "s0.png") is not None and png_size(out / "s3.png") is not None, "the live frames were saved as PNGs") + + +def main(): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--exe", required=True) + ap.add_argument("--work", default=None) + ap.add_argument("--only", default="dump,words,uninstall,unproven,render,myself,jpeg,proton,live") + ap.add_argument("--jpeg-tool", default=None, help="jpeg-linux-tests, which writes the synthetic JPEG art") + a = ap.parse_args() + work = Path(a.work or "linux-ui-tests").resolve() + if work.exists(): + shutil.rmtree(work) + work.mkdir(parents=True) + real_data = Path.home() / ".local" / "share" / "WrongGPU" + had = real_data.exists() + home = make_home(work) + for name, fn in (("dump", test_dump), ("words", test_first_run_words), ("uninstall", test_appimage_settings), ("unproven", test_appimage_unproven), ("render", test_render), ("myself", test_rrconfig_myself), ("proton", test_proton_note), ("live", test_live)): + if name in a.only.split(","): + fn(Path(a.exe), work, home) + if "jpeg" in a.only.split(",") and a.jpeg_tool: + test_jpeg_art(Path(a.exe), work, home, a.jpeg_tool) + check(had or not real_data.exists(), "nothing was written to the real ~/.local/share/WrongGPU") + if failures: + print(f"{len(failures)} check(s) failed") + return 1 + print("linux ui tests: all checks passed") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/clean/installer/tests/run_linux_ui_wording_tests.py b/clean/installer/tests/run_linux_ui_wording_tests.py new file mode 100644 index 00000000..35dfaaa0 --- /dev/null +++ b/clean/installer/tests/run_linux_ui_wording_tests.py @@ -0,0 +1,147 @@ +# SPDX-License-Identifier: MIT +"""The native Linux launcher's wording fixes from the UI review (launcher step 4): the exact strings a player reads. + + run_linux_ui_wording_tests.py --exe [--work ] + +Same setup as run_linux_ui_tests.py (a home of its own, a fake Steam library, SDL's offscreen driver, nothing of the player's read or +written). Needs a WRONGGPU_TESTING build of the Linux launcher. Written for this project.""" +import argparse +import json +import shutil +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +import run_linux_ui_tests as base # noqa: E402 + +check = base.check +NO_CARD = "No graphics card found. WrongGPU's models need an RX 9000-series GPU; games use AMD FSR." +HIP = "Optional. Model M runs through Proton's Direct3D 12 without it, and no game setting uses it." +IMAGE = "WrongGPU-test-x86_64.AppImage" + + +def dump_of(exe, work, home, tag, ids=("0x1002", "0x7550"), image=False, ignore=False, shots=False): + env, run_dir = base.environment(work, home, tag) + env["WRONGGPU_TEST_DRM_ROOT"] = "Z:" + str(base.fake_drm(run_dir / "drm", *ids)) + path = None + if image: + path = run_dir / "Apps" / IMAGE + path.parent.mkdir(parents=True) + path.write_bytes(b"\x7fELF\x02\x01\x01\x00AI\x02\x00\x00\x00\x00\x00fake") + appdir = Path(exe).resolve().parent + base.fake_proc(run_dir / "proc", appdir, path) + env.update(APPIMAGE=str(path), APPDIR=str(appdir), WRONGGPU_TEST_PROC_ROOT=str(run_dir / "proc")) + if ignore: + (run_dir / "data" / "WrongGPU").mkdir(parents=True, exist_ok=True) + (run_dir / "data" / "WrongGPU" / "ignore-files.txt").write_bytes(b"wronggpu-ignore-files 1\r\n") + out = work / tag + args = ["ui-dump", f"--dump={out / 'dump.json'}"] + ([f"--shots={out}"] if shots else []) + r = base.run(exe, args, env, 300) + check(r.returncode == 0, f"{tag}: ui-dump exits 0 (got {r.returncode}: {r.stderr[-300:]})") + return json.loads((out / "dump.json").read_text()), path, out + + +def test_first_run(exe, work, home): + print("first-run sheet: no card, and the Show details pictures") + for tag, ids, want in (("none", (None, None), NO_CARD), ("rdna3", ("0x1002", "0x744c"), None), ("rdna4", ("0x1002", "0x7550"), None)): + d, _, out = dump_of(exe, work, home, "fr-" + tag, ids, shots=True) + lines = d["first_run_lines"] + if want: + check(want in lines and not any(l.startswith("Graphics card detected: none") for l in lines), f"{tag}: the no-card line is exactly '{want}' ({lines[:3]})") + else: + check(any(l.startswith("Graphics card detected: AMD Radeon") for l in lines), f"{tag}: the card line is unchanged ({lines[:3]})") + pic = out / "first-run-details.png" + check(pic.is_file() and base.png_size(pic) == (1180, 760), f"{tag}: the picture of the sheet with Show details open is there") + shown = (out / "first-run-details.png.texts").read_text(encoding="utf-8").replace("\u00a0", " ").splitlines() + want_lines = [l.replace("\u00a0", " ") for l in lines if want is None or l != want] + check(all(any(t.endswith(l) for t in shown) for l in want_lines + ([want.replace("\u00a0", " ")] if want else [])) and any(t.endswith("\tHide details") for t in shown), + f"{tag}: the picture really shows every detail line and 'Hide details'") + + +def test_settings(exe, work, home): + print("Settings: the Launcher row, the side label, Appearance, HIP") + d, image, _ = dump_of(exe, work, home, "set-ignore", image=True, ignore=True) + names = [c["text"] for c in d["settings"]["controls"]] + joined = "\n".join(names) + data = str(work / "set-ignore" / "data" / "WrongGPU") + check(f"WrongGPU 0.6.5, AppImage" in joined or any(n.endswith(", AppImage") for n in names), f"the side label says AppImage ({[n for n in names if 'WrongGPU 0' in n]})") + check(not any("not installed" in n.lower() for n in names), "no 'not installed' on the AppImage's Settings") + row = next((n for n in names if n.startswith("Launcher install")), "") + check("Runs from an AppImage" in row, f"the status is 'Runs from an AppImage' ({row[:120]})") + check(row.count("Runs from") == 1, "the row does not repeat 'Runs from'") + check(f"The file: {image}. Uninstall deletes that file and WrongGPU's data folder ({data}) after you confirm." in row, f"the row's sentence names both paths ({row})") + check("Your ignore-files.txt list is kept. Nothing else is deleted." in row, f"the row says the ignore list is kept when there is one ({row[-120:]})") + check("Uninstall WrongGPU from your games first." not in row, "no 'games first' sentence while no game has WrongGPU") + appearance = " ".join(n for n in names if n.startswith("Appearance:") and n not in ("Appearance: System", "Appearance: Light", "Appearance: Dark")) + caveat = "System should follow the desktop's light or dark setting, but WrongGPU can't read it on Linux yet, so it uses light for now." + check(appearance.endswith("The launcher stays dark. " + caveat) or "The launcher stays dark." in appearance and caveat in appearance, + f"the Appearance caveat shows with Dark chosen, the default ({appearance})") + hip = " ".join(n for n in names if n.startswith("HIP runtime")) + check(HIP in hip, f"the HIP row says Model M runs through Proton's Direct3D 12 ({hip})") + d2, _, _ = dump_of(exe, work, home, "set-noignore", image=True) + row2 = next((n for n in (c["text"] for c in d2["settings"]["controls"]) if n.startswith("Launcher install")), "") + check("ignore-files.txt" not in row2 and "Nothing else is deleted." in row2, f"no ignore-list sentence when there is no list ({row2[-100:]})") + # the words by their inputs: with and without the list, with and without a game that has WrongGPU + words = d["appimage_words"] + check(len(words) == 4 and ("Uninstall WrongGPU from your games first." in words[1] and "Uninstall WrongGPU from your games first." not in words[0]), + f"the 'games first' sentence appears only when a game has WrongGPU ({words[:2]})") + check(words[2].endswith("Nothing else is deleted.") and "Your ignore-files.txt list is kept." in words[2] and "ignore-files" not in words[0], "the ignore-list sentence follows the list") + text = d["appimage_uninstall_text"] + check("Your ignore-files.txt list is kept." in text[1] and "ignore-files" not in text[0], f"the uninstall question says the list is kept, only when there is one ({text[1][-140:]})") + check("Nothing else is deleted. Your games and their files are not touched." in text[1], "the question still says nothing else is touched") + # System chosen: the caveat is the row's sentence + env, run_dir = base.environment(work, home, "set-system") + (run_dir / "data" / "WrongGPU").mkdir(parents=True, exist_ok=True) + (run_dir / "data" / "WrongGPU" / "launcher.ini").write_bytes(b"first_run_done=1\r\nappearance=system\r\n") + r = base.run(exe, ["ui-dump", f"--dump={work / 'set-system' / 'dump.json'}"], env, 300) + dd = json.loads((work / "set-system" / "dump.json").read_text()) + system = " ".join(c["text"] for c in dd["settings"]["controls"] if c["text"].startswith("Appearance:") and c["text"] not in ("Appearance: System", "Appearance: Light", "Appearance: Dark")) + check(r.returncode == 0 and caveat in system and "The launcher stays" not in system, f"with System chosen the row's sentence is the caveat ({system})") + + +def test_windows_folder_card(exe, work, home): + print("the Windows-folder card: a command the player can run, with Copy") + me = str(Path(exe).resolve()) + why = ("Can't find the game's Windows folder. It isn't a Steam game, so WrongGPU can't tell where its Proton or Wine folder is. Find the game's Windows user " + "folder, the one that holds Documents and AppData (usually pfx/drive_c/users/ inside its Proton or Wine folder). Then run this once in a terminal, " + "with the folder in place of . Keep the quotes around it, and write a ' inside the folder's name as '\\'':") + game = "M:\\SteamLibrary\\steamapps\\common\\Borderlands 4\\OakGame\\Binaries\\Win64\\Borderlands4.exe" # the render's made-up game (no Linux disk) + # the variable names a file no process of this run holds: the command is headed by this program's own file, never by that name + for tag, image in (("plain", "/home/player/Apps/WrongGPU-0.6.5-x86_64.AppImage"), ("quote", "/home/player/it's here/WrongGPU-0.6.5-x86_64.AppImage")): + env, _ = base.environment(work, home, "wf-" + tag) + env["APPIMAGE"] = image + out = work / ("wf-" + tag) + r = base.run(exe, ["ui-render", f"--out-dir={out}", f"--fixture={HERE / 'ui_fixture.ini'}", "--size=1180x1500", "--scales=1", + "--frames=game-rrconfig-nofolder-other,game-rrconfig-nofolder-steam"], env, 600) + check(r.returncode == 0, f"{tag}: ui-render exits 0 (got {r.returncode}: {r.stderr[-300:]})") + texts = (out / "game-rrconfig-nofolder-other@100.png.texts").read_text(encoding="utf-8").splitlines() + check(any(t.split("\t")[-1] == why for t in texts), f"{tag}: the card says why and what to do, whole") + want = "Point WrongGPU at the Windows folder: '" + me + "' windows-folder '" + game + "' ''" + check(any(t.split("\t")[-1] == want for t in texts), f"{tag}: the command is the program's own file, the verb, the game's exe and the folder (want {want})") + check(any(t.split("\t")[2:] == ["Copy the windows-folder command"] for t in texts), f"{tag}: the card has a Copy button") + steam = " ".join((out / "game-rrconfig-nofolder-steam@100.png.texts").read_text(encoding="utf-8").splitlines()) + check("Point WrongGPU at the Windows folder" not in steam and "Steam has not made this game's Proton folder yet" in steam, f"{tag}: a Steam game without its Proton folder gets no command card") + + +def main(): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--exe", required=True) + ap.add_argument("--work", default=None) + a = ap.parse_args() + work = Path(a.work or "linux-ui-wording-tests").resolve() + if work.exists(): + shutil.rmtree(work) + work.mkdir(parents=True) + home = base.make_home(work) + for fn in (test_first_run, test_settings, test_windows_folder_card): + fn(Path(a.exe), work, home) + if base.failures: + print(f"{len(base.failures)} check(s) failed") + return 1 + print("linux ui wording tests: all checks passed") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/clean/installer/tests/wg_core_tests.cpp b/clean/installer/tests/wg_core_tests.cpp index 80d99edd..0651a805 100644 --- a/clean/installer/tests/wg_core_tests.cpp +++ b/clean/installer/tests/wg_core_tests.cpp @@ -163,10 +163,10 @@ int main() { rctx.logFile = Join(dir, L"rr-prep.log"); const wstring game = Join(dir, L"No Rule Game\\NoRuleGame.exe"); wstring why; - if (UnderWine()) { + if (UnderProton()) { require(RrKernelsInGame(game) && RrPrepStateOf(rctx, dir, game, 1, &why) == RrPrepState::InGame && Contains(why, L"Proton"), - "RR kernels under Wine: prepared by the game at its first start"); - require(PrepareRr(rctx, dir, game, Join(dir, L"no-runtime.dll"), 1, nullptr, &why) == 4, "PrepareRr under Wine: no helper run (4)"); + "RR kernels under Proton (Wine or native Linux): prepared by the game at its first start"); + require(PrepareRr(rctx, dir, game, Join(dir, L"no-runtime.dll"), 1, nullptr, &why) == 4, "PrepareRr under Proton: no helper run (4)"); } else { require(!RrKernelsInGame(game), "RR kernels on Windows: a game without a rule is prepared by the launcher"); } @@ -211,8 +211,8 @@ int main() { require(NeedsRx9000Sentence() == L"WrongGPU's models need an RX 9000-series GPU; using AMD FSR", "NeedsRx9000Sentence: the runtime's sentence"); GpuInfo rdna4; rdna4.amd = rdna4.rdna4 = true; - require(GpuToolbarLine(L"RX 9070 XT", rdna4) == L"RX 9070 XT (detected) \u00b7 Direct3D 12", - "GpuToolbarLine: RDNA 4 is detected and runs on Direct3D 12"); + require(GpuToolbarLine(L"RX 9070 XT", rdna4) == (NativeLinux() ? L"RX 9070 XT (detected) \u00b7 Direct3D 12 (through Proton)" : L"RX 9070 XT (detected) \u00b7 Direct3D 12"), + "GpuToolbarLine: RDNA 4 is detected and runs on Direct3D 12 (through Proton on the native Linux launcher; Windows and Wine unchanged)"); GpuInfo rdna3; rdna3.amd = true; const wstring l3 = GpuToolbarLine(L"RX 7900 XTX", rdna3); @@ -253,6 +253,39 @@ int main() { card(L"card17", "0x1002\n", "0x7550 \n"); // two RDNA 4 cards: the lower number first require(Contains(LinuxRdna4Name(drm), L"7550"), "LinuxRdna4Name: cards in number order"); } + // S4: the distribution's name from /etc/os-release (any host) + { + require(LinuxOsName("NAME=\"Fedora Linux\"\nVERSION=\"44 (Nobara)\"\nPRETTY_NAME=\"Nobara Linux 44 (GNOME Edition)\"\n") == L"Nobara Linux 44 (GNOME Edition)", + "LinuxOsName: PRETTY_NAME first"); + require(LinuxOsName("NAME='Arch Linux'\nVERSION=rolling\n") == L"Arch Linux rolling", "LinuxOsName: NAME and VERSION without a pretty name, single quotes"); + require(LinuxOsName("NAME=Debian\r\n") == L"Debian", "LinuxOsName: a name without quotes, CRLF"); + require(LinuxOsName("").empty() && LinuxOsName("ID=x\nnot a pair\n").empty(), "LinuxOsName: nothing to read, no name"); + } + // S1: GpuFromDrm on a made-up folder (any host): the AMD RDNA 4 card wins, the names are the built-in list, others by code + { + const wstring drm = Join(dir, L"drm-gpu"); + auto card = [&](const wchar_t* name, const char* vendor, const char* device) { + EnsureDir(Join(drm, wstring(name) + L"\\device")); + WriteFileAtomic(Join(drm, wstring(name) + L"\\device\\vendor"), vendor, strlen(vendor)); + WriteFileAtomic(Join(drm, wstring(name) + L"\\device\\device"), device, strlen(device)); + }; + require(GpuFromDrm(Join(dir, L"no-such-drm")).name.empty(), "GpuFromDrm: a missing device list is no card"); + card(L"card0", "0x1002\n", "0x13c0\n"); // an integrated Radeon + GpuInfo g = GpuFromDrm(drm); + require(g.amd && !g.rdna4 && g.name == L"AMD Radeon (code 1002:13C0)", "GpuFromDrm: an AMD card not on the list is named by its code"); + card(L"card1", "0x1002\n", "0x7550\n"); + g = GpuFromDrm(drm); + require(g.amd && g.rdna4 && g.name == L"AMD Radeon RX 9070 XT", "GpuFromDrm: the RDNA 4 card wins over the iGPU"); + for (const auto& [id, nm] : {std::pair{"0x7551\n", L"AMD Radeon RX 9070 GRE"}, {"0x7590\n", L"AMD Radeon RX 9060 XT"}, {"0x7591\n", L"AMD Radeon RX 9060"}}) { + card(L"card1", "0x1002\n", id); + require(GpuFromDrm(drm).rdna4 && GpuFromDrm(drm).name == nm, "GpuFromDrm: each RDNA 4 id has its own name"); + } + card(L"card1", "0x1002\n", "0x744c\n"); // RDNA 3: stays unsupported + g = GpuFromDrm(drm); + require(g.amd && !g.rdna4, "GpuFromDrm: an RX 7000-series card is AMD but not RDNA 4"); + card(L"card1", "0x10de\n", "0x7550\n"); // another vendor with an RDNA 4 id + require(!GpuFromDrm(drm).rdna4, "GpuFromDrm: the vendor must be AMD"); + } // under Wine an RDNA 4 card that Linux reports is found even when Wine's own DXGI names an old Radeon. Which cards // LinuxRdna4Name looks at is checked above on the made-up folder (card20 and card17 included); here DetectGpu must follow it. if (UnderWine()) { diff --git a/clean/installer/tests/window_linux_tests.cpp b/clean/installer/tests/window_linux_tests.cpp new file mode 100644 index 00000000..b844aa11 --- /dev/null +++ b/clean/installer/tests/window_linux_tests.cpp @@ -0,0 +1,331 @@ +// SPDX-License-Identifier: MIT +// Linux: the window layer's message handling (src/platform/posix/win32_window_*.cpp) against SDL's offscreen driver, with SDL events +// pushed by the test: a display scale change, a batch of key events, text typed into an edit, WM_QUIT against due paints and timers, +// posts from another thread, SetCapture and PeekMessageW's filters. No window opens on a display. +#include + +#include +#include +#include +#include +#include + +#include "win32_window_internal.h" + +using namespace wgwin; + +static int fails = 0; +#define CHECK(c) do { if (!(c)) { std::fprintf(stderr, "FAIL line %d: %s\n", __LINE__, #c); ++fails; } } while (0) +#define CHECK_EQ(a, b) do { const long long x_ = (long long)(a), y_ = (long long)(b); if (x_ != y_) { std::fprintf(stderr, "FAIL line %d: %s == %s (%lld vs %lld)\n", __LINE__, #a, #b, x_, y_); ++fails; } } while (0) + +constexpr UINT kUser = 0x0400; + +struct Seen { + RECT dpiRect{}; + int dpiCount = 0; + UINT dpi = 0; + LPARAM lastDown = 0; + int downCount = 0; + LPARAM lastSize = 0; + int captureLost = 0; + LPARAM captureTo = 0; + int paints = 0; +}; +static std::map seen; + +static LRESULT CALLBACK TestProc(HWND h, UINT m, WPARAM wp, LPARAM lp) { + Seen& s = seen[h]; + switch (m) { + case WM_DPICHANGED: { // what the launcher's window procedure does + const RECT* r = (const RECT*)lp; + s.dpiRect = *r; ++s.dpiCount; s.dpi = HIWORD(wp); + SetWindowPos(h, nullptr, r->left, r->top, r->right - r->left, r->bottom - r->top, SWP_NOZORDER | SWP_NOACTIVATE); + return 0; + } + case WM_LBUTTONDOWN: s.lastDown = lp; ++s.downCount; return 0; + case WM_SIZE: s.lastSize = lp; return 0; + case WM_CAPTURECHANGED: ++s.captureLost; s.captureTo = lp; return 0; + case WM_PAINT: ++s.paints; return DefWindowProcW(h, m, wp, lp); + default: return DefWindowProcW(h, m, wp, lp); + } +} + +static HWND Top(int w, int h) { + HWND hw = CreateWindowExW(0, L"WgTest", L"t", WS_THICKFRAME | WS_VISIBLE, 0, 0, w, h, nullptr, nullptr, nullptr, nullptr); + ShowWindow(hw, SW_SHOW); + return hw; +} +static HWND Edit(HWND parent, const wchar_t* text, int x, int y, int w, int h) { + return CreateWindowExW(0, L"EDIT", text, WS_CHILD | WS_VISIBLE, x, y, w, h, parent, (HMENU)(uintptr_t)7, nullptr, nullptr); +} + +// everything that is ready, handled as the app's loop does +static void Pump() { + MSG m; + int guard = 0; + while (PeekMessageW(&m, nullptr, 0, 0, PM_REMOVE) && ++guard < 10000) { + if (m.message == WM_QUIT) return; + TranslateMessage(&m); + DispatchMessageW(&m); + } +} + +static unsigned SdlId(HWND h) { return Find(h)->sdlId; } +static void PushWin(SDL_EventType t, HWND h) { + SDL_Event e; + SDL_zero(e); + e.type = t; + e.window.windowID = SdlId(h); + SDL_PushEvent(&e); +} +static void PushKey(HWND h, SDL_Keycode k, SDL_Keymod mod, bool down) { + SDL_Event e; + SDL_zero(e); + e.type = down ? SDL_EVENT_KEY_DOWN : SDL_EVENT_KEY_UP; + e.key.windowID = SdlId(h); + e.key.key = k; e.key.mod = mod; e.key.down = down; + SDL_PushEvent(&e); +} +static void PushMouse(HWND h, SDL_EventType t, float x, float y) { + SDL_Event e; + SDL_zero(e); + e.type = t; + if (t == SDL_EVENT_MOUSE_MOTION) { e.motion.windowID = SdlId(h); e.motion.x = x; e.motion.y = y; } + else { e.button.windowID = SdlId(h); e.button.x = x; e.button.y = y; e.button.button = SDL_BUTTON_LEFT; e.button.clicks = 1; e.button.down = t == SDL_EVENT_MOUSE_BUTTON_DOWN; } + SDL_PushEvent(&e); +} +static void PushText(HWND h, const char* text) { + static std::string keep; + keep = text; + SDL_Event e; + SDL_zero(e); + e.type = SDL_EVENT_TEXT_INPUT; + e.text.windowID = SdlId(h); + e.text.text = keep.c_str(); + SDL_PushEvent(&e); +} +static std::wstring Text(HWND h) { + wchar_t b[256]; + GetWindowTextW(h, b, 256); + return b; +} +static void Sel(HWND h, int& a, int& b) { + DWORD s = 0, e = 0; + SendMessageW(h, EM_GETSEL, (WPARAM)&s, (LPARAM)&e); + a = (int)s; b = (int)e; +} + +// 1. a display scale change: the density is read again before the suggested rect and the mouse use it +static void TestDpi() { + HWND a = Top(400, 300), b = Top(300, 200); + HWND field = Edit(a, L"", 180, 80, 200, 40); + Pump(); + seen.clear(); + TestSetPixelDensity(2.f); + PushWin(SDL_EVENT_WINDOW_DISPLAY_SCALE_CHANGED, a); // both queued before either is handled: each has its own rect + PushWin(SDL_EVENT_WINDOW_DISPLAY_SCALE_CHANGED, b); + Pump(); + CHECK_EQ(seen[a].dpiCount, 1); + CHECK_EQ(seen[b].dpiCount, 1); + CHECK_EQ(seen[a].dpi, 192); + CHECK_EQ(seen[a].dpiRect.right - seen[a].dpiRect.left, 800); // the SDL window kept its units: 400 x 2 pixels + CHECK_EQ(seen[a].dpiRect.bottom - seen[a].dpiRect.top, 600); + CHECK_EQ(seen[b].dpiRect.right - seen[b].dpiRect.left, 600); + CHECK_EQ(seen[b].dpiRect.bottom - seen[b].dpiRect.top, 400); + RECT rc{}; + GetClientRect(a, &rc); + CHECK_EQ(rc.right, 800); // SetWindowPos with the suggested rect: not scaled twice (1600) + CHECK_EQ(rc.bottom, 600); + GetClientRect(b, &rc); + CHECK_EQ(rc.right, 600); + CHECK_EQ(rc.bottom, 400); + // a click at SDL unit (100, 50) is pixel (200, 100): inside the field at x 180..380, y 80..120 + PushMouse(a, SDL_EVENT_MOUSE_MOTION, 100, 50); + PushMouse(a, SDL_EVENT_MOUSE_BUTTON_DOWN, 100, 50); + PushMouse(a, SDL_EVENT_MOUSE_BUTTON_UP, 100, 50); + Pump(); + CHECK(GetFocus() == field); + // the pixel size alone changing (the compositor scaled the window to another density) is read the same way, with no WM_DPICHANGED + TestSetPixelDensity(3.f); + seen[a].dpiCount = 0; + PushWin(SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED, a); + Pump(); + CHECK_EQ(LOWORD(seen[a].lastSize), 1200); + seen[a].downCount = 0; + PushMouse(a, SDL_EVENT_MOUSE_MOTION, 100, 50); + PushMouse(a, SDL_EVENT_MOUSE_BUTTON_DOWN, 100, 50); + PushMouse(a, SDL_EVENT_MOUSE_BUTTON_UP, 100, 50); + Pump(); + CHECK_EQ(seen[a].downCount, 1); + CHECK_EQ(GET_X_LPARAM(seen[a].lastDown), 300); // pixel = unit x 3 (the field has the focus: a click on it would not reach the window) + CHECK_EQ(GET_Y_LPARAM(seen[a].lastDown), 150); + TestSetPixelDensity(0.f); + DestroyWindow(a); + DestroyWindow(b); +} + +// 2. Ctrl down, A down, A up, Ctrl up in one batch: the A key is handled with Ctrl down +// 1b. a second scale change while the first WM_DPICHANGED is still queued (a filtered peek pumped SDL but left it there) +// updates that message: one WM_DPICHANGED whose DPI and rect both describe the latest scale +static void TestDpiQueuedTwice() { + HWND c = Top(300, 200); + Pump(); + seen.clear(); + MSG m{}; + TestSetPixelDensity(2.f); + PushWin(SDL_EVENT_WINDOW_DISPLAY_SCALE_CHANGED, c); + PeekMessageW(&m, nullptr, WM_PAINT, WM_PAINT, PM_NOREMOVE); // pumps SDL; WM_DPICHANGED is outside the range and stays queued + TestSetPixelDensity(3.f); + PushWin(SDL_EVENT_WINDOW_DISPLAY_SCALE_CHANGED, c); + PeekMessageW(&m, nullptr, WM_PAINT, WM_PAINT, PM_NOREMOVE); + Pump(); + CHECK_EQ(seen[c].dpiCount, 1); + CHECK_EQ(seen[c].dpi, 288); + CHECK_EQ(seen[c].dpiRect.right - seen[c].dpiRect.left, 900); // 300 units at 3x, matching the DPI it came with + TestSetPixelDensity(0.f); + DestroyWindow(c); +} + +static void TestKeyBatch() { + HWND w = Top(400, 300); + HWND e = Edit(w, L"abc", 10, 10, 200, 30); + Pump(); + SetFocus(e); + SendMessageW(e, EM_SETSEL, 1, 1); + PushKey(w, SDLK_LCTRL, SDL_KMOD_LCTRL, true); + PushKey(w, SDLK_A, SDL_KMOD_LCTRL, true); + PushKey(w, SDLK_A, SDL_KMOD_LCTRL, false); + PushKey(w, SDLK_LCTRL, SDL_KMOD_NONE, false); + Pump(); + int a = -1, b = -1; + Sel(e, a, b); + CHECK_EQ(a, 0); + CHECK_EQ(b, 3); + CHECK(GetKeyState(VK_CONTROL) >= 0); // the last message handled was the Ctrl release + DestroyWindow(w); +} + +// 3. the caret after the text is set is at its start, as in a Win32 edit (typing goes in front) +static void TestCaret() { + HWND w = Top(400, 300); + HWND e = Edit(w, L"0.5", 10, 10, 200, 30); + Pump(); + SetFocus(e); + PushText(w, "1"); + Pump(); + CHECK(Text(e) == L"10.5"); + SetWindowTextW(e, L"xyz"); + int a = -1, b = -1; + Sel(e, a, b); + CHECK_EQ(a, 0); + CHECK_EQ(b, 0); + PushText(w, "!"); + Pump(); + CHECK(Text(e) == L"!xyz"); + DestroyWindow(w); +} + +// 4a. WM_QUIT comes before a paint or a timer that is due +static void TestQuitFirst() { + HWND w = Top(200, 100); + Pump(); + InvalidateRect(w, nullptr, FALSE); + SetTimer(w, 9, 1, nullptr); + std::this_thread::sleep_for(std::chrono::milliseconds(40)); + PostQuitMessage(7); + MSG m{}; + int others = 0; + bool quit = false; + for (int i = 0; i < 50 && !quit; ++i) { + if (!PeekMessageW(&m, nullptr, 0, 0, PM_REMOVE)) break; + if (m.message == WM_QUIT) { quit = true; CHECK_EQ(m.wParam, 7); } + else if (m.message == WM_PAINT || m.message == WM_TIMER) ++others; + } + CHECK(quit); + CHECK_EQ(others, 0); + KillTimer(w, 9); + DestroyWindow(w); +} + +// 4b. a post from another thread carries no pointer position (the UI thread's is not read across threads) +static void TestCrossThreadPost() { + HWND w = Top(400, 300); + Pump(); + PushMouse(w, SDL_EVENT_MOUSE_MOTION, 50, 60); + Pump(); + POINT p{}; + GetCursorPos(&p); + CHECK(p.x != 0 || p.y != 0); + std::thread([&] { PostMessageW(w, kUser + 1, 0, 0); }).join(); + PostMessageW(w, kUser + 2, 0, 0); + MSG m; + bool a = false, b = false; + while (PeekMessageW(&m, nullptr, 0, 0, PM_REMOVE)) { + if (m.message == kUser + 1) { a = true; CHECK(m.pt.x == 0 && m.pt.y == 0); } + if (m.message == kUser + 2) { b = true; CHECK(m.pt.x == p.x && m.pt.y == p.y); } + } + CHECK(a && b); + DestroyWindow(w); +} + +// 4d. taking the capture from another window tells the first one +static void TestCapture() { + HWND a = Top(200, 100), b = Top(200, 100); + Pump(); + seen.clear(); + SetCapture(a); + SetCapture(b); + CHECK_EQ(seen[a].captureLost, 1); + CHECK((HWND)seen[a].captureTo == b); + SetCapture(b); // the same window again: nothing lost + CHECK_EQ(seen[b].captureLost, 0); + ReleaseCapture(); + DestroyWindow(a); + DestroyWindow(b); +} + +// 4e. PeekMessageW's window, range and PM_NOREMOVE for the paints and timers it makes up +static void TestPeekFilters() { + HWND a = Top(200, 100), b = Top(200, 100); + Pump(); + std::this_thread::sleep_for(std::chrono::milliseconds(30)); // past the frame gap + Pump(); + InvalidateRect(a, nullptr, FALSE); + MSG m{}; + CHECK(!PeekMessageW(&m, b, WM_PAINT, WM_PAINT, PM_NOREMOVE)); // b has nothing to paint + CHECK(!PeekMessageW(&m, nullptr, kUser, kUser + 10, PM_NOREMOVE)); // a paint is not in this range + CHECK(PeekMessageW(&m, a, WM_PAINT, WM_PAINT, PM_NOREMOVE) && m.hwnd == a && m.message == WM_PAINT); + CHECK(PeekMessageW(&m, nullptr, WM_PAINT, WM_PAINT, PM_NOREMOVE)); // and still there: not taken + CHECK(PeekMessageW(&m, a, 0, 0, PM_REMOVE) && m.message == WM_PAINT); + DispatchMessageW(&m); + CHECK(!PeekMessageW(&m, a, WM_PAINT, WM_PAINT, PM_NOREMOVE)); // painted: no longer invalid + SetTimer(a, 9, 20, nullptr); + std::this_thread::sleep_for(std::chrono::milliseconds(40)); + CHECK(!PeekMessageW(&m, b, WM_TIMER, WM_TIMER, PM_NOREMOVE)); + CHECK(PeekMessageW(&m, a, WM_TIMER, WM_TIMER, PM_NOREMOVE) && m.wParam == 9); + CHECK(PeekMessageW(&m, a, WM_TIMER, WM_TIMER, PM_NOREMOVE)); // left queued: it did not move to its next period + CHECK(PeekMessageW(&m, a, WM_TIMER, WM_TIMER, PM_REMOVE)); + CHECK(!PeekMessageW(&m, a, WM_TIMER, WM_TIMER, PM_NOREMOVE)); // taken: due again in 20 ms + KillTimer(a, 9); + DestroyWindow(a); + DestroyWindow(b); +} + +int main() { + setenv("SDL_VIDEO_DRIVER", "offscreen", 1); // never a window on the player's desktop + unsetenv("XDG_RUNTIME_DIR"); + WNDCLASSEXW wc{}; + wc.cbSize = sizeof wc; wc.lpfnWndProc = TestProc; wc.lpszClassName = L"WgTest"; + RegisterClassExW(&wc); + TestDpi(); + TestDpiQueuedTwice(); + TestKeyBatch(); + TestCaret(); + TestCrossThreadPost(); + TestCapture(); + TestPeekFilters(); + TestQuitFirst(); + if (fails) { std::fprintf(stderr, "window-linux-tests: %d failure(s)\n", fails); return 1; } + std::printf("window-linux-tests: ok\n"); + return 0; +} diff --git a/clean/installer/tools/elf_testing_identity.py b/clean/installer/tools/elf_testing_identity.py new file mode 100644 index 00000000..22ba94e6 --- /dev/null +++ b/clean/installer/tools/elf_testing_identity.py @@ -0,0 +1,74 @@ +# SPDX-License-Identifier: MIT +"""A WRONGGPU_TESTING Linux build's identity sum: what the PE checksum is to the testing launcher on Windows. + +The Linux testing launcher has a section .wg_testing_id (src/platform/posix/testing_identity_linux.cpp): the identity text, +then "wg-sha256:" and 32 bytes. After the link, this tool writes there the SHA-256 of the whole file with those 32 bytes +counted as zero, so a byte changed or data appended afterwards no longer matches. tests/launcher_build_facts.py checks it +(with the identity text and the test hooks' strings) before the launcher suite runs a program. + + elf_testing_identity.py write the sum (the testing build's POST_BUILD step) + +Written for this project; the standard library only. +""" +import hashlib +import struct +import sys + +SECTION = b".wg_testing_id" +SUM_MARK = b"wg-sha256:" +SHT_NOBITS = 8 + + +def sections(data): + """The sections of a 64-bit little-endian ELF file: [(name, file offset, size, type)]. ValueError when it is not one.""" + if data[:4] != b"\x7fELF" or len(data) < 64 or data[4] != 2 or data[5] != 1: + raise ValueError("not a 64-bit little-endian ELF file") + shoff = struct.unpack_from("= shnum or shoff + shnum * shentsize > len(data): + raise ValueError("no readable section table") + heads = [struct.unpack_from(" len(body): + raise ValueError("the identity section holds no sum") + return off + at + len(SUM_MARK) + + +def expected_sum(data, slot): + return hashlib.sha256(data[:slot] + b"\0" * 32 + data[slot + 32:]).digest() + + +def main(argv): + if len(argv) != 2: + print(__doc__) + return 2 + with open(argv[1], "rb") as f: + data = f.read() + slot = sum_slot(data) + with open(argv[1], "r+b") as f: + f.seek(slot) + f.write(expected_sum(data, slot)) + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv)) diff --git a/clean/installer/tools/ico_to_png.py b/clean/installer/tools/ico_to_png.py new file mode 100644 index 00000000..70d41721 --- /dev/null +++ b/clean/installer/tools/ico_to_png.py @@ -0,0 +1,32 @@ +# SPDX-License-Identifier: MIT +"""Writes the largest PNG frame of assets/wronggpu.ico as a .png file (the Linux icon of the AppImage). + + ico_to_png.py + +The .ico is the project's own icon (make_payload.py copies it to app.ico for Windows); its biggest frame is stored as PNG, so +this copies bytes and draws nothing. +""" +import struct +import sys + + +def main(): + src, dst = sys.argv[1:3] + b = open(src, "rb").read() + reserved, kind, count = struct.unpack(" best[0]): + best = (w, b[off:off + size]) + if best is None: + sys.exit("%s has no PNG frame" % src) + open(dst, "wb").write(best[1]) + print("%s: %dx%d frame -> %s" % (src, best[0], best[0], dst)) + + +if __name__ == "__main__": + main() diff --git a/clean/installer/tools/make_payload.py b/clean/installer/tools/make_payload.py index b0225eff..ee319382 100644 --- a/clean/installer/tools/make_payload.py +++ b/clean/installer/tools/make_payload.py @@ -5,7 +5,8 @@ make_payload.py --payload --map --version [--manifest ] [--hosted-only] --out -Writes /payload_table.h, /resources.rc and /app.ico. The payload directory mirrors the install folder +Writes /payload_table.h, /resources.rc, /resources.S and /app.ico (resources.S: the same RCDATA +resources as resources.rc as .incbin data plus a table, for the Linux launcher, src/platform/posix FindResourceW). The payload directory mirrors the install folder (the folder that holds the game's amd_fidelityfx_dx12.dll): WrongGPU's amd_fidelityfx_dx12.dll (the FSR front end of spec 20) at its root, plus the clean runtime and its kernel files, all from one release build. Every file is embedded, hashed (SHA-256) and verified by the installer. The converter map (spec 08) is embedded with its hash. @@ -326,6 +327,20 @@ def main(): rc.append('%d RCDATA "%s"' % (1001 + i, fwd(full))) with open(os.path.join(a.out, "resources.rc"), "w", newline="\n") as f: f.write("\n".join(rc) + "\n") + # Linux: the RCDATA resources of the script above (ids and bytes; the icon, version and manifest are Windows-only) as one + # table the POSIX FindResourceW reads: {id, type, start, size}, ended by an entry with id 0. + res = [(MAP_ID, a.map)] + ([(901, a.map_k)] if a.map_k else []) + ([(MAP_F_ID, a.map_f)] if a.map_f else []) + \ + ([(MAP_L_ID, a.map_l)] if a.map_l else []) + [(RR_FIRST_ID + i, r[3]) for i, r in enumerate(rr_rows)] + \ + ([(LOGO_ID, logo)] if os.path.isfile(logo) else []) + [(1001 + i, r[3]) for i, r in enumerate(rows)] + asm = ["// Generated by tools/make_payload.py - do not edit.", " .section .rodata", " .balign 16"] + for rid, path in res: + asm += ["wg_res_%d:" % rid, ' .incbin "%s"' % fwd(path).replace("\\", "\\\\").replace('"', '\\"'), "wg_res_%d_end:" % rid] + asm += [" .section .data.rel.ro,\"aw\"", " .balign 8", " .globl wg_resource_table", "wg_resource_table:"] + for rid, _ in res: + asm.append(" .long %d, 10\n .quad wg_res_%d, wg_res_%d_end - wg_res_%d" % (rid, rid, rid, rid)) + asm += [" .long 0, 0\n .quad 0, 0", ' .section .note.GNU-stack,"",@progbits', ""] + with open(os.path.join(a.out, "resources.S"), "w", newline="\n") as f: + f.write("\n".join(asm)) print("payload: %d files, %.1f MB from %s; map %s" % (len(rows), sum(r[2] for r in rows) / 1048576.0, root, a.map)) print("Ray Reconstruction: %s; RR converter map %s" % ("%d files from %s" % (len(rr_rows), a.rr) if rr_rows else "none", a.map_f or "none")) print("Model L converter map: %s" % (a.map_l or "none")) diff --git a/tools/ci/check_portable.py b/tools/ci/check_portable.py new file mode 100644 index 00000000..2d652416 --- /dev/null +++ b/tools/ci/check_portable.py @@ -0,0 +1,262 @@ +# SPDX-License-Identifier: MIT +"""Portability check (CI and ctest on Linux): keeps the launcher building on Linux when someone edits it on Windows. + +The launcher's shared code (src/wg_core, src/app) is compiled on Windows and on Linux. The Linux build answers Windows calls +with src/platform/posix; two mistakes get past a Windows-only build and break Linux later. This script finds both by reading +the source, without a compiler: + + (a) a std::filesystem::path made straight from a wstring in src/wg_core or src/app (constructed, copy-initialised, or a + `p = w;` assignment to a path of the same function). On Linux that spells a Windows path + ("C:\\Games", backslashes) wrongly; wg::FsPath(wstring) (src/wg_core/util.h) converts it for the host. + (b) a shared UI file (src/app/*.cpp and *.h, except WINDOWS_ONLY below) that uses Direct2D, DirectWrite, WIC, DWM or UI + Automation outside an `#ifdef _WIN32` block. Those are Windows' own; the shared code reaches the screen through Gfx + (ui_gfx.cpp on Windows, ui_gfx_cairo.cpp on Linux) and keeps the rest inside `#ifdef _WIN32`. + + check_portable.py [--root ] check the tree (exit 1 on a finding) + check_portable.py --self-test plant a violation of each rule, expect red; the clean sample, expect green +""" +import argparse +import re +import sys +from pathlib import Path + +# src/app files that exist only on Windows (the Direct2D Gfx, the GDI+ wizard, the per-game restorer): not part of the Linux build. +WINDOWS_ONLY = {"ui_gfx.cpp", "wizard.cpp", "restore_main.cpp"} + +# Windows identifiers the shared UI must keep inside `#ifdef _WIN32`. +WINDOWS_API = re.compile( + r"\b(?:ID2D1\w*|D2D1_\w+|D2D1\w*Factory\w*|IDWrite\w*|DWRITE_\w+|DWriteCreateFactory|IWIC\w+|CLSID_WIC\w+|GUID_WIC\w+" + r"|WIC[A-Z]\w+|Dwm[A-Z]\w+|DWMWA_\w+|DWMWCP_\w+|DWM_\w+|IUIAutomation\w*|UIA_\w+|Uia(?:ReturnRawElementProvider|HostProviderFromHwnd|Raise\w+|ClientsAreListening|Disconnect\w+)|IRawElementProvider\w+)\b" + r"|#\s*include\s*[<\"](?:d2d1\w*|dwrite\w*|wincodec\w*|dwmapi|uiautomation\w*)\.h[>\"]") + +# a path constructed in place: `std::filesystem::path(x)`, `fs::path{x}` or `fs::path p(x)`; a declaration without an +# initializer, a reference or a pointer is not a construction +NS_ALIAS = re.compile(r"\bnamespace\s+(\w+)\s*=\s*(?:std::)?filesystem\s*;") +# the arguments of a function declaration (`path Name(const wstring& p)`), not of a construction (`path p(w)`) +DECLARATION_ARGS = re.compile(r"^\s*(?:const\s+)?[\w:<>]+(?:\s*[&*]+\s*|\s+)\w*\s*(?:,.*)?$", re.S) +NARROW_LITERAL = re.compile(r"""^\s*(?:u8)?"(?:[^"\\]|\\.)*"\s*$""") + + +def strip_comments_and_strings(text): + """The text with comments removed and string contents blanked (lines stay where they are). #include lines keep their + header name, which is what the Windows-API check reads.""" + out, i, n = [], 0, len(text) + line_start = True + while i < n: + c = text[i] + if text.startswith("//", i): + j = text.find("\n", i) + j = n if j < 0 else j + out.append(" " * (j - i)) + i = j + continue + if text.startswith("/*", i): + j = text.find("*/", i + 2) + j = n if j < 0 else j + 2 + out.append("".join("\n" if ch == "\n" else " " for ch in text[i:j])) + i = j + continue + if c in "\"'": + if line_start is False or not re.match(r"[ \t]*#[ \t]*include", text[text.rfind("\n", 0, i) + 1:i]): + j = i + 1 + while j < n and text[j] != c and text[j] != "\n": + j += 2 if text[j] == "\\" else 1 + out.append(c + " " * max(0, j - i - 1) + (c if j < n and text[j] == c else "")) + i = j + 1 + continue + out.append(c) + line_start = c == "\n" + i += 1 + return "".join(out) + + +def windows_only_lines(code): + """The set of line numbers (1-based) that only a Windows build compiles: inside `#ifdef _WIN32`, `#if defined(_WIN32)` or + the #else of `#ifndef _WIN32`. Anything else (#if of other macros, #elif) counts as both.""" + stack, lines = [], set() + for no, line in enumerate(code.split("\n"), 1): + m = re.match(r"\s*#\s*(ifdef|ifndef|if|elif|else|endif)\b(.*)", line) + if m: + d, rest = m.group(1), m.group(2) + if d in ("ifdef", "ifndef", "if"): + win = re.search(r"\b_WIN32\b", rest) is not None + neg = d == "ifndef" or re.search(r"!\s*defined\s*\(?\s*_WIN32\b", rest) is not None or re.match(r"\s*!\s*_WIN32\b", rest) + stack.append("nonwin" if win and neg else "win" if win else "any") + elif d == "else" and stack: + stack[-1] = {"win": "nonwin", "nonwin": "win"}.get(stack[-1], "any") + elif d == "elif" and stack: + stack[-1] = "any" + elif d == "endif" and stack: + stack.pop() + if "win" in stack: + lines.add(no) + continue + if "win" in stack: + lines.add(no) + return lines + + +def check_fs_path(rel, text): + """(a): findings for one file of src/wg_core or src/app.""" + code = strip_comments_and_strings(text) + win = windows_only_lines(code) + names = {"filesystem"} | set(NS_ALIAS.findall(code)) + pat = re.compile(r"\b(?:%s)::path\b\s*(?:(\w+)\s*)?([({])" % "|".join(re.escape(n) for n in names)) + found = [] + for m in pat.finditer(code): + close = {"(": ")", "{": "}"}[m.group(2)] + depth, j = 1, m.end() + while j < len(code) and depth: + depth += code[j] == m.group(2) + depth -= code[j] == close + j += 1 + arg = code[m.end():j - 1] + line = code.count("\n", 0, m.start()) + 1 + if not arg.strip() or NARROW_LITERAL.match(arg) or line in win or (m.group(1) and DECLARATION_ARGS.match(arg)): + continue + found.append("%s:%d: std::filesystem::path built directly (%s); use wg::FsPath(wstring) from wg_core/util.h" + % (rel, line, " ".join(code[m.start():j].split())[:80])) + # copy-initialisation compiles from a wstring too: `fs::path p = w;` (a narrow literal or wg::FsPath on the right is fine) + init = re.compile(r"\b(?:%s)::path\s+\w+\s*=\s*([^;]+);" % "|".join(re.escape(n) for n in names)) + for m in init.finditer(code): + rhs = m.group(1).strip() + line = code.count("\n", 0, m.start()) + 1 + if NARROW_LITERAL.match(rhs) or rhs.startswith(("FsPath(", "wg::FsPath(")) or line in win: + continue + found.append("%s:%d: std::filesystem::path copy-initialised (%s); use wg::FsPath(wstring) from wg_core/util.h" + % (rel, line, " ".join(code[m.start():m.end()].split())[:80])) + # assignment: `fs::path p; ... p = w;` with w a wstring of the same function (a function ends at a `}` in column 0), or a + # wide literal. Only a plain wstring or wide literal on the right counts, so another path or a call never flags. + assign = re.compile(r"(?m)^[ \t]*(\w+)\s*=\s*(L\"[^;]*|\w+)\s*;") + start = 0 + for body in re.split(r"(?m)^\}", code): + paths = set(re.findall(r"\b(?:%s)::path\s+(\w+)\s*[;=({]" % "|".join(re.escape(n) for n in names), body)) + wides = set(re.findall(r"\b(?:std::)?wstring(?:_view)?\s*[&*]*\s*(\w+)", body)) | set(re.findall(r"\bwchar_t\s*\*?\s*(\w+)", body)) + for m in assign.finditer(body): + rhs = m.group(2) + line = code.count("\n", 0, start + m.start()) + 1 + if m.group(1) in paths and (rhs.startswith('L"') or rhs in wides) and line not in win: + found.append("%s:%d: std::filesystem::path assigned from a wide string (%s); use wg::FsPath(wstring) from wg_core/util.h" + % (rel, line, " ".join(m.group(0).split())[:80])) + start += len(body) + 1 + return found + + +def check_windows_api(rel, text, standins=frozenset()): + """(b): findings for one shared UI file. `standins` are the names and headers src/platform/posix provides (the Linux build + compiles a use of those); a name the file defines itself (a Linux stub struct) is its own, not Windows'.""" + code = strip_comments_and_strings(text) + win = windows_only_lines(code) + own = set(re.findall(r"\b(?:struct|class|enum|using|typedef)\s+(\w+)", code)) + found = [] + for no, line in enumerate(code.split("\n"), 1): + for m in WINDOWS_API.finditer(line): + name = m.group(0).strip() + header = re.search(r"[<\"](\w+\.h)[>\"]", name) + if no in win or name in own or (header.group(1) if header else name) in standins: + continue + found.append("%s:%d: %s is Windows-only; put it inside #ifdef _WIN32 or behind Gfx, or add a stand-in in " + "src/platform/posix" % (rel, no, name)) + return found + + +def standins_of(root): + """What src/platform/posix provides: its header names and every word its headers declare.""" + names = set() + for h in (root / "src/platform/posix").glob("*.h"): + names.add(h.name) + names.update(re.findall(r"\w+", strip_comments_and_strings(h.read_text(encoding="utf-8", errors="replace")))) + return names + + +def check_tree(root): + found = [] + for sub in ("src/wg_core", "src/app"): + for f in sorted((root / sub).glob("*")): + if f.suffix in (".cpp", ".h"): + found += check_fs_path("%s/%s" % (sub, f.name), f.read_text(encoding="utf-8", errors="replace")) + standins = standins_of(root) + for f in sorted((root / "src/app").glob("*")): + if f.suffix in (".cpp", ".h") and f.name not in WINDOWS_ONLY: + found += check_windows_api("src/app/" + f.name, f.read_text(encoding="utf-8", errors="replace"), standins) + return found + + +CLEAN = """\ +#include +namespace fs = std::filesystem; +#ifdef _WIN32 +#include +#include +inline std::filesystem::path Direct(const std::wstring& p) { return std::filesystem::path(p); } // Windows spells it as is +ID2D1Factory* f = nullptr; +#else +std::filesystem::path FsPath(const std::wstring& p); +#endif +// std::filesystem::path(wide) and ID2D1Factory in a comment, "fs::path(x)" and "DwmSetWindowAttribute" in a string +const char* s = "fs::path(x) DwmSetWindowAttribute"; +void F(const fs::path& a, const std::filesystem::path* b) { std::filesystem::path none; auto c = fs::path("narrow"); fs::path d; } +void G(const std::wstring& w) { auto p = wg::FsPath(w); (void)p; std::filesystem::path q = wg::FsPath(w); fs::path r = "narrow"; } +void H(const std::wstring& w, const fs::path& other) { + fs::path a; + a = wg::FsPath(w); + a = other; + std::wstring s2 = w; + s2 = w; +} +std::filesystem::path FsPath(const std::wstring& p); +#ifndef _WIN32 +struct IWICImagingFactory { void Release() {} }; // the Linux branch's own stub of a name Windows has +#endif +#include +HRESULT r = DwmSetWindowAttribute(h, 13, &v, sizeof v); // posix/dwmapi.h stands in for it +""" +CLEAN_STANDINS = {"dwmapi.h", "DwmSetWindowAttribute"} + +PLANTED = { + "(a) path from a wstring, fully qualified": ("src/wg_core/x.cpp", "void F(const std::wstring& w) { auto p = std::filesystem::path(w); }\n", check_fs_path), + "(a) path from a wstring, through an alias": ("src/app/x.cpp", "namespace fs = std::filesystem;\nvoid F(const std::wstring& w) { fs::path p(w); }\n", check_fs_path), + "(a) path from a wstring, in the Linux branch": ("src/app/x.cpp", "#ifdef _WIN32\n#else\nvoid F(const std::wstring& w) { std::filesystem::path p{w}; }\n#endif\n", check_fs_path), + "(a) path copy-initialised from a wstring": ("src/wg_core/x.cpp", "void F(const std::wstring& w) { std::filesystem::path p = w; }\n", check_fs_path), + "(a) path assigned from a wstring": ("src/app/x.cpp", "void F(const std::wstring& w) {\n std::filesystem::path p;\n p = w;\n}\n", check_fs_path), + "(a) path assigned from a wide literal": ("src/wg_core/x.cpp", "namespace fs = std::filesystem;\nvoid F() {\n fs::path p;\n p = L\"C:\\\\Games\";\n}\n", check_fs_path), + "(b) Direct2D outside #ifdef _WIN32": ("src/app/ui_x.cpp", "ID2D1Factory* g = nullptr;\n", check_windows_api), + "(b) DWM call in the Linux branch": ("src/app/ui_x.cpp", "#ifndef _WIN32\nvoid F(HWND h) { DwmSetWindowAttribute(h, 13, 0, 0); }\n#endif\n", check_windows_api), + "(b) UI Automation header": ("src/app/ui_x.cpp", "#include \n", check_windows_api), + "(b) DWM call without a stand-in": ("src/app/ui_x.cpp", "void F(HWND h) { DwmExtendFrameIntoClientArea(h, 0); }\n", check_windows_api), + "(b) WIC": ("src/app/ui_x.cpp", "void F() { IWICImagingFactory* w = nullptr; }\n", check_windows_api), +} + + +def self_test(): + ok = True + for name, (rel, text, fn) in PLANTED.items(): + hits = fn(rel, text) + print("%s %s" % ("red (found) " if hits else "FAIL (not found)", name)) + ok &= bool(hits) + for fn in (check_fs_path, check_windows_api): + hits = fn("src/app/x.cpp", CLEAN) if fn is check_fs_path else fn("src/app/x.cpp", CLEAN, CLEAN_STANDINS) + print("%s clean sample, %s" % ("green" if not hits else "FAIL", fn.__name__)) + ok &= not hits + for h in hits: + print(" ", h) + return 0 if ok else 1 + + +def main(): + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("--root", type=Path, default=Path(__file__).resolve().parents[2] / "clean" / "installer", + help="the installer folder (default: clean/installer of this checkout)") + ap.add_argument("--self-test", action="store_true", help="prove each rule fails on a planted violation and passes on a clean sample") + a = ap.parse_args() + if a.self_test: + return self_test() + found = check_tree(a.root) + for f in found: + print(f) + print("portable: %d finding(s)" % len(found)) + return 1 if found else 0 + + +if __name__ == "__main__": + sys.exit(main())