diff --git a/.gitignore b/.gitignore index c48b3e04..d5a71f64 100644 --- a/.gitignore +++ b/.gitignore @@ -15,6 +15,7 @@ Makefile DartConfiguration.tcl compile_commands.json _deps/ +.deps/ # Qt meta-object / resource / uic output *_autogen/ @@ -51,6 +52,7 @@ packaging/.tools/ # Editor / tooling .claude/ .worktrees/ +__pycache__/ # CTest output Testing/ diff --git a/CMakeLists.txt b/CMakeLists.txt index d5f07ad4..8d4ee430 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -7,8 +7,20 @@ set(CMAKE_AUTOMOC ON) set(CMAKE_AUTORCC ON) set(CMAKE_AUTOUIC ON) +if(APPLE) + enable_language(OBJCXX) + set(CMAKE_OSX_DEPLOYMENT_TARGET "12.0" CACHE STRING + "Minimum macOS version supported by FileCommander") +endif() + include(cmake/FileCommanderOptions.cmake) +if(FILECOMMANDER_DEPS_ROOT) + get_filename_component(_fc_deps_root + "${FILECOMMANDER_DEPS_ROOT}" ABSOLUTE BASE_DIR "${CMAKE_SOURCE_DIR}") + list(PREPEND CMAKE_PREFIX_PATH "${_fc_deps_root}") +endif() + # Tests and benchmarks default ON (the normal development build is unchanged), # but a packaging build turns them off: they roughly triple build time, and # tests/ hard-requires /usr/src/googletest, which a clean package builder has no @@ -33,6 +45,9 @@ add_compile_definitions( FILECOMMANDER_MEDIA_BACKEND_MPV=${FILECOMMANDER_MEDIA_BACKEND_MPV} FILECOMMANDER_MEDIA_BACKEND_WINDOWSMF=${FILECOMMANDER_MEDIA_BACKEND_WINDOWSMF} ) +if(FILECOMMANDER_USE_VCPKG) + add_compile_definitions(FILECOMMANDER_USE_VCPKG=1) +endif() if(MSVC) add_compile_options(/utf-8) endif() @@ -51,6 +66,31 @@ endif() if(FILECOMMANDER_ENABLE_NETWORK) find_package(Qt5 REQUIRED COMPONENTS WebSockets) endif() + +if(APPLE AND CMAKE_OSX_ARCHITECTURES MATCHES "arm64" AND + CMAKE_OSX_ARCHITECTURES MATCHES "x86_64") + get_target_property(_fc_qt_core_location Qt5::Core IMPORTED_LOCATION_RELEASE) + if(NOT _fc_qt_core_location) + get_target_property(_fc_qt_core_location Qt5::Core IMPORTED_LOCATION) + endif() + if(_fc_qt_core_location AND EXISTS "${_fc_qt_core_location}") + execute_process( + COMMAND /usr/bin/lipo -info "${_fc_qt_core_location}" + OUTPUT_VARIABLE _fc_qt_architectures + ERROR_VARIABLE _fc_qt_architecture_error + RESULT_VARIABLE _fc_qt_lipo_result + OUTPUT_STRIP_TRAILING_WHITESPACE + ) + if(NOT _fc_qt_lipo_result EQUAL 0 OR + NOT _fc_qt_architectures MATCHES "x86_64" OR + NOT _fc_qt_architectures MATCHES "arm64") + message(FATAL_ERROR + "Universal2 macOS builds require a universal Qt5::Core framework. " + "The selected Qt installation is not universal: " + "${_fc_qt_core_location}") + endif() + endif() +endif() find_package(LibArchive) # Official announcement-only update manifest. Tests inject a local URL through @@ -87,16 +127,36 @@ add_subdirectory(src/ui) add_subdirectory(src/viewer) add_subdirectory(src/archive) add_subdirectory(src/search) -if(FILECOMMANDER_ENABLE_LINUX_INTEGRATION AND FILECOMMANDER_ENABLE_NETWORK) +if(FILECOMMANDER_ENABLE_NETWORK AND + (FILECOMMANDER_ENABLE_LINUX_INTEGRATION OR APPLE)) add_subdirectory(src/smbhelper) endif() -add_executable(FileCommander +set(FILECOMMANDER_APP_SOURCES src/main.cpp resources/resources.qrc ) +if(APPLE) + set(FILECOMMANDER_MACOS_ICON + "${CMAKE_SOURCE_DIR}/resources/macos/FileCommander.icns") + set_source_files_properties("${FILECOMMANDER_MACOS_ICON}" + PROPERTIES MACOSX_PACKAGE_LOCATION Resources) + list(APPEND FILECOMMANDER_APP_SOURCES "${FILECOMMANDER_MACOS_ICON}") +endif() + +add_executable(FileCommander ${FILECOMMANDER_APP_SOURCES}) if(WIN32) set_target_properties(FileCommander PROPERTIES WIN32_EXECUTABLE TRUE) +elseif(APPLE) + set_target_properties(FileCommander PROPERTIES + MACOSX_BUNDLE TRUE + MACOSX_BUNDLE_GUI_IDENTIFIER "com.aigutta.FileCommander" + MACOSX_BUNDLE_BUNDLE_NAME "FileCommander" + MACOSX_BUNDLE_BUNDLE_VERSION "${PROJECT_VERSION}" + MACOSX_BUNDLE_LONG_VERSION_STRING "${PROJECT_VERSION}" + MACOSX_BUNDLE_SHORT_VERSION_STRING "${PROJECT_VERSION}" + MACOSX_BUNDLE_ICON_FILE "FileCommander.icns" + ) endif() target_link_libraries(FileCommander PRIVATE @@ -113,6 +173,27 @@ target_compile_definitions(FileCommander PRIVATE FILECOMMANDER_MEDIA_BACKEND_WINDOWSMF=${FILECOMMANDER_MEDIA_BACKEND_WINDOWSMF} ) +if(APPLE) + # Keep the bundle self-contained during development. The helper is copied + # into the conventional LaunchServices location by the helper target below. + add_executable(FileCommanderPrivilegedHelper + src/platform/macos/FileCommanderPrivilegedHelper.cpp + ) + set_target_properties(FileCommanderPrivilegedHelper PROPERTIES + OUTPUT_NAME "com.aigutta.FileCommander.privileged-helper" + RUNTIME_OUTPUT_DIRECTORY + "${CMAKE_BINARY_DIR}/FileCommander.app/Contents/Library/LaunchServices" + ) + target_link_libraries(FileCommanderPrivilegedHelper PRIVATE + platform + Qt5::Core + ) + add_dependencies(FileCommander FileCommanderPrivilegedHelper) +endif() +if(TARGET FileCommander-smb-helper) + add_dependencies(FileCommander FileCommander-smb-helper) +endif() + if(WIN32 AND CMAKE_BUILD_TYPE STREQUAL "Debug") get_filename_component(_qt_bin "${Qt5_DIR}/../../../bin" ABSOLUTE) set(_windeployqt "${_qt_bin}/windeployqt.exe") @@ -165,7 +246,13 @@ endif() # which is how the window manager ties running windows back to the launcher entry. include(GNUInstallDirs) -install(TARGETS FileCommander RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}) +if(APPLE) + install(TARGETS FileCommander BUNDLE DESTINATION .) + install(TARGETS FileCommanderPrivilegedHelper + RUNTIME DESTINATION FileCommander.app/Contents/Library/LaunchServices) +else() + install(TARGETS FileCommander RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}) +endif() if(UNIX AND NOT APPLE) install(FILES packaging/FileCommander.desktop DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/applications) diff --git a/CMakePresets.json b/CMakePresets.json index a34c16ea..65164fa9 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -69,6 +69,86 @@ "TTC_BUILD_TESTS": "OFF", "TTC_BUILD_BENCH": "OFF" } + }, + { + "name": "macos-universal2-debug", + "displayName": "macOS Universal2 Debug", + "generator": "Ninja", + "binaryDir": "${sourceDir}/build/macos-universal2-debug", + "cacheVariables": { + "CMAKE_BUILD_TYPE": "Debug", + "CMAKE_OSX_ARCHITECTURES": "x86_64;arm64", + "CMAKE_OSX_DEPLOYMENT_TARGET": "12.0", + "CMAKE_PREFIX_PATH": "$env{FILECOMMANDER_QT_ROOT}", + "TTC_BUILD_TESTS": "ON", + "TTC_BUILD_BENCH": "OFF", + "FILECOMMANDER_ENABLE_NETWORK": "ON", + "FILECOMMANDER_ENABLE_LINUX_INTEGRATION": "OFF", + "FILECOMMANDER_PREVIEW_PDF": "OFF", + "FILECOMMANDER_PREVIEW_MEDIA": "OFF", + "FILECOMMANDER_PREVIEW_OFFICE": "ON" + } + }, + { + "name": "macos-x86_64-release", + "displayName": "macOS Intel Release", + "generator": "Ninja", + "binaryDir": "${sourceDir}/build/macos-x86_64-release", + "cacheVariables": { + "CMAKE_BUILD_TYPE": "Release", + "CMAKE_OSX_ARCHITECTURES": "x86_64", + "CMAKE_OSX_DEPLOYMENT_TARGET": "12.0", + "CMAKE_TOOLCHAIN_FILE": "${sourceDir}/.deps/macos/vcpkg/scripts/buildsystems/vcpkg.cmake", + "VCPKG_TARGET_TRIPLET": "filecommander-x64-osx-release", + "VCPKG_HOST_TRIPLET": "filecommander-x64-osx-release", + "VCPKG_INSTALLED_DIR": "${sourceDir}/.deps/macos/vcpkg/installed", + "FILECOMMANDER_DEPS_ROOT": "${sourceDir}/.deps/macos/vcpkg/installed/filecommander-x64-osx-release", + "FILECOMMANDER_POPPLER_QT5_ROOT": "${sourceDir}/.deps/macos/poppler-qt5-x64", + "FILECOMMANDER_USE_VCPKG": "ON", + "TTC_BUILD_TESTS": "OFF", + "TTC_BUILD_BENCH": "OFF", + "FILECOMMANDER_ENABLE_NETWORK": "ON", + "FILECOMMANDER_ENABLE_LINUX_INTEGRATION": "OFF", + "FILECOMMANDER_PREVIEW_PDF": "ON", + "FILECOMMANDER_PREVIEW_MEDIA": "ON", + "FILECOMMANDER_MEDIA_BACKEND": "mpv", + "FILECOMMANDER_PREVIEW_OFFICE": "ON" + } + }, + { + "name": "macos-arm64-release", + "displayName": "macOS Apple Silicon Release", + "generator": "Ninja", + "binaryDir": "${sourceDir}/build/macos-arm64-release", + "cacheVariables": { + "CMAKE_BUILD_TYPE": "Release", + "CMAKE_OSX_ARCHITECTURES": "arm64", + "CMAKE_OSX_DEPLOYMENT_TARGET": "12.0", + "CMAKE_TOOLCHAIN_FILE": "${sourceDir}/.deps/macos/vcpkg/scripts/buildsystems/vcpkg.cmake", + "VCPKG_TARGET_TRIPLET": "filecommander-arm64-osx-release", + "VCPKG_HOST_TRIPLET": "filecommander-x64-osx-release", + "VCPKG_INSTALLED_DIR": "${sourceDir}/.deps/macos/vcpkg/installed", + "FILECOMMANDER_DEPS_ROOT": "${sourceDir}/.deps/macos/vcpkg/installed/filecommander-arm64-osx-release", + "FILECOMMANDER_USE_VCPKG": "ON", + "TTC_BUILD_TESTS": "OFF", + "TTC_BUILD_BENCH": "OFF", + "FILECOMMANDER_ENABLE_NETWORK": "ON", + "FILECOMMANDER_ENABLE_LINUX_INTEGRATION": "OFF", + "FILECOMMANDER_PREVIEW_PDF": "OFF", + "FILECOMMANDER_PREVIEW_MEDIA": "OFF", + "FILECOMMANDER_PREVIEW_OFFICE": "ON" + } + }, + { + "name": "macos-universal2-release", + "inherits": "macos-universal2-debug", + "displayName": "macOS Universal2 Release", + "binaryDir": "${sourceDir}/build/macos-universal2-release", + "cacheVariables": { + "CMAKE_BUILD_TYPE": "Release", + "TTC_BUILD_TESTS": "OFF", + "TTC_BUILD_BENCH": "OFF" + } } ], "buildPresets": [ @@ -77,7 +157,23 @@ { "name": "windows-msvc-x86-debug", "configurePreset": "windows-msvc-x86-debug" }, { "name": "windows-msvc-arm64-debug", "configurePreset": "windows-msvc-arm64-debug" }, { "name": "linux-debug", "configurePreset": "linux-debug" }, - { "name": "linux-release", "configurePreset": "linux-release" } + { "name": "linux-release", "configurePreset": "linux-release" }, + { + "name": "macos-universal2-debug", + "configurePreset": "macos-universal2-debug" + }, + { + "name": "macos-universal2-release", + "configurePreset": "macos-universal2-release" + }, + { + "name": "macos-x86_64-release", + "configurePreset": "macos-x86_64-release" + }, + { + "name": "macos-arm64-release", + "configurePreset": "macos-arm64-release" + } ], "testPresets": [ { @@ -89,6 +185,11 @@ "name": "linux-debug", "configurePreset": "linux-debug", "output": { "outputOnFailure": true } + }, + { + "name": "macos-universal2-debug", + "configurePreset": "macos-universal2-debug", + "output": { "outputOnFailure": true } } ] } diff --git a/README.md b/README.md index 8a45eed2..7a71d978 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ # FileCommander · 文件指挥官 -面向 Windows 和 Linux 的双栏文件管理器:熟悉的高效操作,连接不同设备。 +面向 Windows、Linux 和 macOS 的双栏文件管理器:熟悉的高效操作,连接不同设备。 [下载](https://github.com/liuwenhuan/FileCommander/releases) · [English](#english) @@ -16,13 +16,13 @@ - **跨设备文件发送和剪贴板同步。** 登录账号后,可向另一台设备发送文件:网络可达时设备间直连,否则通过中继传输。还可主动发送文字或图片到其他设备。支持官方服务器和自定义服务器;普通文件管理无需登录。 - **本地、网络与压缩包统一浏览。** 在同一工作区管理本地磁盘、SFTP、FTP、WebDAV、SMB,以及 7z、ZIP、TAR 等压缩包。 - **列表旁即时预览与编辑。** `Ctrl+Q` 在另一栏预览图片、文本、PDF、视频等文件;`Ctrl+E` 打开内嵌编辑,切换文件时不必反复开关窗口。Office 预览需另装 `office-oxide`。 -- **Windows 与 Linux 双平台。** 提供可重绑定快捷键、多语言界面,以及浅色、深色和 Green CRT 主题。 +- **Windows、Linux 与 macOS。** 提供可重绑定快捷键、多语言界面,以及浅色、深色和 Green CRT 主题。 ## 获取与构建 可用安装包以 [GitHub Releases](https://github.com/liuwenhuan/FileCommander/releases) 的实际附件为准。仓库提供 Windows 安装/便携包及 Linux DEB、AppImage、RPM 的[打包脚本](packaging/);Windows 下不要单独复制 `FileCommander.exe`,它还需要随包提供的运行库。 -Linux 开发环境需安装 Qt 5、libarchive、libssh2、libcurl、Poppler Qt5 等依赖;网络和媒体等功能的开关见 [`cmake/FileCommanderOptions.cmake`](cmake/FileCommanderOptions.cmake)。常规构建与测试: +Linux 开发环境需安装 Qt 5、libarchive、libssh2、libcurl、Poppler Qt5 等依赖;网络和媒体等功能的开关见 [`cmake/FileCommanderOptions.cmake`](cmake/FileCommanderOptions.cmake)。macOS 当前提供 Intel `x86_64` 打包流程,会使用 vcpkg、Homebrew 的 mpv/Samba 依赖,并自动编译 Qt5 Poppler 与打包 Office/SMB helper,步骤见 [`packaging/macos/README.md`](packaging/macos/README.md)。常规构建与测试: ```bash cmake -S . -B build -DCMAKE_BUILD_TYPE=Release @@ -42,7 +42,7 @@ Windows 使用 Qt 5/MSVC 及项目所需 SDK;发布包脚本见 [`packaging/bu ## English -FileCommander is a dual-pane file manager for Windows and Linux. It pairs a familiar, keyboard-friendly workflow with file transfers and clipboard sharing across devices. +FileCommander is a dual-pane file manager for Windows, Linux, and macOS. It pairs a familiar, keyboard-friendly workflow with file transfers and clipboard sharing across devices. ### Why FileCommander @@ -50,10 +50,10 @@ FileCommander is a dual-pane file manager for Windows and Linux. It pairs a fami - **Cross-device file transfers and clipboard sharing.** Sign in to send files directly between devices when reachable, with relay fallback, or explicitly send text and images through Cloud Clipboard. Use the official or a custom server; local file management needs no account. - **Local, network, and archive browsing in one workspace.** Work with local drives, SFTP, FTP, WebDAV, SMB, and archives including 7z, ZIP, and TAR. - **Preview and edit alongside the file list.** Use `Ctrl+Q` for embedded previews of images, text, PDFs, videos, and more, or `Ctrl+E` for embedded editing while navigating files. Office previews require a separate `office-oxide` installation. -- **Windows and Linux support.** Rebind shortcuts, choose from multiple languages, and switch between light, dark, and Green CRT themes. +- **Windows, Linux, and macOS support.** Rebind shortcuts, choose from multiple languages, and switch between light, dark, and Green CRT themes. ### Download and build -See [GitHub Releases](https://github.com/liuwenhuan/FileCommander/releases) for available packages. Windows packages must include the bundled runtime libraries; the EXE alone is not a complete distribution. Packaging scripts are in [`packaging/`](packaging/), and build options are in [`cmake/FileCommanderOptions.cmake`](cmake/FileCommanderOptions.cmake). The project uses Qt 5 and C++17; build and test with CMake and CTest as shown above. +See [GitHub Releases](https://github.com/liuwenhuan/FileCommander/releases) for available packages. Windows packages must include the bundled runtime libraries; the EXE alone is not a complete distribution. Packaging scripts are in [`packaging/`](packaging/), including the Intel macOS workflow in [`packaging/macos/`](packaging/macos/). Build options are in [`cmake/FileCommanderOptions.cmake`](cmake/FileCommanderOptions.cmake). The project uses Qt 5 and C++17; build and test with CMake and CTest as shown above. Read the [development record](docs/development-history.md) for design decisions and known limitations. FileCommander is licensed under [GPL-3.0-or-later](LICENSE). diff --git a/cmake/FileCommanderOptions.cmake b/cmake/FileCommanderOptions.cmake index 9e178ec6..44b70c11 100644 --- a/cmake/FileCommanderOptions.cmake +++ b/cmake/FileCommanderOptions.cmake @@ -2,11 +2,15 @@ option(FILECOMMANDER_ENABLE_NETWORK "Build network providers" ON) option(FILECOMMANDER_PREVIEW_PDF "Build Poppler PDF preview" ON) option(FILECOMMANDER_PREVIEW_MEDIA "Build media preview" ON) option(FILECOMMANDER_PREVIEW_OFFICE "Build office-oxide integration" ON) +option(FILECOMMANDER_USE_VCPKG + "Resolve third-party libraries through vcpkg CMake package configs" OFF) +set(FILECOMMANDER_DEPS_ROOT "" CACHE PATH + "Prefix containing the third-party dependencies used by this build") set(FILECOMMANDER_MEDIA_BACKEND "auto" CACHE STRING "Media backend: auto, mpv, windowsmf, or none") set_property(CACHE FILECOMMANDER_MEDIA_BACKEND PROPERTY STRINGS auto mpv windowsmf none) -if(WIN32) +if(WIN32 OR APPLE) option(FILECOMMANDER_ENABLE_LINUX_INTEGRATION "Build Linux-only DBus, GVFS, X11, libsecret and libsmbclient integration" OFF) else() diff --git a/packaging/macos/README.md b/packaging/macos/README.md new file mode 100644 index 00000000..4a5c1f06 --- /dev/null +++ b/packaging/macos/README.md @@ -0,0 +1,60 @@ +# macOS Intel build + +The supported package workflow currently produces one Intel `x86_64` app. It +uses Qt 5 and the archive/network libraries from the pinned vcpkg prefix, plus +Homebrew's `mpv` and Samba libraries. + +Install the macOS-only dependencies first: + +```bash +brew install mpv samba pkg-config +``` + +Prepare the Intel vcpkg prefix and build the application: + +```bash +packaging/macos/bootstrap-deps.sh --arch x86_64 +packaging/macos/build-x86_64.sh +``` + +The build script automatically: + +- bundles the native `FileCommander.icns` app icon into the macOS bundle; +- builds Poppler's Qt5 bindings into `.deps/macos/poppler-qt5-x64`; +- enables PDF preview and libmpv video/audio preview; +- builds the pinned `office-oxide` revision and bundles it beside the app; +- builds the SMB provider and its isolated `FileCommander-smb-helper`; +- deploys Qt, Poppler, mpv, Samba/libsmbclient, and their transitive dylibs; +- verifies that every app binary and bundled dylib is Intel-only and has no + Homebrew or build-cache absolute runtime dependency. + +The app is written to: + +```text +build/macos-x86_64-release/FileCommander.app +``` + +The icon is stored at: + +```text +build/macos-x86_64-release/FileCommander.app/Contents/Resources/FileCommander.icns +``` + +The build also checks that `Contents/Info.plist` references this icon. If the +Finder or Dock still shows an old icon after rebuilding, restart Finder or +refresh LaunchServices before diagnosing the bundle. + +The default deployment target is macOS 12.0. Set +`FILECOMMANDER_ADHOC_SIGN=0` to skip the local ad-hoc signature. Developer ID +signing, hardened runtime, and notarization remain release-environment steps. + +Useful overrides: + +```bash +FILECOMMANDER_DEPS_ROOT=/Volumes/build-cache/filecommander \ +FILECOMMANDER_BUILD_JOBS=4 \ +packaging/macos/build-x86_64.sh + +FILECOMMANDER_POPPLER_VERSION=26.04.0 \ +packaging/macos/build-poppler-qt5.sh +``` diff --git a/packaging/macos/bootstrap-deps.sh b/packaging/macos/bootstrap-deps.sh new file mode 100755 index 00000000..f5fb62f5 --- /dev/null +++ b/packaging/macos/bootstrap-deps.sh @@ -0,0 +1,402 @@ +#!/usr/bin/env bash +# +# Download and build the native macOS dependencies used by FileCommander. +# +# This script deliberately keeps the dependency tree outside the source +# checkout. It can be run on an Intel Mac with --arch arm64: vcpkg invokes +# Apple's arm64 cross compiler while its host tools continue to run as x86_64. + +set -euo pipefail + +SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" +SOURCE_DIR="$(cd -- "${SCRIPT_DIR}/../.." && pwd)" +DEPS_ROOT="${FILECOMMANDER_DEPS_ROOT:-${SOURCE_DIR}/.deps/macos}" +VCPKG_REF="${FILECOMMANDER_VCPKG_REF:-11ace808cc8a3a941f386e33726b992b22ba9e5a}" +VCPKG_URL="${FILECOMMANDER_VCPKG_URL:-https://github.com/microsoft/vcpkg.git}" +ARCH="" + +die() { + printf 'error: %s\n' "$*" >&2 + exit 1 +} + +usage() { + cat >&2 <<'EOF' +Usage: packaging/macos/bootstrap-deps.sh --arch + +Environment: + FILECOMMANDER_DEPS_ROOT Dependency cache root + FILECOMMANDER_VCPKG_REF vcpkg commit to use + FILECOMMANDER_VCPKG_URL vcpkg Git URL +EOF + exit 2 +} + +while (($#)); do + case "$1" in + --arch) + (($# >= 2)) || usage + ARCH="$2" + shift 2 + ;; + --help|-h) + usage + ;; + *) + usage + ;; + esac +done + +case "${ARCH}" in + x86_64) + TRIPLET="filecommander-x64-osx-release" + ;; + arm64) + TRIPLET="filecommander-arm64-osx-release" + ;; + *) + usage + ;; +esac + +command -v git >/dev/null 2>&1 || die "git is required" +command -v xcodebuild >/dev/null 2>&1 || die "Xcode command line tools are required" + +prepare_host_build_tools() { + local brew_command + brew_command="$(command -v brew || true)" + if [[ -n "${brew_command}" ]]; then + local brew_bin + local automake_bin + local libtool_gnubin + brew_bin="$("${brew_command}" --prefix)/bin" + automake_bin="$("${brew_command}" --prefix automake 2>/dev/null || true)/bin" + libtool_gnubin="$("${brew_command}" --prefix libtool 2>/dev/null || true)/libexec/gnubin" + export PATH="${automake_bin}:${libtool_gnubin}:${brew_bin}:${PATH}" + fi + + local missing=() + for tool in autoconf automake libtoolize; do + command -v "${tool}" >/dev/null 2>&1 || missing+=("${tool}") + done + if ((${#missing[@]})) && [[ -n "${brew_command}" ]]; then + "${brew_command}" install autoconf autoconf-archive automake libtool + export PATH="$("${brew_command}" --prefix automake)/bin:$("${brew_command}" --prefix libtool)/libexec/gnubin:${PATH}" + fi + + for tool in autoconf automake libtoolize; do + command -v "${tool}" >/dev/null 2>&1 || + die "host build tool '${tool}' is required; install autoconf, autoconf-archive, automake, and libtool" + done +} + +prepare_host_build_tools + +VCPKG_ROOT="${DEPS_ROOT}/vcpkg" +VCPKG_INSTALL_ROOT="${VCPKG_ROOT}/installed" +VCPKG_DOWNLOADS="${DEPS_ROOT}/downloads" +VCPKG_BINARY_CACHE="${DEPS_ROOT}/binary-cache" +TRIPLET_DIR="${SCRIPT_DIR}/vcpkg-triplets" +QT_CROSS_PATCH="${SCRIPT_DIR}/vcpkg-patches/qt5-base-configure-cross.patch" +QT_PORT_CROSS_PATCH="${SCRIPT_DIR}/vcpkg-patches/qt5-base-port-cross.patch" +QT_INSTALL_CROSS_PATCH="${SCRIPT_DIR}/vcpkg-patches/qt5-base-install-cross.patch" +QT_HOST_PREFIX_PATCH="${SCRIPT_DIR}/vcpkg-patches/qt5-base-host-prefix.patch" +VCPKG_QMAKE_CROSS_PATCH="${SCRIPT_DIR}/vcpkg-patches/vcpkg-configure-qmake-cross.patch" +QT_SUBMODULE_CROSS_PATCH="${SCRIPT_DIR}/vcpkg-patches/qt5-base-submodule-cross.patch" +QT_EXTERNAL_QMAKE_PATCH="${SCRIPT_DIR}/vcpkg-patches/qt5-base-external-qmake.patch" +PREFIX="${VCPKG_INSTALL_ROOT}/${TRIPLET}" +mkdir -p "${DEPS_ROOT}" "${VCPKG_DOWNLOADS}" "${VCPKG_BINARY_CACHE}" + +HOST_QT_TOOLS_ROOT="${VCPKG_INSTALL_ROOT}/filecommander-x64-osx-release/tools/qt5" + +if [[ ! -d "${VCPKG_ROOT}/.git" ]]; then + if [[ -e "${VCPKG_ROOT}" ]]; then + die "${VCPKG_ROOT} exists but is not a vcpkg checkout" + fi + git clone --filter=blob:none --no-checkout --no-tags \ + "${VCPKG_URL}" "${VCPKG_ROOT}" +fi + +# A failed arm64 attempt may have left temporary Qt port patches in the +# ignored vcpkg checkout. Restore only those generated files before the +# cleanliness check; source-tree changes are never touched by this script. +git -C "${VCPKG_ROOT}" restore -- \ + ports/qt5-base/cmake/configure_qt.cmake \ + ports/qt5-base/cmake/install_qt.cmake \ + ports/qt5-base/portfile.cmake \ + ports/qt5-base/cmake/qt_build_submodule.cmake \ + scripts/cmake/vcpkg_configure_qmake.cmake 2>/dev/null || true + +if [[ -f "${VCPKG_ROOT}/bootstrap-vcpkg.sh" ]] && + [[ -n "$(git -C "${VCPKG_ROOT}" status --porcelain)" ]]; then + die "vcpkg checkout has local changes: ${VCPKG_ROOT}" +fi + +git -C "${VCPKG_ROOT}" fetch --depth=1 origin "${VCPKG_REF}" +git -C "${VCPKG_ROOT}" checkout --detach "${VCPKG_REF}" +[[ -z "$(git -C "${VCPKG_ROOT}" status --porcelain)" ]] || + die "vcpkg checkout has local changes after checkout: ${VCPKG_ROOT}" + +if [[ ! -x "${VCPKG_ROOT}/vcpkg" ]]; then + ( + cd "${VCPKG_ROOT}" + ./bootstrap-vcpkg.sh -disableMetrics + ) +fi + +QT_CROSS_PATCH_APPLIED=0 +QT_PORT_CROSS_PATCH_APPLIED=0 +QT_INSTALL_CROSS_PATCH_APPLIED=0 +QT_HOST_PREFIX_PATCH_APPLIED=0 +VCPKG_QMAKE_CROSS_PATCH_APPLIED=0 +QT_SUBMODULE_CROSS_PATCH_APPLIED=0 +restore_qt_cross_patch() { + if ((QT_CROSS_PATCH_APPLIED)); then + git -C "${VCPKG_ROOT}" restore -- ports/qt5-base/cmake/configure_qt.cmake + fi + if ((QT_HOST_PREFIX_PATCH_APPLIED)); then + git -C "${VCPKG_ROOT}" restore -- ports/qt5-base/cmake/configure_qt.cmake + fi + if ((QT_INSTALL_CROSS_PATCH_APPLIED)); then + git -C "${VCPKG_ROOT}" restore -- ports/qt5-base/cmake/install_qt.cmake + fi + if ((QT_PORT_CROSS_PATCH_APPLIED)); then + git -C "${VCPKG_ROOT}" restore -- ports/qt5-base/portfile.cmake + fi + if ((VCPKG_QMAKE_CROSS_PATCH_APPLIED)); then + git -C "${VCPKG_ROOT}" restore -- scripts/cmake/vcpkg_configure_qmake.cmake + fi + if ((QT_SUBMODULE_CROSS_PATCH_APPLIED)); then + git -C "${VCPKG_ROOT}" restore -- ports/qt5-base/cmake/qt_build_submodule.cmake + fi +} +trap restore_qt_cross_patch EXIT + +prepare_arm64_qt_host_tools() { + # The Qt 5 port needs host executables such as moc and rcc while it is + # cross-compiling the target libraries. Pass the already-built Intel Qt + # tools explicitly because this vcpkg revision does not reliably discover + # a custom host triplet on macOS. + local qt_cross_tools_root="${DEPS_ROOT}/qt-host-tools-arm64" + local target_qmodule_pri="${VCPKG_ROOT}/buildtrees/qt5-base/${TRIPLET}-rel/mkspecs/qmodule.pri" + local preserved_qmodule_pri="${qt_cross_tools_root}/qmodule.pri.arm64-preserved" + mkdir -p "${qt_cross_tools_root}/bin" + + if [[ ! -x "${HOST_QT_TOOLS_ROOT}/bin/qmake" ]]; then + printf 'Preparing x86_64 Qt host tools for the arm64 cross build\n' + "${VCPKG_ROOT}/vcpkg" install \ + qt5-base \ + --triplet=filecommander-x64-osx-release \ + --overlay-triplets="${TRIPLET_DIR}" \ + --x-install-root="${VCPKG_INSTALL_ROOT}" + fi + + [[ -x "${HOST_QT_TOOLS_ROOT}/bin/qmake" ]] || + die "x86_64 Qt host tools were not built at ${HOST_QT_TOOLS_ROOT}" + + cp "${HOST_QT_TOOLS_ROOT}/bin/qmake" \ + "${qt_cross_tools_root}/bin/qmake.bin" + if [[ -f "${qt_cross_tools_root}/mkspecs/qmodule.pri" ]] && + grep -q 'QT_CPU_FEATURES\.arm64[[:space:]]*=' \ + "${qt_cross_tools_root}/mkspecs/qmodule.pri"; then + cp "${qt_cross_tools_root}/mkspecs/qmodule.pri" \ + "${preserved_qmodule_pri}" + else + rm -f "${preserved_qmodule_pri}" + fi + rm -rf "${qt_cross_tools_root}/mkspecs" + cp -R "${HOST_QT_TOOLS_ROOT}/mkspecs" \ + "${qt_cross_tools_root}/mkspecs" + if [[ -f "${target_qmodule_pri}" ]] && + grep -q 'QT_CPU_FEATURES\.arm64[[:space:]]*=' \ + "${target_qmodule_pri}"; then + # A retry may reuse an installed qt5-base and skip its configure + # phase. Reuse the target metadata from the previous cross build + # instead of replacing it with the x86_64 host metadata above. + cp "${target_qmodule_pri}" \ + "${qt_cross_tools_root}/mkspecs/qmodule.pri" + elif [[ -f "${preserved_qmodule_pri}" ]]; then + cp "${preserved_qmodule_pri}" \ + "${qt_cross_tools_root}/mkspecs/qmodule.pri" + fi + rm -f "${preserved_qmodule_pri}" + + { + cat <<'EOF' +host_build { + QT_ARCH = x86_64 + QT_BUILDABI = x86_64-little_endian-lp64 + QT_TARGET_ARCH = arm64 + QT_TARGET_BUILDABI = arm64-little_endian-lp64 +} else { + QT_ARCH = arm64 + QT_BUILDABI = arm64-little_endian-lp64 +} +host_build { + QT_ARCHS = $$QT_ARCH +} else { + QT_ARCHS = $$QT_ARCH +} +EOF + sed \ + -e '/^QT_ARCH = /d' \ + -e '/^QT_BUILDABI = /d' \ + -e '/^QT_ARCHS = /d' \ + -e 's/^QT.global.enabled_features = /QT.global.enabled_features = cross_compile /' \ + -e 's/^QT.global.disabled_features = cross_compile /QT.global.disabled_features = /' \ + -e 's/^QT_CONFIG += /QT_CONFIG += cross_compile /' \ + -e 's/^CONFIG += /CONFIG += cross_compile /' \ + "${HOST_QT_TOOLS_ROOT}/mkspecs/qconfig.pri" + } > "${qt_cross_tools_root}/mkspecs/qconfig.pri" + + cat > "${qt_cross_tools_root}/bin/qt.conf" < "${qt_cross_tools_root}/bin/qmake" <&1)" + [[ "${arch_info}" == *"${expected_arch}"* ]] || + die "dependency has the wrong architecture: ${candidate} (${arch_info})" + fi +done + +mkdir -p "${PREFIX}" +cat > "${PREFIX}/.filecommander-dependencies" <&2 + exit 1 +} + +command -v meson >/dev/null 2>&1 || die "meson is required" +command -v ninja >/dev/null 2>&1 || die "ninja is required" +command -v curl >/dev/null 2>&1 || die "curl is required" +command -v tar >/dev/null 2>&1 || die "tar is required" +command -v pkg-config >/dev/null 2>&1 || die "pkg-config is required" + +HEADER="${PREFIX}/include/mpv/client.h" +LIBRARY="${PREFIX}/lib/libmpv.2.dylib" +if [[ -f "${HEADER}" && -e "${LIBRARY}" ]]; then + printf 'libmpv x86_64 is already available at %s\n' "${PREFIX}" + exit 0 +fi + +mkdir -p "${WORK_ROOT}" "${PREFIX}" +ARCHIVE="${WORK_ROOT}/mpv-${VERSION}.tar.gz" +SOURCE_TREE="${WORK_ROOT}/mpv-${VERSION}" +if [[ ! -f "${ARCHIVE}" ]]; then + URL="https://github.com/mpv-player/mpv/archive/refs/tags/v${VERSION}.tar.gz" + printf 'Downloading %s\n' "${URL}" + curl --fail --location --retry 3 --output "${ARCHIVE}" "${URL}" +fi +if [[ ! -f "${SOURCE_TREE}/meson.build" ]]; then + rm -rf "${SOURCE_TREE}" + tar -xzf "${ARCHIVE}" -C "${WORK_ROOT}" + if [[ ! -d "${SOURCE_TREE}" ]]; then + extracted="${WORK_ROOT}/mpv-${VERSION}" + [[ -d "${extracted}" ]] || + die "mpv source tree was not extracted: ${extracted}" + fi +fi +[[ -f "${SOURCE_TREE}/meson.build" ]] || + die "mpv source tree was not extracted: ${SOURCE_TREE}" + +BREW="${FILECOMMANDER_BREW:-$(command -v brew || true)}" +[[ -n "${BREW}" ]] || die "Homebrew is required for FFmpeg, libass and libplacebo" +BREW_PREFIX="${FILECOMMANDER_BREW_PREFIX:-$("${BREW}" --prefix)}" +FFMPEG_PREFIX="${FILECOMMANDER_FFMPEG_ROOT:-$("${BREW}" --prefix ffmpeg)}" +LIBASS_PREFIX="${FILECOMMANDER_LIBASS_ROOT:-$("${BREW}" --prefix libass)}" +LIBPLACEBO_PREFIX="${FILECOMMANDER_LIBPLACEBO_ROOT:-$("${BREW}" --prefix libplacebo)}" +for dependency in "${FFMPEG_PREFIX}" "${LIBASS_PREFIX}" "${LIBPLACEBO_PREFIX}"; do + [[ -d "${dependency}/lib" ]] || + die "required mpv dependency is missing: ${dependency}" +done + +export PKG_CONFIG_PATH="${FFMPEG_PREFIX}/lib/pkgconfig:${LIBASS_PREFIX}/lib/pkgconfig:${LIBPLACEBO_PREFIX}/lib/pkgconfig:${BREW_PREFIX}/lib/pkgconfig${PKG_CONFIG_PATH:+:${PKG_CONFIG_PATH}}" +pkg-config --exists libavcodec libavfilter libavformat libavutil libswresample libswscale libass libplacebo || + die "pkg-config cannot find the libmpv build dependencies" + +meson setup "${BUILD_DIR}" "${SOURCE_TREE}" \ + --prefix="${PREFIX}" \ + --libdir=lib \ + --buildtype=release \ + --default-library=shared \ + -Dcplayer=false \ + -Dlibmpv=true \ + -Dbuild-date=false \ + -Dtests=false \ + -Dhtml-build=disabled \ + -Dmanpage-build=disabled \ + -Dpdf-build=disabled \ + -Djavascript=disabled \ + -Dlua=disabled \ + -Diconv=disabled \ + -Djpeg=disabled \ + -Dlcms2=disabled \ + -Dlibarchive=disabled \ + -Dlibavdevice=disabled \ + -Dlibbluray=disabled \ + -Drubberband=disabled \ + -Duchardet=disabled \ + -Dvapoursynth=disabled \ + -Dzimg=disabled \ + -Dcdda=disabled \ + -Ddvbin=disabled \ + -Ddvdnav=disabled \ + -Dalsa=disabled \ + -Daudiounit=disabled \ + -Dcoreaudio=enabled \ + -Davfoundation=disabled \ + -Djack=disabled \ + -Dopenal=disabled \ + -Dpipewire=disabled \ + -Dpulse=disabled \ + -Dsndio=disabled \ + -Dcocoa=disabled \ + -Dgl-cocoa=disabled \ + -Dgl=enabled \ + -Dplain-gl=enabled \ + -Dvulkan=disabled \ + -Dshaderc=disabled \ + -Dspirv-cross=disabled \ + -Dx11=disabled \ + -Dwayland=disabled \ + -Degl=disabled \ + -Ddrm=disabled \ + -Dgbm=disabled \ + -Dvaapi=disabled \ + -Dvideotoolbox-gl=disabled \ + -Dvideotoolbox-pl=disabled \ + -Dmacos-cocoa-cb=disabled \ + -Dmacos-media-player=disabled \ + -Dmacos-touchbar=disabled \ + -Dswift-build=disabled \ + -Dcplugins=disabled \ + -Dvector=enabled \ + -Dzlib=enabled \ + -Dc_args="-arch x86_64 -mmacosx-version-min=${DEPLOYMENT_TARGET}" \ + -Dc_link_args="-arch x86_64 -mmacosx-version-min=${DEPLOYMENT_TARGET}" \ + -Dcpp_args="-arch x86_64 -mmacosx-version-min=${DEPLOYMENT_TARGET}" \ + -Dcpp_link_args="-arch x86_64 -mmacosx-version-min=${DEPLOYMENT_TARGET}" + +meson compile -C "${BUILD_DIR}" -j "${JOBS}" +meson install -C "${BUILD_DIR}" + +[[ -f "${HEADER}" ]] || + die "libmpv installed without the client header: ${HEADER}" +[[ -e "${LIBRARY}" ]] || + die "libmpv installed without the shared library: ${LIBRARY}" + +file -b "${LIBRARY}" | grep -q 'x86_64' || + die "libmpv is not x86_64: ${LIBRARY}" + +cat > "${PREFIX}/.filecommander-mpv" <&2 + exit 1 +} + +command -v cmake >/dev/null 2>&1 || die "cmake is required" +command -v ninja >/dev/null 2>&1 || die "ninja is required" +command -v curl >/dev/null 2>&1 || die "curl is required" +command -v tar >/dev/null 2>&1 || die "tar is required" +[[ -x "${VCPKG_ROOT}/vcpkg" ]] || + die "vcpkg is missing at ${VCPKG_ROOT}; run packaging/macos/bootstrap-deps.sh --arch x86_64" +[[ -d "${VCPKG_PREFIX}" ]] || + die "vcpkg x86_64 prefix is missing: ${VCPKG_PREFIX}" + +HEADER="${PREFIX}/include/poppler/qt5/poppler-qt5.h" +LIBRARY="${PREFIX}/lib/libpoppler-qt5.dylib" +if [[ -f "${HEADER}" && -e "${LIBRARY}" ]]; then + printf 'Poppler Qt5 is already available at %s\n' "${PREFIX}" + exit 0 +fi + +mkdir -p "${WORK_ROOT}" "${PREFIX}" + +# Keep the dependency set in the x86_64 vcpkg prefix. These are the same +# libraries Poppler needs for its core renderer; Qt itself is already present. +"${VCPKG_ROOT}/vcpkg" install \ + boost-container freetype libiconv libjpeg-turbo libpng openjpeg tiff zlib \ + --recurse \ + --triplet="${TRIPLET}" \ + --host-triplet="${TRIPLET}" \ + --overlay-triplets="${SCRIPT_DIR}/vcpkg-triplets" \ + --x-install-root="${VCPKG_INSTALL_ROOT}" + +ARCHIVE="${WORK_ROOT}/poppler-${POPPLER_VERSION}.tar.xz" +SOURCE_TREE="${WORK_ROOT}/poppler-${POPPLER_VERSION}" +if [[ ! -f "${ARCHIVE}" ]]; then + URL="https://poppler.freedesktop.org/poppler-${POPPLER_VERSION}.tar.xz" + printf 'Downloading %s\n' "${URL}" + curl --fail --location --retry 3 --output "${ARCHIVE}" "${URL}" +fi +if [[ ! -f "${SOURCE_TREE}/CMakeLists.txt" ]]; then + rm -rf "${SOURCE_TREE}" + tar -xJf "${ARCHIVE}" -C "${WORK_ROOT}" +fi +[[ -f "${SOURCE_TREE}/CMakeLists.txt" ]] || + die "Poppler source tree was not extracted: ${SOURCE_TREE}" + +BUILD_DIR="${WORK_ROOT}/build-${TRIPLET}" +PKGCONFIG_PATH="${VCPKG_PREFIX}/lib/pkgconfig:${VCPKG_PREFIX}/share/pkgconfig" +export PKG_CONFIG_PATH="${PKGCONFIG_PATH}${PKG_CONFIG_PATH:+:${PKG_CONFIG_PATH}}" + +cmake -S "${SOURCE_TREE}" -B "${BUILD_DIR}" -G Ninja \ + -DCMAKE_BUILD_TYPE=Release \ + -DCMAKE_INSTALL_PREFIX="${PREFIX}" \ + -DCMAKE_INSTALL_LIBDIR=lib \ + -DCMAKE_OSX_ARCHITECTURES=x86_64 \ + -DCMAKE_OSX_DEPLOYMENT_TARGET="${DEPLOYMENT_TARGET}" \ + -DCMAKE_INSTALL_NAME_DIR=@rpath \ + -DCMAKE_BUILD_WITH_INSTALL_RPATH=ON \ + -DCMAKE_TOOLCHAIN_FILE="${VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake" \ + -DVCPKG_TARGET_TRIPLET="${TRIPLET}" \ + -DVCPKG_HOST_TRIPLET="${TRIPLET}" \ + -DVCPKG_INSTALLED_DIR="${VCPKG_INSTALL_ROOT}" \ + -DCMAKE_PREFIX_PATH="${VCPKG_PREFIX}" \ + -DQt5_DIR="${VCPKG_PREFIX}/share/cmake/Qt5" \ + -DENABLE_QT5=ON \ + -DENABLE_QT6=OFF \ + -DENABLE_GLIB=OFF \ + -DENABLE_GOBJECT_INTROSPECTION=OFF \ + -DENABLE_CPP=ON \ + -DENABLE_UTILS=OFF \ + -DBUILD_GTK_TESTS=OFF \ + -DBUILD_QT5_TESTS=OFF \ + -DBUILD_QT6_TESTS=OFF \ + -DBUILD_CPP_TESTS=OFF \ + -DBUILD_MANUAL_TESTS=OFF \ + -DENABLE_BOOST=OFF \ + -DENABLE_LIBCURL=OFF \ + -DENABLE_LCMS=OFF \ + -DENABLE_NSS3=OFF \ + -DENABLE_GPGME=OFF \ + -DENABLE_LIBTIFF=OFF \ + -DFONT_CONFIGURATION=generic \ + -DRUN_GPERF_IF_PRESENT=OFF + +cmake --build "${BUILD_DIR}" --parallel "${JOBS}" +cmake --install "${BUILD_DIR}" + +[[ -f "${HEADER}" ]] || + die "Poppler installed without the Qt5 header: ${HEADER}" +[[ -e "${LIBRARY}" ]] || + die "Poppler installed without the Qt5 library: ${LIBRARY}" + +cat > "${PREFIX}/.filecommander-poppler-qt5" <&2 + exit 1 +} + +command -v cmake >/dev/null 2>&1 || die "cmake is required" +command -v ninja >/dev/null 2>&1 || die "ninja is required" +command -v xcrun >/dev/null 2>&1 || die "Xcode command line tools are required" +[[ -x "${VCPKG_ROOT}/vcpkg" ]] || + die "dependencies are missing; run bootstrap-deps.sh for both architectures" + +build_one() { + local arch="$1" + local triplet="$2" + local prefix="${VCPKG_INSTALL_ROOT}/${triplet}" + local build_dir="${BUILD_ROOT}/${arch}-${BUILD_CONFIG_DIR}" + local app="${build_dir}/FileCommander.app" + + [[ -d "${prefix}" ]] || + die "missing ${arch} dependencies at ${prefix}; run bootstrap-deps.sh --arch ${arch}" + + cmake -S "${SOURCE_DIR}" -B "${build_dir}" -G Ninja \ + -DCMAKE_BUILD_TYPE="${BUILD_TYPE}" \ + -DCMAKE_TOOLCHAIN_FILE="${VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake" \ + -DVCPKG_TARGET_TRIPLET="${triplet}" \ + -DVCPKG_HOST_TRIPLET="${VCPKG_HOST_TRIPLET}" \ + -DVCPKG_INSTALLED_DIR="${VCPKG_INSTALL_ROOT}" \ + -DFILECOMMANDER_DEPS_ROOT="${prefix}" \ + -DFILECOMMANDER_USE_VCPKG=ON \ + -DCMAKE_OSX_ARCHITECTURES="${arch}" \ + -DCMAKE_OSX_DEPLOYMENT_TARGET="${DEPLOYMENT_TARGET}" \ + -DTTC_BUILD_TESTS=OFF \ + -DTTC_BUILD_BENCH=OFF \ + -DFILECOMMANDER_ENABLE_NETWORK=ON \ + -DFILECOMMANDER_ENABLE_LINUX_INTEGRATION=OFF \ + -DFILECOMMANDER_PREVIEW_PDF=OFF \ + -DFILECOMMANDER_PREVIEW_MEDIA=OFF \ + -DFILECOMMANDER_PREVIEW_OFFICE=ON + cmake --build "${build_dir}" --parallel "${JOBS}" + [[ -d "${app}" ]] || die "CMake did not produce ${app}" +} + +deploy_one() { + local app="$1" + local prefix="$2" + local macdeployqt + macdeployqt="$(find \ + "${VCPKG_INSTALL_ROOT}/${VCPKG_HOST_TRIPLET}/tools" \ + -type f -name macdeployqt -perm -111 -print -quit 2>/dev/null || true)" + [[ -n "${macdeployqt}" ]] || + die "host macdeployqt was not found below ${VCPKG_INSTALL_ROOT}/${VCPKG_HOST_TRIPLET}/tools" + + "${macdeployqt}" "${app}" -always-overwrite \ + "-libpath=${prefix}/lib" \ + "-executable=${app}/Contents/Library/LaunchServices/com.aigutta.FileCommander.privileged-helper" +} + +X86_TRIPLET="filecommander-x64-osx-release" +ARM64_TRIPLET="filecommander-arm64-osx-release" +build_one x86_64 "${X86_TRIPLET}" +build_one arm64 "${ARM64_TRIPLET}" +X86_APP="${BUILD_ROOT}/x86_64-${BUILD_CONFIG_DIR}/FileCommander.app" +ARM64_APP="${BUILD_ROOT}/arm64-${BUILD_CONFIG_DIR}/FileCommander.app" + +deploy_one "${X86_APP}" "${VCPKG_INSTALL_ROOT}/${X86_TRIPLET}" +deploy_one "${ARM64_APP}" "${VCPKG_INSTALL_ROOT}/${ARM64_TRIPLET}" + +OUTPUT_APP="${BUILD_ROOT}/FileCommander-universal2.app" +python3 "${SCRIPT_DIR}/merge-universal-app.py" \ + --x86-app "${X86_APP}" \ + --arm64-app "${ARM64_APP}" \ + --output "${OUTPUT_APP}" + +if [[ "${FILECOMMANDER_ADHOC_SIGN:-1}" == "1" ]]; then + codesign --force --deep --sign - "${OUTPUT_APP}" +fi + +printf 'Universal2 app: %s\n' "${OUTPUT_APP}" diff --git a/packaging/macos/build-x86_64.sh b/packaging/macos/build-x86_64.sh new file mode 100755 index 00000000..dc96cc31 --- /dev/null +++ b/packaging/macos/build-x86_64.sh @@ -0,0 +1,412 @@ +#!/usr/bin/env bash +# +# Build and package the Intel macOS application. +# +# This script intentionally performs one architecture build only. It does not +# invoke the Universal2 builder or cross-compile an arm64 dependency tree. + +set -euo pipefail + +SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" +SOURCE_DIR="$(cd -- "${SCRIPT_DIR}/../.." && pwd)" +DEPS_ROOT="${FILECOMMANDER_DEPS_ROOT:-${SOURCE_DIR}/.deps/macos}" +VCPKG_ROOT="${DEPS_ROOT}/vcpkg" +VCPKG_INSTALL_ROOT="${VCPKG_ROOT}/installed" +TRIPLET="filecommander-x64-osx-release" +VCPKG_PREFIX="${VCPKG_INSTALL_ROOT}/${TRIPLET}" +POPPLER_PREFIX="${FILECOMMANDER_POPPLER_QT5_ROOT:-${DEPS_ROOT}/poppler-qt5-x64}" +BUILD_DIR="${FILECOMMANDER_MACOS_BUILD_DIR:-${SOURCE_DIR}/build/macos-x86_64-release}" +APP="${BUILD_DIR}/FileCommander.app" +ICON="${APP}/Contents/Resources/FileCommander.icns" +DEPLOYMENT_TARGET="${FILECOMMANDER_MACOS_DEPLOYMENT_TARGET:-12.0}" +BUILD_TYPE="${FILECOMMANDER_BUILD_TYPE:-Release}" +JOBS="${FILECOMMANDER_BUILD_JOBS:-$(sysctl -n hw.ncpu)}" +BREW="${FILECOMMANDER_BREW:-$(command -v brew || true)}" + +die() { + printf 'error: %s\n' "$*" >&2 + exit 1 +} + +[[ -n "${BREW}" ]] || die "Homebrew is required for the macOS SMB dependency" +BREW_PREFIX="${FILECOMMANDER_BREW_PREFIX:-$("${BREW}" --prefix)}" +MPV_PREFIX="${FILECOMMANDER_MPV_ROOT:-}" +if [[ -z "${MPV_PREFIX}" ]]; then + MPV_PREFIX="$("${BREW}" --prefix mpv 2>/dev/null || true)" +fi +SAMBA_PREFIX="$("${BREW}" --prefix samba 2>/dev/null || true)" +FFMPEG_PREFIX="$("${BREW}" --prefix ffmpeg 2>/dev/null || true)" +LIBASS_PREFIX="$("${BREW}" --prefix libass 2>/dev/null || true)" +LIBPLACEBO_PREFIX="$("${BREW}" --prefix libplacebo 2>/dev/null || true)" +PKGCONFIG_PREFIX="$("${BREW}" --prefix pkg-config 2>/dev/null || \ + "${BREW}" --prefix pkgconf 2>/dev/null || true)" +export PATH="${BREW_PREFIX}/bin:${PATH}" + +for tool in cmake ninja xcrun pkg-config install_name_tool otool file plutil; do + command -v "${tool}" >/dev/null 2>&1 || die "${tool} is required" +done +[[ -d "${VCPKG_PREFIX}" ]] || + die "vcpkg x86_64 dependencies are missing: ${VCPKG_PREFIX}" +[[ -d "${MPV_PREFIX}/lib" ]] || + die "x86_64 libmpv is not installed: ${MPV_PREFIX}; set FILECOMMANDER_MPV_ROOT or install Homebrew mpv" +[[ -d "${SAMBA_PREFIX}/lib" ]] || + die "Homebrew samba is not installed: ${SAMBA_PREFIX}" + +export PKG_CONFIG_PATH="${POPPLER_PREFIX}/lib/pkgconfig:${MPV_PREFIX}/lib/pkgconfig:${SAMBA_PREFIX}/lib/pkgconfig:${FFMPEG_PREFIX}/lib/pkgconfig:${LIBASS_PREFIX}/lib/pkgconfig:${LIBPLACEBO_PREFIX}/lib/pkgconfig:${BREW_PREFIX}/lib/pkgconfig:${PKGCONFIG_PREFIX}/lib/pkgconfig:${VCPKG_PREFIX}/lib/pkgconfig${PKG_CONFIG_PATH:+:${PKG_CONFIG_PATH}}" +pkg-config --exists mpv || + die "pkg-config cannot find libmpv; PKG_CONFIG_PATH=${PKG_CONFIG_PATH}" +pkg-config --exists smbclient || + die "pkg-config cannot find Homebrew smbclient; PKG_CONFIG_PATH=${PKG_CONFIG_PATH}" + +"${SCRIPT_DIR}/build-poppler-qt5.sh" "${POPPLER_PREFIX}" +[[ -f "${POPPLER_PREFIX}/include/poppler/qt5/poppler-qt5.h" ]] || + die "Poppler Qt5 was not built: ${POPPLER_PREFIX}" + +OFFICE_OUTPUT="${FILECOMMANDER_OFFICE_OXIDE_OUTPUT:-${SOURCE_DIR}/build/office-oxide}" +if [[ ! -x "${OFFICE_OUTPUT}/office-oxide" ]]; then + command -v cargo >/dev/null 2>&1 || die "cargo is required to build office-oxide" + bash "${SOURCE_DIR}/scripts/build-office-oxide.sh" "${OFFICE_OUTPUT}" +fi +[[ -x "${OFFICE_OUTPUT}/office-oxide" ]] || + die "pinned office-oxide was not built: ${OFFICE_OUTPUT}/office-oxide" + +[[ -x "${VCPKG_ROOT}/vcpkg" ]] || + die "vcpkg is missing at ${VCPKG_ROOT}" + +cmake -S "${SOURCE_DIR}" -B "${BUILD_DIR}" -G Ninja \ + -DCMAKE_BUILD_TYPE="${BUILD_TYPE}" \ + -DCMAKE_TOOLCHAIN_FILE="${VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake" \ + -DVCPKG_TARGET_TRIPLET="${TRIPLET}" \ + -DVCPKG_HOST_TRIPLET="${TRIPLET}" \ + -DVCPKG_INSTALLED_DIR="${VCPKG_INSTALL_ROOT}" \ + -DFILECOMMANDER_DEPS_ROOT="${VCPKG_PREFIX}" \ + -DFILECOMMANDER_USE_VCPKG=ON \ + -DCMAKE_OSX_ARCHITECTURES=x86_64 \ + -DCMAKE_OSX_DEPLOYMENT_TARGET="${DEPLOYMENT_TARGET}" \ + -DFILECOMMANDER_POPPLER_QT5_ROOT="${POPPLER_PREFIX}" \ + -DFILECOMMANDER_ENABLE_NETWORK=ON \ + -DFILECOMMANDER_ENABLE_LINUX_INTEGRATION=OFF \ + -DFILECOMMANDER_PREVIEW_PDF=ON \ + -DFILECOMMANDER_PREVIEW_MEDIA=ON \ + -DFILECOMMANDER_MEDIA_BACKEND=mpv \ + -DFILECOMMANDER_PREVIEW_OFFICE=ON \ + -DTTC_BUILD_TESTS=OFF \ + -DTTC_BUILD_BENCH=OFF + +cmake --build "${BUILD_DIR}" --parallel "${JOBS}" +[[ -d "${APP}" ]] || die "CMake did not produce ${APP}" +[[ -f "${ICON}" ]] || die "macOS app icon was not bundled: ${ICON}" +ICON_FILE="$(plutil -extract CFBundleIconFile raw -o - \ + "${APP}/Contents/Info.plist" 2>/dev/null || true)" +[[ "${ICON_FILE}" == "FileCommander.icns" ]] || + die "Info.plist does not reference FileCommander.icns (got: ${ICON_FILE:-})" +[[ "$(file -b "${ICON}")" == *"Mac OS X icon"* ]] || + die "invalid macOS app icon: ${ICON}" + +HELPER="${APP}/Contents/Helpers/FileCommander-smb-helper" +if [[ ! -x "${HELPER}" && -x "${BUILD_DIR}/FileCommander-smb-helper" ]]; then + mkdir -p "$(dirname -- "${HELPER}")" + cp -f "${BUILD_DIR}/FileCommander-smb-helper" "${HELPER}" + chmod +x "${HELPER}" +fi +[[ -x "${HELPER}" ]] || die "SMB helper was not built: ${HELPER}" + +PRIVILEGED_HELPER="${APP}/Contents/Library/LaunchServices/com.aigutta.FileCommander.privileged-helper" +[[ -x "${PRIVILEGED_HELPER}" ]] || + die "privileged helper was not built: ${PRIVILEGED_HELPER}" + +cp -f "${OFFICE_OUTPUT}/office-oxide" "${APP}/Contents/MacOS/office-oxide" +chmod +x "${APP}/Contents/MacOS/office-oxide" + +# The bundle may have been produced by an earlier packaging attempt. Remove +# only generated runtime directories so stale macdeployqt files cannot survive +# into a later deterministic package. +rm -rf "${APP}/Contents/Frameworks" "${APP}/Contents/PlugIns" + +FRAMEWORKS="${APP}/Contents/Frameworks" +mkdir -p "${FRAMEWORKS}" + +# Deploy the Qt runtime without macdeployqt. The vcpkg macdeployqt binary can +# spend several minutes inside install_name_tool when it follows Samba's large +# private-library closure. The application only needs a small, known Qt set; +# the recursive Mach-O pass below handles its dependencies in the same way as +# mpv, Poppler, Samba and their transitive libraries. +deploy_qt_runtime() { + local qt_module source destination plugin_dir plugin_source + local qt_modules=( + Qt5Core + Qt5Gui + Qt5Widgets + Qt5Network + Qt5WebSockets + Qt5Concurrent + Qt5OpenGL + Qt5Svg + Qt5Xml + Qt5PrintSupport + Qt5DBus + ) + for qt_module in "${qt_modules[@]}"; do + source="$(find "${VCPKG_PREFIX}/lib" -maxdepth 1 -type f \ + -name "lib${qt_module}*.dylib" -print -quit 2>/dev/null || true)" + [[ -n "${source}" ]] || + die "Qt runtime library is missing: ${qt_module}" + destination="${FRAMEWORKS}/$(basename -- "${source}")" + cp -Lf "${source}" "${destination}" + done + + for plugin_dir in platforms imageformats iconengines printsupport styles; do + plugin_source="${VCPKG_PREFIX}/plugins/${plugin_dir}" + [[ -d "${plugin_source}" ]] || continue + mkdir -p "${APP}/Contents/PlugIns/${plugin_dir}" + while IFS= read -r -d '' source; do + cp -Lf "${source}" \ + "${APP}/Contents/PlugIns/${plugin_dir}/$(basename -- "${source}")" + done < <(find -L "${plugin_source}" -maxdepth 1 -type f -print0) + done + + mkdir -p "${APP}/Contents/Resources" + cat > "${APP}/Contents/Resources/qt.conf" <<'EOF' +[Paths] +Plugins = PlugIns +Imports = Resources/qml +Qml2Imports = Resources/qml +EOF +} + +deploy_qt_runtime + +# Resolve an external dependency by its original install name. Absolute +# Homebrew/vcpkg paths are preferred; @rpath names are looked up by basename +# across the same prefixes. This keeps the closure complete for mpv, which +# pulls in FFmpeg and a sizeable codec stack through Homebrew. +find_dependency_source() { + local dependency="$1" + local base="${dependency##*/}" + if [[ "${dependency}" != @* && -f "${dependency}" ]]; then + printf '%s\n' "${dependency}" + return 0 + fi + local root + for root in \ + "${MPV_PREFIX}" \ + "${SAMBA_PREFIX}" \ + "${BREW_PREFIX}/opt" \ + "${POPPLER_PREFIX}" \ + "${VCPKG_PREFIX}"; do + if [[ -f "${root}/lib/${base}" ]]; then + printf '%s\n' "${root}/lib/${base}" + return 0 + fi + local found + found="$(find -L "${root}" -type f -name "${base}" -print -quit 2>/dev/null || true)" + if [[ -n "${found}" ]]; then + printf '%s\n' "${found}" + return 0 + fi + done + return 1 +} + +bundle_dependency() { + local dependency="$1" + local base="${dependency##*/}" + local destination="${FRAMEWORKS}/${base}" + if [[ -e "${destination}" ]]; then + printf '%s\n' "${destination}" + return 0 + fi + local source + source="$(find_dependency_source "${dependency}" || true)" + [[ -n "${source}" ]] || return 1 + cp -Lf "${source}" "${destination}" + printf '%s\n' "${destination}" +} + +add_rpath() { + local binary="$1" + local rpath="$2" + if ! otool -l "${binary}" 2>/dev/null | + grep -Fq "path ${rpath} ("; then + install_name_tool -add_rpath "${rpath}" "${binary}" + fi +} + +remove_absolute_rpaths() { + local binary="$1" + local rpath + while IFS= read -r rpath; do + [[ "${rpath}" == /* ]] || continue + install_name_tool -delete_rpath "${rpath}" "${binary}" || true + done < <( + otool -l "${binary}" 2>/dev/null | + awk ' + /LC_RPATH/ { waiting = 1; next } + waiting && $1 == "path" { print $2; waiting = 0 } + ' + ) +} + +macho_file() { + file -b "$1" 2>/dev/null | grep -q 'Mach-O' +} + +dependency_lines() { + # otool -L prints the inspected file on line one. A dylib then has its own + # install name on line two, while an executable starts with its first real + # dependency on line two. Filter the identity by asking otool -D instead + # of dropping a fixed number of lines. + local self_id + self_id="$(otool -D "$1" 2>/dev/null | tail -n 1 || true)" + otool -L "$1" 2>/dev/null | tail -n +2 | + sed -E 's/^[[:space:]]+([^[:space:]]+)[[:space:]]+\(.*/\1/' | + awk -v self_id="${self_id}" '$0 != self_id' +} + +queue_contains() { + local candidate="$1" + local item + for item in "${MACHO_QUEUE[@]}"; do + [[ "${item}" == "${candidate}" ]] && return 0 + done + return 1 +} + +MACHO_QUEUE=( + "${APP}/Contents/MacOS/FileCommander" + "${HELPER}" + "${PRIVILEGED_HELPER}" +) +while IFS= read -r -d '' candidate; do + if macho_file "${candidate}" && ! queue_contains "${candidate}"; then + MACHO_QUEUE+=("${candidate}") + fi +done < <(find "${APP}" -type f -print0) + +index=0 +while ((index < ${#MACHO_QUEUE[@]})); do + binary="${MACHO_QUEUE[index]}" + index=$((index + 1)) + [[ -f "${binary}" ]] || continue + macho_file "${binary}" || continue + + remove_absolute_rpaths "${binary}" + case "${binary}" in + "${FRAMEWORKS}"/*) + add_rpath "${binary}" "@loader_path" + if [[ "$(dirname -- "${binary}")" == "${FRAMEWORKS}" ]]; then + install_name_tool -id "@rpath/$(basename -- "${binary}")" "${binary}" || true + fi + ;; + */Contents/Helpers/*) + add_rpath "${binary}" "@loader_path/../Frameworks" + ;; + */Contents/Library/LaunchServices/*) + add_rpath "${binary}" "@loader_path/../../Frameworks" + ;; + */Contents/PlugIns/*) + add_rpath "${binary}" "@loader_path/../../Frameworks" + ;; + *) + add_rpath "${binary}" "@loader_path/../Frameworks" + ;; + esac + + while IFS= read -r dependency; do + [[ -n "${dependency}" ]] || continue + base="${dependency##*/}" + case "${dependency}" in + /System/*|/usr/lib/*|/usr/libexec/*) + continue + ;; + @loader_path/*|@executable_path/*) + if [[ -e "${FRAMEWORKS}/${base}" ]]; then + destination="${FRAMEWORKS}/${base}" + else + destination="$(bundle_dependency "${dependency}" || true)" + if [[ -n "${destination}" ]]; then + install_name_tool -change "${dependency}" \ + "@rpath/${base}" "${binary}" + fi + fi + ;; + @rpath/*) + destination="${FRAMEWORKS}/${dependency#@rpath/}" + if [[ ! -e "${destination}" ]]; then + destination="$(bundle_dependency "${dependency}" || true)" + fi + ;; + *) + destination="$(bundle_dependency "${dependency}" || true)" + if [[ -n "${destination}" ]]; then + install_name_tool -change "${dependency}" \ + "@rpath/${base}" "${binary}" + fi + ;; + esac + if [[ -n "${destination:-}" && -f "${destination}" ]] && + macho_file "${destination}" && + ! queue_contains "${destination}"; then + MACHO_QUEUE+=("${destination}") + fi + destination="" + done < <(dependency_lines "${binary}") +done + +if [[ "${FILECOMMANDER_ADHOC_SIGN:-1}" == "1" ]]; then + codesign --force --deep --sign - "${APP}" + codesign --verify --deep --strict "${APP}" +fi + +verify_x86_64() { + local path="$1" + local info + info="$(file -b "${path}")" + [[ "${info}" == *"x86_64"* ]] || + die "expected x86_64 binary, got ${path}: ${info}" + [[ "${info}" != *"arm64"* ]] || + die "unexpected arm64 slice in ${path}: ${info}" +} + +verify_macho_dependencies() { + local binary="$1" + local rpath + while IFS= read -r dependency; do + case "${dependency}" in + /usr/local/opt/*|/usr/local/Cellar/*|/opt/homebrew/*|\ + "${MPV_PREFIX}"/*|"${SAMBA_PREFIX}"/*|"${VCPKG_PREFIX}"/*|\ + "${POPPLER_PREFIX}"/*) + die "absolute third-party dependency remains in ${binary}: ${dependency}" + ;; + esac + done < <(dependency_lines "${binary}") + while IFS= read -r rpath; do + case "${rpath}" in + /System/*|/usr/lib/*|/usr/libexec/*) + ;; + /*) + die "absolute third-party rpath remains in ${binary}: ${rpath}" + ;; + esac + done < <( + otool -l "${binary}" 2>/dev/null | + awk ' + /LC_RPATH/ { waiting = 1; next } + waiting && $1 == "path" { print $2; waiting = 0 } + ' + ) +} + +verify_x86_64 "${APP}/Contents/MacOS/FileCommander" +verify_x86_64 "${HELPER}" +verify_x86_64 "${PRIVILEGED_HELPER}" +verify_x86_64 "${APP}/Contents/MacOS/office-oxide" + +while IFS= read -r -d '' binary; do + if macho_file "${binary}"; then + verify_x86_64 "${binary}" + verify_macho_dependencies "${binary}" + fi +done < <(find "${APP}" -type f -print0) + +printf 'Intel macOS app: %s\n' "${APP}" diff --git a/packaging/macos/merge-universal-app.py b/packaging/macos/merge-universal-app.py new file mode 100755 index 00000000..0dcad254 --- /dev/null +++ b/packaging/macos/merge-universal-app.py @@ -0,0 +1,153 @@ +#!/usr/bin/env python3 +"""Merge two macOS app bundles into one Universal2 bundle.""" + +from __future__ import annotations + +import argparse +import filecmp +import os +from pathlib import Path +import shutil +import subprocess +import sys + + +MACH_O_MAGICS = { + b"\xfe\xed\xfa\xce", + b"\xce\xfa\xed\xfe", + b"\xfe\xed\xfa\xcf", + b"\xcf\xfa\xed\xfe", + b"\xca\xfe\xba\xbe", + b"\xbe\xba\xfe\xca", +} + + +def is_macho(path: Path) -> bool: + try: + with path.open("rb") as handle: + return handle.read(4) in MACH_O_MAGICS + except (OSError, IsADirectoryError): + return False + + +def run_lipo(x86_path: Path, arm64_path: Path, output_path: Path) -> None: + output_path.parent.mkdir(parents=True, exist_ok=True) + temporary_path = output_path.with_name(output_path.name + ".universal2.tmp") + if temporary_path.exists() or temporary_path.is_symlink(): + temporary_path.unlink() + subprocess.run( + [ + "/usr/bin/lipo", + "-create", + str(x86_path), + str(arm64_path), + "-output", + str(temporary_path), + ], + check=True, + ) + os.replace(temporary_path, output_path) + shutil.copymode(x86_path, output_path) + + +def relative_files(root: Path) -> set[Path]: + return { + path.relative_to(root) + for path in root.rglob("*") + if not path.is_dir() + } + + +def copy_entry(source: Path, destination: Path) -> None: + destination.parent.mkdir(parents=True, exist_ok=True) + if source.is_symlink(): + destination.symlink_to(os.readlink(source)) + else: + shutil.copy2(source, destination) + + +def merge_bundle(x86_app: Path, arm64_app: Path, output_app: Path) -> None: + if not x86_app.is_dir() or not arm64_app.is_dir(): + raise SystemExit("both architecture inputs must be existing .app directories") + if output_app.exists() or output_app.is_symlink(): + shutil.rmtree(output_app) + + shutil.copytree(x86_app, output_app, symlinks=True) + x86_files = relative_files(x86_app) + arm64_files = relative_files(arm64_app) + + for relative_path in sorted(arm64_files - x86_files): + copy_entry(arm64_app / relative_path, output_app / relative_path) + + for relative_path in sorted(x86_files & arm64_files): + x86_path = x86_app / relative_path + arm64_path = arm64_app / relative_path + output_path = output_app / relative_path + + if x86_path.is_symlink() or arm64_path.is_symlink(): + if x86_path.is_symlink() and arm64_path.is_symlink(): + if os.readlink(x86_path) != os.readlink(arm64_path): + raise SystemExit( + f"architecture bundles disagree on symlink: {relative_path}" + ) + continue + raise SystemExit(f"architecture bundles disagree on file type: {relative_path}") + + if is_macho(x86_path) or is_macho(arm64_path): + if not is_macho(x86_path) or not is_macho(arm64_path): + raise SystemExit( + f"only one architecture contains a Mach-O file: {relative_path}" + ) + run_lipo(x86_path, arm64_path, output_path) + elif not filecmp.cmp(x86_path, arm64_path, shallow=False): + raise SystemExit( + f"architecture bundles disagree on non-Mach-O file: {relative_path}" + ) + + +def verify_bundle(app: Path) -> None: + failures: list[str] = [] + for path in sorted(relative_files(app)): + absolute_path = app / path + if not is_macho(absolute_path): + continue + result = subprocess.run( + ["/usr/bin/lipo", "-info", str(absolute_path)], + check=False, + capture_output=True, + text=True, + ) + output = f"{result.stdout}\n{result.stderr}" + if result.returncode != 0 or "x86_64" not in output or "arm64" not in output: + failures.append(str(path)) + if failures: + raise SystemExit( + "Universal2 verification failed for:\n " + "\n ".join(failures) + ) + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--x86-app", type=Path) + parser.add_argument("--arm64-app", type=Path) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--verify-only", action="store_true") + args = parser.parse_args() + + if args.verify_only: + verify_bundle(args.output) + else: + if args.x86_app is None or args.arm64_app is None: + parser.error("--x86-app and --arm64-app are required unless --verify-only is used") + merge_bundle(args.x86_app, args.arm64_app, args.output) + verify_bundle(args.output) + return 0 + + +if __name__ == "__main__": + try: + raise SystemExit(main()) + except subprocess.CalledProcessError as error: + command = " ".join(error.cmd) + print(f"error: command failed ({error.returncode}): {command}", file=sys.stderr) + raise diff --git a/packaging/macos/vcpkg-patches/qt5-base-configure-cross.patch b/packaging/macos/vcpkg-patches/qt5-base-configure-cross.patch new file mode 100644 index 00000000..479132e2 --- /dev/null +++ b/packaging/macos/vcpkg-patches/qt5-base-configure-cross.patch @@ -0,0 +1,43 @@ +--- a/ports/qt5-base/cmake/configure_qt.cmake ++++ b/ports/qt5-base/cmake/configure_qt.cmake +@@ -147,6 +147,11 @@ + + # These paths get hardcoded into qmake. So point them into the CURRENT_INSTALLED_DIR instead of CURRENT_PACKAGES_DIR + # makefiles will be fixed to install into CURRENT_PACKAGES_DIR in install_qt ++ set(QT_TARGET_PLATFORM_OPTION -platform) ++ if(DEFINED _csc_HOST_PLATFORM) ++ set(QT_TARGET_PLATFORM_OPTION -xplatform) ++ endif() ++ + set(BUILD_OPTIONS ${_csc_OPTIONS} ${_csc_OPTIONS_${_buildname}} + -prefix ${CURRENT_INSTALLED_DIR} + #-extprefix ${CURRENT_INSTALLED_DIR} +@@ -170,7 +175,11 @@ + -I ${CURRENT_INSTALLED_DIR}/include/qt5 + -L ${CURRENT_INSTALLED_DIR}${_path_suffix_${_buildname}}/lib + -L ${CURRENT_INSTALLED_DIR}${_path_suffix_${_buildname}}/lib/manual-link +- -platform ${_csc_TARGET_PLATFORM} ++ # When a prepared host toolchain is supplied, Qt must receive ++ # the target mkspec as -xplatform. Passing it as a second ++ # -platform makes the target qmake build host tools with the ++ # target architecture. ++ ${QT_TARGET_PLATFORM_OPTION} ${_csc_TARGET_PLATFORM} + ) + + if(DEFINED _csc_HOST_TOOLS_ROOT) #use qmake +@@ -182,6 +191,15 @@ + WORKING_DIRECTORY ${_build_dir} + LOGNAME config-${_build_triplet} + ) ++ if(EXISTS "${_build_dir}/mkspecs/qmodule.pri") ++ file(COPY ++ "${_build_dir}/mkspecs/qmodule.pri" ++ DESTINATION "${_csc_HOST_TOOLS_ROOT}/mkspecs" ++ ) ++ else() ++ message(FATAL_ERROR ++ "Qt target qmodule.pri was not generated in ${_build_dir}/mkspecs") ++ endif() + else()# call configure (builds qmake for triplet and calls it like above) + vcpkg_execute_required_process( + COMMAND "${INVOKE}" ${BUILD_OPTIONS} ${qmake_build_tools} ${qmake_comp_flags} diff --git a/packaging/macos/vcpkg-patches/qt5-base-external-qmake.patch b/packaging/macos/vcpkg-patches/qt5-base-external-qmake.patch new file mode 100644 index 00000000..b966e60e --- /dev/null +++ b/packaging/macos/vcpkg-patches/qt5-base-external-qmake.patch @@ -0,0 +1,16 @@ +diff --git a/qmake/qmake-aux.pro b/qmake/qmake-aux.pro +--- a/qmake/qmake-aux.pro ++++ b/qmake/qmake-aux.pro +@@ -9,7 +9,11 @@ + + !build_pass { + qmake_exe.target = $$OUT_PWD/qmake$$EXTENSION +- qmake_exe.commands = $(MAKE) binary ++ !isEmpty(HOST_QT_TOOLS) { ++ qmake_exe.commands = $$QMAKE_COPY_FILE $$shell_path($$HOST_QT_TOOLS/qmake$$EXTENSION) $$shell_path($$OUT_PWD/qmake$$EXTENSION) ++ } else { ++ qmake_exe.commands = $(MAKE) binary ++ } + qmake_exe.CONFIG = phony + QMAKE_EXTRA_TARGETS += qmake_exe + diff --git a/packaging/macos/vcpkg-patches/qt5-base-host-prefix.patch b/packaging/macos/vcpkg-patches/qt5-base-host-prefix.patch new file mode 100644 index 00000000..0a1e768b --- /dev/null +++ b/packaging/macos/vcpkg-patches/qt5-base-host-prefix.patch @@ -0,0 +1,20 @@ +diff --git a/ports/qt5-base/cmake/configure_qt.cmake b/ports/qt5-base/cmake/configure_qt.cmake +index 7951086bb..1856f79d6 100644 +--- a/ports/qt5-base/cmake/configure_qt.cmake ++++ b/ports/qt5-base/cmake/configure_qt.cmake +@@ -199,6 +199,15 @@ function(configure_qt) + file(READ "${CURRENT_BUILDTREES_DIR}/${_build_triplet}/bin/qt.conf" _contents) + string(REPLACE "${CMAKE_CURRENT_PACKAGES_DIR_PATH}" "\${CURRENT_INSTALLED_DIR}" _contents ${_contents}) + string(REPLACE "${CMAKE_CURRENT_INSTALLED_DIR_PATH}" "\${CURRENT_INSTALLED_DIR}" _contents ${_contents}) ++ if(DEFINED _csc_HOST_TOOLS_ROOT) ++ file(TO_CMAKE_PATH "${_csc_HOST_TOOLS_ROOT}" _host_tools_root_path) ++ string(REGEX REPLACE ++ "HostPrefix=[^\r\n]+" ++ "HostPrefix=${_host_tools_root_path}" ++ _contents ++ "${_contents}" ++ ) ++ endif() + #string(REPLACE "HostPrefix=\${CURRENT_PACKAGES_DIR}" "HostPrefix=\${CURRENT_INSTALLED_DIR}" _contents ${_contents}) + string(REPLACE "[EffectivePaths]\nPrefix=..\n" "" _contents ${_contents}) + string(REGEX REPLACE "\\[EffectiveSourcePaths\\]\r?\nPrefix=[^\r\n]+\r?\n" "" _contents ${_contents}) diff --git a/packaging/macos/vcpkg-patches/qt5-base-install-cross.patch b/packaging/macos/vcpkg-patches/qt5-base-install-cross.patch new file mode 100644 index 00000000..ef2292da --- /dev/null +++ b/packaging/macos/vcpkg-patches/qt5-base-install-cross.patch @@ -0,0 +1,56 @@ +diff --git a/ports/qt5-base/cmake/install_qt.cmake b/ports/qt5-base/cmake/install_qt.cmake +index 86202ab56..483d65354 100644 +--- a/ports/qt5-base/cmake/install_qt.cmake ++++ b/ports/qt5-base/cmake/install_qt.cmake +@@ -83,21 +83,45 @@ function(install_qt) + endif() + + message(STATUS "Building ${_build_triplet}") ++ if(DEFINED ENV{QMAKEMODULES}) ++ set(_qmake_modules_was_defined TRUE) ++ set(_qmake_modules_backup "$ENV{QMAKEMODULES}") ++ else() ++ set(_qmake_modules_was_defined FALSE) ++ endif() ++ # Qt generates target module metadata while individual modules build. ++ # Make every nested qmake invocation see the target directory. ++ set(ENV{QMAKEMODULES} "${CURRENT_BUILDTREES_DIR}/${_build_triplet}/mkspecs/modules") + vcpkg_execute_build_process( + COMMAND ${INVOKE} + NO_PARALLEL_COMMAND ${INVOKE_SINGLE} + WORKING_DIRECTORY ${CURRENT_BUILDTREES_DIR}/${_build_triplet} + LOGNAME build-${_build_triplet} + ) ++ if(_qmake_modules_was_defined) ++ set(ENV{QMAKEMODULES} "${_qmake_modules_backup}") ++ else() ++ unset(ENV{QMAKEMODULES}) ++ endif() + + if(VCPKG_TARGET_IS_OSX) + # For some reason there will be an error on MacOSX without this clean! +- message(STATUS "Cleaning after build before install ${_build_triplet}") +- vcpkg_execute_required_process( +- COMMAND ${INVOKE_SINGLE} clean +- WORKING_DIRECTORY ${CURRENT_BUILDTREES_DIR}/${_build_triplet}/qmake +- LOGNAME cleaning-after-build-${_build_triplet} +- ) ++ set(_qmake_build_dir "${CURRENT_BUILDTREES_DIR}/${_build_triplet}/qmake") ++ if(EXISTS "${_qmake_build_dir}/Makefile") ++ set(_qmake_makefile "Makefile") ++ elseif(EXISTS "${_qmake_build_dir}/Makefile.qmake-aux") ++ set(_qmake_makefile "Makefile.qmake-aux") ++ else() ++ set(_qmake_makefile "") ++ endif() ++ if(NOT _qmake_makefile STREQUAL "") ++ message(STATUS "Cleaning after build before install ${_build_triplet}") ++ vcpkg_execute_required_process( ++ COMMAND ${INVOKE_SINGLE} -f ${_qmake_makefile} clean ++ WORKING_DIRECTORY ${_qmake_build_dir} ++ LOGNAME cleaning-after-build-${_build_triplet} ++ ) ++ endif() + endif() + + message(STATUS "Fixing makefile installation path ${_build_triplet}") diff --git a/packaging/macos/vcpkg-patches/qt5-base-port-cross.patch b/packaging/macos/vcpkg-patches/qt5-base-port-cross.patch new file mode 100644 index 00000000..ad1e27d2 --- /dev/null +++ b/packaging/macos/vcpkg-patches/qt5-base-port-cross.patch @@ -0,0 +1,23 @@ +diff --git a/ports/qt5-base/portfile.cmake b/ports/qt5-base/portfile.cmake +index 55117abcb..97995daa5 100644 +--- a/ports/qt5-base/portfile.cmake ++++ b/ports/qt5-base/portfile.cmake +@@ -69,6 +69,9 @@ set(PATCHES + patches/mingw9.patch # Fix compile with MinGW-W64 9.0.0: Redefinition of 'struct _FILE_ID_INFO' + patches/qmake-arm64.patch # Fix by Oliver Wolff to support ARM64 hosts on Windows + ) ++if(VCPKG_TARGET_ARCHITECTURE STREQUAL "arm64" AND DEFINED ENV{FILECOMMANDER_QMAKE_AUX_PATCH}) ++ list(APPEND PATCHES "$ENV{FILECOMMANDER_QMAKE_AUX_PATCH}") ++endif() + if(VCPKG_TARGET_IS_OSX) + execute_process(COMMAND xcrun --sdk macosx --show-sdk-version + OUTPUT_VARIABLE OSX_SDK_VERSION +@@ -82,7 +85,7 @@ endif() + qt_download_submodule(OUT_SOURCE_PATH SOURCE_PATH PATCHES ${PATCHES}) + + # Remove vendored dependencies to ensure they are not picked up by the build +-foreach(DEPENDENCY IN ITEMS double-conversion freetype harfbuzz-ng libjpeg libpng md4c pcre2 sqlite zlib) ++foreach(DEPENDENCY IN ITEMS double-conversion freetype harfbuzz-ng libjpeg libpng md4c pcre2 sqlite) + file(REMOVE_RECURSE "${SOURCE_PATH}/src/3rdparty/${DEPENDENCY}") + endforeach() + diff --git a/packaging/macos/vcpkg-patches/qt5-base-submodule-cross.patch b/packaging/macos/vcpkg-patches/qt5-base-submodule-cross.patch new file mode 100644 index 00000000..bb2fc11d --- /dev/null +++ b/packaging/macos/vcpkg-patches/qt5-base-submodule-cross.patch @@ -0,0 +1,50 @@ +diff --git a/ports/qt5-base/cmake/qt_build_submodule.cmake b/ports/qt5-base/cmake/qt_build_submodule.cmake +index 6c59090f4..79a5fd6b8 100644 +--- a/ports/qt5-base/cmake/qt_build_submodule.cmake ++++ b/ports/qt5-base/cmake/qt_build_submodule.cmake +@@ -10,6 +10,24 @@ function(qt_build_submodule SOURCE_PATH) + + vcpkg_build_qmake(SKIP_MAKEFILES) + ++ # Cross builds must make host tools available before target modules run ++ # their build-time generators. ++ if(DEFINED ENV{FILECOMMANDER_QT_HOST_TOOLS_ROOT} AND ++ PORT STREQUAL "qt5-declarative") ++ set(_qt_submodule_build_dir ++ "${CURRENT_BUILDTREES_DIR}/${TARGET_TRIPLET}-rel") ++ set(_qt_host_tool_dir ++ "${_qt_submodule_build_dir}/src/qmltyperegistrar") ++ if(EXISTS "${_qt_host_tool_dir}/Makefile") ++ find_program(_qt_make_program NAMES make REQUIRED) ++ vcpkg_execute_build_process( ++ COMMAND "${_qt_make_program}" -C "${_qt_host_tool_dir}" install ++ WORKING_DIRECTORY "${_qt_submodule_build_dir}" ++ LOGNAME "host-tools-${TARGET_TRIPLET}-rel" ++ ) ++ endif() ++ endif() ++ + #Fix the installation location within the makefiles + qt_fix_makefile_install("${CURRENT_BUILDTREES_DIR}/${TARGET_TRIPLET}-dbg/") + qt_fix_makefile_install("${CURRENT_BUILDTREES_DIR}/${TARGET_TRIPLET}-rel/") +@@ -136,8 +154,16 @@ function(qt_build_submodule SOURCE_PATH) + endif() + + # Remove duplicate flags from qmodule.pri issue -> https://github.com/microsoft/vcpkg/issues/28835 +- file(READ "${CURRENT_INSTALLED_DIR}/tools/qt5/mkspecs/qmodule.pri" QMODULE_PRI_CONTENT) +- string(REGEX REPLACE "QMAKE_CXXFLAGS_RELEASE\\+=[^\n]*\n" "QMAKE_CXXFLAGS_RELEASE=\n" QMODULE_PRI_CONTENT ${QMODULE_PRI_CONTENT}) +- file(WRITE "${CURRENT_INSTALLED_DIR}/tools/qt5/mkspecs/qmodule.pri" "${QMODULE_PRI_CONTENT}") ++ # Cross builds keep this file with the external host tools because the ++ # target Qt installation does not contain host mkspecs. ++ set(_qt_qmodule_pri "${CURRENT_INSTALLED_DIR}/tools/qt5/mkspecs/qmodule.pri") ++ if(NOT EXISTS "${_qt_qmodule_pri}" AND DEFINED ENV{FILECOMMANDER_QT_HOST_TOOLS_ROOT}) ++ set(_qt_qmodule_pri "$ENV{FILECOMMANDER_QT_HOST_TOOLS_ROOT}/mkspecs/qmodule.pri") ++ endif() ++ if(EXISTS "${_qt_qmodule_pri}") ++ file(READ "${_qt_qmodule_pri}" QMODULE_PRI_CONTENT) ++ string(REGEX REPLACE "QMAKE_CXXFLAGS_RELEASE\\+=[^\n]*\n" "QMAKE_CXXFLAGS_RELEASE=\n" QMODULE_PRI_CONTENT ${QMODULE_PRI_CONTENT}) ++ file(WRITE "${_qt_qmodule_pri}" "${QMODULE_PRI_CONTENT}") ++ endif() + + endfunction() +\ No newline at end of file diff --git a/packaging/macos/vcpkg-patches/vcpkg-configure-qmake-cross.patch b/packaging/macos/vcpkg-patches/vcpkg-configure-qmake-cross.patch new file mode 100644 index 00000000..34949dcc --- /dev/null +++ b/packaging/macos/vcpkg-patches/vcpkg-configure-qmake-cross.patch @@ -0,0 +1,40 @@ +diff --git a/scripts/cmake/vcpkg_configure_qmake.cmake b/scripts/cmake/vcpkg_configure_qmake.cmake +index 9340fefb6..9a3fd21c0 100644 +--- a/scripts/cmake/vcpkg_configure_qmake.cmake ++++ b/scripts/cmake/vcpkg_configure_qmake.cmake +@@ -6,8 +6,18 @@ function(vcpkg_configure_qmake) + "OPTIONS;OPTIONS_RELEASE;OPTIONS_DEBUG;BUILD_OPTIONS;BUILD_OPTIONS_RELEASE;BUILD_OPTIONS_DEBUG" + ) + +- # Find qmake executable +- find_program(qmake_executable NAMES qmake PATHS "${CURRENT_HOST_INSTALLED_DIR}/tools/qt5/bin" NO_DEFAULT_PATH) ++ # Find qmake executable. Cross builds may provide a host qmake outside ++ # the vcpkg host triplet, for example a prepared Qt toolchain on macOS. ++ if(DEFINED ENV{FILECOMMANDER_QT_HOST_TOOLS_ROOT}) ++ find_program( ++ qmake_executable ++ NAMES qmake ++ PATHS "$ENV{FILECOMMANDER_QT_HOST_TOOLS_ROOT}/bin" ++ NO_DEFAULT_PATH ++ ) ++ else() ++ find_program(qmake_executable NAMES qmake PATHS "${CURRENT_HOST_INSTALLED_DIR}/tools/qt5/bin" NO_DEFAULT_PATH) ++ endif() + + if(NOT qmake_executable) + message(FATAL_ERROR "vcpkg_configure_qmake: unable to find qmake.") +@@ -54,6 +64,14 @@ function(vcpkg_configure_qmake) + set(qmake_comp_flags "") + macro(qmake_add_flags qmake_var operation flags) + string(STRIP "${flags}" striped_flags) ++ if(VCPKG_TARGET_IS_OSX AND VCPKG_TARGET_ARCHITECTURE STREQUAL "arm64" AND ++ "${qmake_var}" MATCHES "^QMAKE_LFLAGS") ++ # QMAKE_LFLAGS is global and leaks into Qt host_build subprojects ++ # such as qmltyperegistrar. The target qmodule.pri supplies the ++ # arm64 linker flag only for target builds. ++ string(REGEX REPLACE "-arch[ \t]+arm64" "" striped_flags "${striped_flags}") ++ string(STRIP "${striped_flags}" striped_flags) ++ endif() + if(striped_flags) + vcpkg_list(APPEND qmake_comp_flags "${qmake_var}${operation}${striped_flags}") + endif() diff --git a/packaging/macos/vcpkg-triplets/filecommander-arm64-osx-release.cmake b/packaging/macos/vcpkg-triplets/filecommander-arm64-osx-release.cmake new file mode 100644 index 00000000..cea9bf2a --- /dev/null +++ b/packaging/macos/vcpkg-triplets/filecommander-arm64-osx-release.cmake @@ -0,0 +1,24 @@ +# FileCommander release dependencies for an arm64 macOS build. +# +# vcpkg performs the target build with Apple's cross compiler, so this triplet +# can be used on an Intel Mac. Host tools are supplied separately through the +# x64 FileCommander triplet. +set(VCPKG_TARGET_ARCHITECTURE arm64) +set(VCPKG_CRT_LINKAGE dynamic) +set(VCPKG_LIBRARY_LINKAGE dynamic) +set(VCPKG_BUILD_TYPE release) + +set(VCPKG_CMAKE_SYSTEM_NAME Darwin) +set(VCPKG_OSX_ARCHITECTURES arm64) +set(VCPKG_OSX_DEPLOYMENT_TARGET 12.0) +set(VCPKG_CMAKE_CONFIGURE_OPTIONS + "-DCMAKE_OSX_DEPLOYMENT_TARGET=12.0" +) + +# Qt's cross build must run qmake/moc/rcc/uic on the host while emitting +# libraries for arm64. The host triplet is supplied to vcpkg at install time; +# this tells the Qt 5 port where to find its x86_64 host tools. +set(VCPKG_QT_HOST_PLATFORM x64-osx) +set(VCPKG_QT_HOST_MKSPEC macx-clang) +set(VCPKG_QT_HOST_TOOLS_ROOT + "$ENV{FILECOMMANDER_QT_HOST_TOOLS_ROOT}") diff --git a/packaging/macos/vcpkg-triplets/filecommander-x64-osx-release.cmake b/packaging/macos/vcpkg-triplets/filecommander-x64-osx-release.cmake new file mode 100644 index 00000000..fceb08d2 --- /dev/null +++ b/packaging/macos/vcpkg-triplets/filecommander-x64-osx-release.cmake @@ -0,0 +1,15 @@ +# FileCommander release dependencies for an Intel macOS build. +# +# This triplet is intentionally kept in the repository so the arm64 and +# x86_64 dependency builds use the same linkage and deployment settings. +set(VCPKG_TARGET_ARCHITECTURE x64) +set(VCPKG_CRT_LINKAGE dynamic) +set(VCPKG_LIBRARY_LINKAGE dynamic) +set(VCPKG_BUILD_TYPE release) + +set(VCPKG_CMAKE_SYSTEM_NAME Darwin) +set(VCPKG_OSX_ARCHITECTURES x86_64) +set(VCPKG_OSX_DEPLOYMENT_TARGET 12.0) +set(VCPKG_CMAKE_CONFIGURE_OPTIONS + "-DCMAKE_OSX_DEPLOYMENT_TARGET=12.0" +) diff --git a/resources/macos/FileCommander.icns b/resources/macos/FileCommander.icns new file mode 100644 index 00000000..d7b4a152 Binary files /dev/null and b/resources/macos/FileCommander.icns differ diff --git a/scripts/build-office-oxide.sh b/scripts/build-office-oxide.sh index 19611412..3e1ae8b3 100644 --- a/scripts/build-office-oxide.sh +++ b/scripts/build-office-oxide.sh @@ -7,10 +7,26 @@ commit="$(sed -n 's/^commit=//p' "$pin_file")" package="$(sed -n 's/^package=//p' "$pin_file")" output="${1:-$repo_root/build/office-oxide}" source_dir="$output/source" +cargo_home="${FILECOMMANDER_CARGO_HOME:-$output/cargo-home}" +cargo_workdir="${FILECOMMANDER_CARGO_WORKDIR:-/tmp}" if [[ ! -d "$source_dir/.git" ]]; then git clone "$url" "$source_dir"; fi git -C "$source_dir" fetch origin "$commit" --depth 1 git -C "$source_dir" checkout --detach "$commit" test "$(git -C "$source_dir" rev-parse HEAD)" = "$commit" -cargo build --manifest-path "$source_dir/Cargo.toml" --release -p "$package" +mkdir -p "$cargo_home" +if [[ -z "${FILECOMMANDER_CARGO_HOME:-}" || ! -f "$cargo_home/config.toml" ]]; then + cat > "$cargo_home/config.toml" <<'EOF' +# Keep the pinned macOS helper build independent of a user's global Cargo +# source replacement. The default crates.io endpoint is the portable fallback +# when a machine-local mirror is stale or unavailable. +[registries.crates-io] +protocol = "sparse" +EOF +fi +(cd "$cargo_workdir" && + CARGO_HOME="$cargo_home" cargo build \ + --manifest-path "$source_dir/Cargo.toml" \ + --release \ + -p "$package") mkdir -p "$output" cp "$source_dir/target/release/office-oxide" "$output/office-oxide" diff --git a/src/core/CMakeLists.txt b/src/core/CMakeLists.txt index 641b7bf6..6c66e539 100644 --- a/src/core/CMakeLists.txt +++ b/src/core/CMakeLists.txt @@ -97,14 +97,20 @@ if(FILECOMMANDER_ENABLE_LINUX_INTEGRATION) list(APPEND CORE_SOURCES network/GvfsMounter.h network/GvfsMounter.cpp + devices/RemovableDeviceMonitor.h + devices/RemovableDeviceMonitor.cpp + ) +endif() + +if(FILECOMMANDER_ENABLE_NETWORK AND + (FILECOMMANDER_ENABLE_LINUX_INTEGRATION OR APPLE)) + list(APPEND CORE_SOURCES network/SmbClientGate.h network/SmbProvider.h network/SmbProvider.cpp network/SmbHelperProtocol.h network/SmbHelperClient.h network/SmbHelperClient.cpp - devices/RemovableDeviceMonitor.h - devices/RemovableDeviceMonitor.cpp ) endif() @@ -153,6 +159,12 @@ if(WIN32) endif() elseif(CMAKE_SYSTEM_NAME STREQUAL "Linux") list(APPEND CORE_SOURCES filesystem/DirectoryChangeMonitor_linux.cpp) +elseif(APPLE) + list(APPEND CORE_SOURCES + filesystem/DirectoryChangeMonitor_macos.cpp + devices/RemovableDeviceMonitor.h + devices/RemovableDeviceMonitor_macos.mm + ) else() list(APPEND CORE_SOURCES filesystem/DirectoryChangeMonitor_stub.cpp) endif() @@ -160,7 +172,7 @@ endif() add_library(core STATIC ${CORE_SOURCES}) if(FILECOMMANDER_ENABLE_NETWORK) - if(WIN32) + if(WIN32 OR FILECOMMANDER_USE_VCPKG) find_package(libssh2 CONFIG REQUIRED) find_package(CURL CONFIG REQUIRED) else() @@ -177,7 +189,8 @@ if(FILECOMMANDER_ENABLE_NETWORK) find_package(OpenSSL REQUIRED) endif() -if(FILECOMMANDER_ENABLE_LINUX_INTEGRATION) +if(FILECOMMANDER_ENABLE_NETWORK AND + (FILECOMMANDER_ENABLE_LINUX_INTEGRATION OR APPLE)) find_package(PkgConfig REQUIRED) pkg_check_modules(SMBCLIENT REQUIRED IMPORTED_TARGET smbclient) endif() @@ -211,20 +224,38 @@ if(WIN32) target_link_libraries(core PUBLIC Advapi32 Shell32) endif() +if(APPLE) + target_link_libraries(core PUBLIC + "-framework DiskArbitration" + "-framework Foundation" + "-framework IOKit" + ) +endif() + if(FILECOMMANDER_ENABLE_NETWORK) target_link_libraries(core PUBLIC Qt5::WebSockets) # Crypto only: the TLS itself is Qt's and curl's, we just make the key. target_link_libraries(core PUBLIC OpenSSL::Crypto) if(WIN32) - target_link_libraries(core PUBLIC libssh2::libssh2 CURL::libcurl ws2_32 Mpr Netapi32) + target_link_libraries(core PUBLIC + libssh2::libssh2 + CURL::libcurl + ws2_32 + Mpr + Netapi32 + ) + elseif(FILECOMMANDER_USE_VCPKG) + target_link_libraries(core PUBLIC libssh2::libssh2 CURL::libcurl) else() target_link_libraries(core PUBLIC PkgConfig::LIBSSH2 PkgConfig::CURL) endif() endif() if(FILECOMMANDER_ENABLE_LINUX_INTEGRATION) - target_link_libraries(core PUBLIC - Qt5::DBus - PkgConfig::SMBCLIENT - ) + target_link_libraries(core PUBLIC Qt5::DBus) +endif() + +if(FILECOMMANDER_ENABLE_NETWORK AND + (FILECOMMANDER_ENABLE_LINUX_INTEGRATION OR APPLE)) + target_link_libraries(core PUBLIC PkgConfig::SMBCLIENT) endif() diff --git a/src/core/devices/RemovableDeviceMonitor.cpp b/src/core/devices/RemovableDeviceMonitor.cpp index 81ac0e87..0c6abcf8 100644 --- a/src/core/devices/RemovableDeviceMonitor.cpp +++ b/src/core/devices/RemovableDeviceMonitor.cpp @@ -166,6 +166,8 @@ RemovableDeviceMonitor::RemovableDeviceMonitor(QObject *parent) : QObject(parent m_devices = enumerate(); } +RemovableDeviceMonitor::~RemovableDeviceMonitor() = default; + QVector RemovableDeviceMonitor::devices() const { return m_devices; } diff --git a/src/core/devices/RemovableDeviceMonitor.h b/src/core/devices/RemovableDeviceMonitor.h index fd1df31f..3ae6d8e5 100644 --- a/src/core/devices/RemovableDeviceMonitor.h +++ b/src/core/devices/RemovableDeviceMonitor.h @@ -39,6 +39,7 @@ class RemovableDeviceMonitor : public QObject { Q_OBJECT public: explicit RemovableDeviceMonitor(QObject *parent = nullptr); + ~RemovableDeviceMonitor() override; // Current snapshot of removable devices. QVector devices() const; @@ -75,4 +76,5 @@ private slots: QVector m_devices; QTimer *m_refreshDebounce = nullptr; // coalesces D-Bus signal bursts + void *m_nativeState = nullptr; // macOS workspace observer state }; diff --git a/src/core/devices/RemovableDeviceMonitor_macos.mm b/src/core/devices/RemovableDeviceMonitor_macos.mm new file mode 100644 index 00000000..0b45647a --- /dev/null +++ b/src/core/devices/RemovableDeviceMonitor_macos.mm @@ -0,0 +1,395 @@ +#include "RemovableDeviceMonitor.h" + +#import +#import + +#include + +#include +#include +#include +#include + +#include + +namespace { + +struct MacDeviceState { + NSNotificationCenter *notificationCenter = nil; + id mountObserver = nil; + id unmountObserver = nil; + id renameObserver = nil; +}; + +QString fromCFString(CFStringRef value) { + if (!value) + return {}; + char buffer[PATH_MAX] = {}; + if (CFStringGetCString(value, buffer, sizeof(buffer), kCFStringEncodingUTF8)) + return QString::fromUtf8(buffer); + return {}; +} + +bool dictionaryBool(CFDictionaryRef dictionary, const void *key) { + const auto value = + static_cast(CFDictionaryGetValue(dictionary, key)); + return value && CFGetTypeID(value) == CFBooleanGetTypeID() && + CFBooleanGetValue(value); +} + +CFTypeRef dictionaryValue(CFDictionaryRef dictionary, const void *key) { + return dictionary ? CFDictionaryGetValue(dictionary, key) : nullptr; +} + +QString diskError(DADissenterRef dissenter, const QString &fallback) { + if (dissenter) { + if (CFStringRef text = DADissenterGetStatusString(dissenter)) { + const QString message = fromCFString(text); + if (!message.isEmpty()) + return message; + } + return QStringLiteral("Disk Arbitration rejected the operation."); + } + return fallback; +} + +QString normalizedBSDName(const QString &id) { + QString name = id.trimmed(); + if (name.startsWith(QStringLiteral("/dev/"))) + name.remove(0, 5); + return name; +} + +struct DiskOperation { + dispatch_semaphore_t finished = nullptr; + QString mountPoint; + QString error; + bool success = false; +}; + +void mountCallback(DADiskRef disk, DADissenterRef dissenter, void *context) { + auto *operation = static_cast(context); + if (!dissenter && disk) { + CFDictionaryRef description = DADiskCopyDescription(disk); + if (description) { + if (auto path = static_cast( + dictionaryValue(description, kDADiskDescriptionVolumePathKey))) { + char buffer[PATH_MAX] = {}; + if (CFURLGetFileSystemRepresentation(path, true, reinterpret_cast(buffer), + sizeof(buffer))) + operation->mountPoint = QString::fromUtf8(buffer); + } + CFRelease(description); + } + operation->success = !operation->mountPoint.isEmpty(); + } else { + operation->error = diskError(dissenter, QStringLiteral("Could not mount the volume.")); + } + dispatch_semaphore_signal(operation->finished); +} + +void ejectCallback(DADiskRef, DADissenterRef dissenter, void *context) { + auto *operation = static_cast(context); + operation->success = dissenter == nullptr; + if (dissenter) + operation->error = diskError(dissenter, QStringLiteral("Could not eject the volume.")); + dispatch_semaphore_signal(operation->finished); +} + +bool isExternalVolume(CFDictionaryRef description) { + if (!description) + return false; + if (dictionaryBool(description, kDADiskDescriptionVolumeNetworkKey)) + return false; + + const bool removable = + dictionaryBool(description, kDADiskDescriptionMediaRemovableKey); + const bool ejectable = + dictionaryBool(description, kDADiskDescriptionMediaEjectableKey); + const auto internal = + static_cast(dictionaryValue(description, + kDADiskDescriptionDeviceInternalKey)); + const bool isInternal = internal && CFGetTypeID(internal) == CFBooleanGetTypeID() && + CFBooleanGetValue(internal); + const QString protocol = fromCFString(static_cast( + dictionaryValue(description, + kDADiskDescriptionDeviceProtocolKey))) + .toLower(); + + if (removable || ejectable) + return true; + if (isInternal) + return false; + return protocol.contains(QStringLiteral("usb")) || + protocol.contains(QStringLiteral("firewire")) || + protocol.contains(QStringLiteral("thunderbolt")) || + protocol.contains(QStringLiteral("sd")); +} + +QString iconForDescription(CFDictionaryRef description) { + const QString protocol = fromCFString(static_cast( + dictionaryValue(description, + kDADiskDescriptionDeviceProtocolKey))) + .toLower(); + if (protocol.contains(QStringLiteral("sd"))) + return QStringLiteral("dev-sdcard"); + if (protocol.contains(QStringLiteral("usb"))) + return QStringLiteral("dev-usb"); + if (protocol.contains(QStringLiteral("firewire")) || + protocol.contains(QStringLiteral("thunderbolt"))) + return QStringLiteral("dev-hdd"); + return QStringLiteral("dev-drive"); +} + +} // namespace + +RemovableDeviceMonitor::RemovableDeviceMonitor(QObject *parent) : QObject(parent) { + auto *state = new MacDeviceState; + state->notificationCenter = [NSWorkspace sharedWorkspace].notificationCenter; + const auto scheduleRefresh = [this] { + QMetaObject::invokeMethod(this, "handleInterfacesChanged", Qt::QueuedConnection); + }; + state->mountObserver = + [state->notificationCenter addObserverForName:NSWorkspaceDidMountNotification + object:nil + queue:[NSOperationQueue mainQueue] + usingBlock:^(NSNotification *) { + scheduleRefresh(); + }]; + state->unmountObserver = + [state->notificationCenter addObserverForName:NSWorkspaceDidUnmountNotification + object:nil + queue:[NSOperationQueue mainQueue] + usingBlock:^(NSNotification *) { + scheduleRefresh(); + }]; + state->renameObserver = + [state->notificationCenter + addObserverForName:NSWorkspaceDidRenameVolumeNotification + object:nil + queue:[NSOperationQueue mainQueue] + usingBlock:^(NSNotification *) { + scheduleRefresh(); + }]; + m_nativeState = state; + + // The workspace notifications are immediate. The settled snapshot timer + // catches a volume whose mount notification races Disk Arbitration's final + // QStorageInfo state. + m_refreshDebounce = new QTimer(this); + m_refreshDebounce->setInterval(1000); + connect(m_refreshDebounce, &QTimer::timeout, this, &RemovableDeviceMonitor::refresh); + m_refreshDebounce->start(); + m_devices = enumerate(); +} + +RemovableDeviceMonitor::~RemovableDeviceMonitor() { + auto *state = static_cast(m_nativeState); + if (!state) + return; + m_nativeState = nullptr; + if (state->notificationCenter) { + if (state->mountObserver) + [state->notificationCenter removeObserver:state->mountObserver]; + if (state->unmountObserver) + [state->notificationCenter removeObserver:state->unmountObserver]; + if (state->renameObserver) + [state->notificationCenter removeObserver:state->renameObserver]; + } + delete state; +} + +QVector RemovableDeviceMonitor::devices() const { + return m_devices; +} + +void RemovableDeviceMonitor::handleInterfacesChanged() { + refresh(); +} + +void RemovableDeviceMonitor::refresh() { + const QVector fresh = enumerate(); + + for (const RemovableDevice ¤t : fresh) { + bool present = false; + for (const RemovableDevice &old : m_devices) { + if (old.id == current.id) { + present = true; + break; + } + } + if (!present) + emit deviceAdded(current); + } + for (const RemovableDevice &old : m_devices) { + bool present = false; + for (const RemovableDevice ¤t : fresh) { + if (old.id == current.id) { + present = true; + break; + } + } + if (!present) + emit deviceRemoved(old.id); + } + + bool changed = fresh.size() != m_devices.size(); + for (const RemovableDevice ¤t : fresh) { + for (const RemovableDevice &old : m_devices) { + if (old.id != current.id) + continue; + changed = changed || old.mountPoint != current.mountPoint || + old.name != current.name || + old.bytesTotal != current.bytesTotal || + old.bytesAvailable != current.bytesAvailable; + break; + } + } + + if (changed) { + m_devices = fresh; + emit devicesChanged(); + } +} + +QString RemovableDeviceMonitor::ensureMounted(const QString &id, QString *errorOut) { + for (const RemovableDevice &device : m_devices) { + if (device.id == id && device.isMounted && !device.mountPoint.isEmpty()) + return device.mountPoint; + } + + DASessionRef session = DASessionCreate(kCFAllocatorDefault); + if (!session) { + if (errorOut) + *errorOut = tr("Disk Arbitration is not available."); + return {}; + } + DASessionSetDispatchQueue(session, + dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)); + + const QByteArray bsdName = normalizedBSDName(id).toLocal8Bit(); + DADiskRef disk = + DADiskCreateFromBSDName(kCFAllocatorDefault, session, bsdName.constData()); + if (!disk) { + CFRelease(session); + if (errorOut) + *errorOut = tr("The volume is no longer available."); + return {}; + } + + DiskOperation operation; + operation.finished = dispatch_semaphore_create(0); + DADiskMount(disk, nullptr, kDADiskMountOptionDefault, mountCallback, &operation); + dispatch_semaphore_wait(operation.finished, DISPATCH_TIME_FOREVER); + const QString mountPoint = operation.mountPoint; + const QString error = operation.error; + CFRelease(disk); + CFRelease(session); + + if (!operation.success) { + if (errorOut) + *errorOut = error.isEmpty() ? tr("Could not mount the volume.") : error; + return {}; + } + refresh(); + return mountPoint; +} + +bool RemovableDeviceMonitor::eject(const QString &id, QString *errorOut) { + DASessionRef session = DASessionCreate(kCFAllocatorDefault); + if (!session) { + if (errorOut) + *errorOut = tr("Disk Arbitration is not available."); + return false; + } + DASessionSetDispatchQueue(session, + dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)); + + const QByteArray bsdName = normalizedBSDName(id).toLocal8Bit(); + DADiskRef disk = + DADiskCreateFromBSDName(kCFAllocatorDefault, session, bsdName.constData()); + if (!disk) { + CFRelease(session); + if (errorOut) + *errorOut = tr("The volume is no longer available."); + return false; + } + DADiskRef wholeDisk = DADiskCopyWholeDisk(disk); + if (!wholeDisk) + wholeDisk = disk; + + DiskOperation operation; + operation.finished = dispatch_semaphore_create(0); + DADiskEject(wholeDisk, kDADiskEjectOptionDefault, ejectCallback, &operation); + dispatch_semaphore_wait(operation.finished, DISPATCH_TIME_FOREVER); + const QString error = operation.error; + const bool success = operation.success; + if (wholeDisk != disk) + CFRelease(wholeDisk); + CFRelease(disk); + CFRelease(session); + + if (!success) { + if (errorOut) + *errorOut = error.isEmpty() ? tr("Could not eject the volume.") : error; + return false; + } + refresh(); + return true; +} + +QVector RemovableDeviceMonitor::enumerate() const { + QVector result; + DASessionRef session = DASessionCreate(kCFAllocatorDefault); + if (!session) + return result; + + for (const QStorageInfo &storage : QStorageInfo::mountedVolumes()) { + if (!storage.isValid() || !storage.isReady() || storage.isRoot()) + continue; + + const QString mountPoint = QDir::cleanPath(storage.rootPath()); + if (mountPoint.startsWith(QStringLiteral("/System/Volumes/"))) + continue; + + const QByteArray device = storage.device(); + if (device.isEmpty()) + continue; + QString id = QString::fromLocal8Bit(device); + if (!id.startsWith(QStringLiteral("/dev/"))) + id.prepend(QStringLiteral("/dev/")); + const QByteArray bsdName = id.mid(5).toLocal8Bit(); + DADiskRef disk = + DADiskCreateFromBSDName(kCFAllocatorDefault, session, bsdName.constData()); + if (!disk) + continue; + CFDictionaryRef description = DADiskCopyDescription(disk); + if (!isExternalVolume(description)) { + if (description) + CFRelease(description); + CFRelease(disk); + continue; + } + + RemovableDevice deviceInfo; + deviceInfo.id = id; + deviceInfo.devNode = id; + deviceInfo.mountPoint = mountPoint; + deviceInfo.isMounted = true; + deviceInfo.name = storage.displayName(); + if (deviceInfo.name.isEmpty()) + deviceInfo.name = QFileInfo(mountPoint).fileName(); + if (deviceInfo.name.isEmpty()) + deviceInfo.name = id; + deviceInfo.iconName = iconForDescription(description); + deviceInfo.bytesTotal = storage.bytesTotal(); + deviceInfo.bytesAvailable = storage.bytesAvailable(); + result.append(deviceInfo); + + if (description) + CFRelease(description); + CFRelease(disk); + } + CFRelease(session); + return result; +} diff --git a/src/core/devices/RemovableDeviceMonitor_windows.cpp b/src/core/devices/RemovableDeviceMonitor_windows.cpp index 5b982566..e2d138cc 100644 --- a/src/core/devices/RemovableDeviceMonitor_windows.cpp +++ b/src/core/devices/RemovableDeviceMonitor_windows.cpp @@ -121,6 +121,8 @@ RemovableDeviceMonitor::RemovableDeviceMonitor(QObject *parent) : QObject(parent refresh(); } +RemovableDeviceMonitor::~RemovableDeviceMonitor() = default; + QVector RemovableDeviceMonitor::devices() const { return m_devices; } QVector RemovableDeviceMonitor::enumerate() const { diff --git a/src/core/filesystem/DirectoryChangeMonitor_macos.cpp b/src/core/filesystem/DirectoryChangeMonitor_macos.cpp new file mode 100644 index 00000000..98940998 --- /dev/null +++ b/src/core/filesystem/DirectoryChangeMonitor_macos.cpp @@ -0,0 +1,105 @@ +#include "DirectoryChangeMonitor.h" + +#include + +#include +#include + +#include +#include +#include + +namespace { + +struct MacWatch { + int queue = -1; + int directory = -1; + QSocketNotifier *notifier = nullptr; +}; + +} // namespace + +bool DirectoryChangeMonitor::startNative(const QString &path) { + const QFileInfo info(path); + if (!info.exists() || !info.isDir()) + return false; + + auto *state = new MacWatch; + const QByteArray nativePath = info.absoluteFilePath().toLocal8Bit(); + state->directory = ::open(nativePath.constData(), O_RDONLY | O_EVTONLY | O_CLOEXEC); + if (state->directory < 0) { + delete state; + return false; + } + + state->queue = ::kqueue(); + if (state->queue < 0) { + ::close(state->directory); + delete state; + return false; + } + + struct kevent event; + EV_SET(&event, static_cast(state->directory), EVFILT_VNODE, + EV_ADD | EV_CLEAR, + NOTE_WRITE | NOTE_DELETE | NOTE_EXTEND | NOTE_ATTRIB | NOTE_LINK | + NOTE_RENAME | NOTE_REVOKE, + 0, nullptr); + if (::kevent(state->queue, &event, 1, nullptr, 0, nullptr) < 0) { + ::close(state->queue); + ::close(state->directory); + delete state; + return false; + } + + m_nativeState = state; + state->notifier = new QSocketNotifier(state->queue, QSocketNotifier::Read, this); + connect(state->notifier, &QSocketNotifier::activated, this, [this](int) { + auto *watch = static_cast(m_nativeState); + if (!watch) + return; + + bool changed = false; + for (;;) { + struct kevent event; + const timespec timeout{0, 0}; + const int count = ::kevent(watch->queue, nullptr, 0, &event, 1, &timeout); + if (count == 0) + break; + if (count < 0) { + if (errno == EINTR) + continue; + requireReconciliation(); + return; + } + + if ((event.flags & EV_ERROR) || + (event.fflags & (NOTE_DELETE | NOTE_RENAME | NOTE_REVOKE))) { + requireReconciliation(); + return; + } + changed = true; + } + + if (changed) + notifyChanged(); + }); + return true; +} + +void DirectoryChangeMonitor::stopNative() { + auto *state = static_cast(m_nativeState); + if (!state) + return; + m_nativeState = nullptr; + + if (state->notifier) { + state->notifier->setEnabled(false); + delete state->notifier; + } + if (state->queue >= 0) + ::close(state->queue); + if (state->directory >= 0) + ::close(state->directory); + delete state; +} diff --git a/src/core/network/SmbHelperClient.cpp b/src/core/network/SmbHelperClient.cpp index a9f8b074..0956b65e 100644 --- a/src/core/network/SmbHelperClient.cpp +++ b/src/core/network/SmbHelperClient.cpp @@ -1,10 +1,12 @@ #include "SmbHelperClient.h" #include +#include #include #include #include #include +#include #include "SmbHelperProtocol.h" @@ -12,6 +14,7 @@ #include #include +#include #include #include #include @@ -99,11 +102,18 @@ QString SmbHelperClient::helperPath() { // Next to the running binary first, so a development build and an // uninstalled AppImage layout both find their own helper rather than a // stale system-wide one. - const QString beside = - QCoreApplication::applicationDirPath() + QLatin1Char('/') + - QLatin1String(kHelperName); - if (QFileInfo(beside).isExecutable()) - return beside; + const QString appDir = QCoreApplication::applicationDirPath(); + const QStringList candidates = { + appDir + QLatin1Char('/') + QLatin1String(kHelperName), +#if defined(Q_OS_MACOS) + QDir::cleanPath(appDir + QStringLiteral("/../Helpers/") + + QLatin1String(kHelperName)), +#endif + }; + for (const QString &candidate : candidates) { + if (QFileInfo(candidate).isExecutable()) + return candidate; + } return QStandardPaths::findExecutable(QLatin1String(kHelperName)); }(); return path; @@ -374,8 +384,16 @@ SmbHelperClient::Channel *SmbHelperClient::spawn() { // parent cannot deadlock by draining the wrong one, and the helper's stderr // stays inherited for diagnostics. int sv[2]; - if (::socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, sv) != 0) + if (::socketpair(AF_UNIX, SOCK_STREAM, 0, sv) != 0) return nullptr; + for (const int fd : sv) { + const int flags = ::fcntl(fd, F_GETFD); + if (flags < 0 || ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) != 0) { + ::close(sv[0]); + ::close(sv[1]); + return nullptr; + } + } posix_spawn_file_actions_t actions; if (posix_spawn_file_actions_init(&actions) != 0) { diff --git a/src/platform/CMakeLists.txt b/src/platform/CMakeLists.txt index 5b2f2450..75616a59 100644 --- a/src/platform/CMakeLists.txt +++ b/src/platform/CMakeLists.txt @@ -31,6 +31,14 @@ if(WIN32) windows/WindowsPrivilegeBroker.cpp windows/WindowsShellShortcuts.cpp ) +elseif(APPLE) + list(APPEND PLATFORM_SOURCES + macos/MacOpenWithHandlers.mm + macos/MacTrashService.mm + macos/MacCredentialStore.cpp + macos/MacPrivilegeBroker.cpp + macos/MacShellShortcuts.cpp + ) else() list(APPEND PLATFORM_SOURCES linux/LinuxOpenWithHandlers.cpp @@ -46,8 +54,17 @@ target_include_directories(platform PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) target_link_libraries(platform PUBLIC Qt5::Core Qt5::Network) if(WIN32) target_link_libraries(platform PRIVATE shell32 ole32 Advapi32) -else() +elseif(FILECOMMANDER_ENABLE_LINUX_INTEGRATION) find_package(PkgConfig REQUIRED) pkg_check_modules(LIBSECRET REQUIRED IMPORTED_TARGET GLOBAL libsecret-1) target_link_libraries(platform PRIVATE PkgConfig::LIBSECRET) endif() + +if(APPLE) + target_link_libraries(platform PRIVATE + "-framework AppKit" + "-framework CoreServices" + "-framework Security" + "-framework UniformTypeIdentifiers" + ) +endif() diff --git a/src/platform/TerminalLauncher.cpp b/src/platform/TerminalLauncher.cpp index 405d38ca..92b6764f 100644 --- a/src/platform/TerminalLauncher.cpp +++ b/src/platform/TerminalLauncher.cpp @@ -20,6 +20,16 @@ QVector terminalCandidates(const QString &workingDirectory) { // cannot come up empty on a working system. {QStringLiteral("cmd.exe"), {}}, }; +#elif defined(Q_OS_MACOS) + // Launch Services opens the installed terminal application and receives + // the directory as an explicit document. This does not depend on a shell + // executable being present on PATH. + return { + {QStringLiteral("/usr/bin/open"), + {QStringLiteral("-a"), QStringLiteral("Terminal"), workingDirectory}}, + {QStringLiteral("/usr/bin/open"), + {QStringLiteral("-a"), QStringLiteral("iTerm"), workingDirectory}}, + }; #else Q_UNUSED(workingDirectory); QVector candidates = { diff --git a/src/platform/macos/FileCommanderPrivilegedHelper.cpp b/src/platform/macos/FileCommanderPrivilegedHelper.cpp new file mode 100644 index 00000000..a7c14a64 --- /dev/null +++ b/src/platform/macos/FileCommanderPrivilegedHelper.cpp @@ -0,0 +1,157 @@ +#include "privilege/PrivilegedFileOperation.h" + +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace { + +QJsonObject response(bool ok, PrivilegeStatus status, qint64 nativeCode, + const QString &message = {}) { + return { + {QStringLiteral("ok"), ok}, + {QStringLiteral("status"), static_cast(status)}, + {QStringLiteral("nativeCode"), static_cast(nativeCode)}, + {QStringLiteral("message"), message}, + }; +} + +bool exists(const QString &path) { + return QFileInfo(path).exists() || QFileInfo(path).isSymLink(); +} + +int runTool(const QString &program, const QStringList &arguments, QString *errorMessage) { + QProcess process; + process.start(program, arguments); + if (!process.waitForStarted()) { + if (errorMessage) + *errorMessage = QStringLiteral("Could not start %1.").arg(program); + return ENOENT; + } + if (!process.waitForFinished(-1)) { + if (errorMessage) + *errorMessage = QStringLiteral("%1 did not finish.").arg(program); + return EIO; + } + if (process.exitStatus() != QProcess::NormalExit || process.exitCode() != 0) { + const QString detail = QString::fromLocal8Bit(process.readAllStandardError()).trimmed(); + if (errorMessage) + *errorMessage = detail.isEmpty() + ? QStringLiteral("%1 failed with exit code %2.") + .arg(program) + .arg(process.exitCode()) + : detail; + return process.exitCode() == 0 ? EIO : process.exitCode(); + } + return 0; +} + +PrivilegeResult perform(const PrivilegedOperationRequest &request) { + const PrivilegeResult validation = validatePrivilegedOperationRequest(request); + if (validation.status != PrivilegeStatus::Succeeded) + return validation; + + const bool needsSource = request.kind != PrivilegedOperationKind::Mkdir; + const bool needsTarget = request.kind != PrivilegedOperationKind::DeletePermanent; + if ((needsSource && !exists(request.sourcePath)) || + (needsTarget && request.kind != PrivilegedOperationKind::Mkdir && + !QFileInfo(request.targetPath).absoluteDir().exists())) { + return {PrivilegeStatus::Failed, ENOENT, + QStringLiteral("A source or destination parent does not exist.")}; + } + + if (request.kind == PrivilegedOperationKind::Mkdir) { + QString error; + const int code = runTool(QStringLiteral("/bin/mkdir"), + {QStringLiteral("-p"), QStringLiteral("--"), + request.targetPath}, + &error); + return code == 0 + ? PrivilegeResult{PrivilegeStatus::Succeeded, 0, {}} + : PrivilegeResult{PrivilegeStatus::Failed, code, error}; + } + + if (request.kind != PrivilegedOperationKind::DeletePermanent && + exists(request.targetPath)) { + if (!request.overwrite) + return {PrivilegeStatus::Failed, EEXIST, + QStringLiteral("The target path already exists.")}; + QString error; + const int code = runTool(QStringLiteral("/bin/rm"), + {QStringLiteral("-rf"), QStringLiteral("--"), + request.targetPath}, + &error); + if (code != 0) + return {PrivilegeStatus::Failed, code, error}; + } + + QString program; + QStringList arguments; + switch (request.kind) { + case PrivilegedOperationKind::Copy: + program = QStringLiteral("/bin/cp"); + arguments = QStringList{QStringLiteral("-a"), QStringLiteral("--"), + request.sourcePath, request.targetPath}; + break; + case PrivilegedOperationKind::Move: + case PrivilegedOperationKind::Rename: + program = QStringLiteral("/bin/mv"); + arguments = + QStringList{QStringLiteral("--"), request.sourcePath, request.targetPath}; + break; + case PrivilegedOperationKind::DeletePermanent: + program = QStringLiteral("/bin/rm"); + arguments = + QStringList{QStringLiteral("-rf"), QStringLiteral("--"), request.sourcePath}; + break; + case PrivilegedOperationKind::Symlink: + program = QStringLiteral("/bin/ln"); + arguments = QStringList{QStringLiteral("-s"), QStringLiteral("--"), + request.sourcePath, request.targetPath}; + break; + case PrivilegedOperationKind::Mkdir: + break; + } + + QString error; + const int code = runTool(program, arguments, &error); + return code == 0 + ? PrivilegeResult{PrivilegeStatus::Succeeded, 0, {}} + : PrivilegeResult{PrivilegeStatus::Failed, code, error}; +} + +} // namespace + +int main(int argc, char **argv) { + QCoreApplication application(argc, argv); + if (argc != 2) { + const QByteArray output = + QJsonDocument(response(false, PrivilegeStatus::InvalidRequest, EINVAL, + QStringLiteral("The helper received an invalid argument count."))) + .toJson(QJsonDocument::Compact); + fwrite(output.constData(), 1, static_cast(output.size()), stdout); + fputc('\n', stdout); + return 2; + } + + PrivilegedOperationRequest request; + const PrivilegeResult decoded = + decodePrivilegedRequest(QByteArray(argv[1]), &request); + const PrivilegeResult result = decoded.status == PrivilegeStatus::Succeeded + ? perform(request) + : decoded; + const QByteArray output = + QJsonDocument(response(result.status == PrivilegeStatus::Succeeded, + result.status, result.nativeCode, result.message)) + .toJson(QJsonDocument::Compact); + fwrite(output.constData(), 1, static_cast(output.size()), stdout); + fputc('\n', stdout); + fflush(stdout); + return result.status == PrivilegeStatus::Succeeded ? 0 : 1; +} diff --git a/src/platform/macos/MacCredentialStore.cpp b/src/platform/macos/MacCredentialStore.cpp new file mode 100644 index 00000000..55b3f5ea --- /dev/null +++ b/src/platform/macos/MacCredentialStore.cpp @@ -0,0 +1,104 @@ +#include "CredentialStore.h" + +#include + +namespace { + +const QString kService = QStringLiteral("com.aigutta.FileCommander"); + +PlatformResult invalidId() { + return PlatformResult::failure(PlatformError::InvalidPath, + QStringLiteral("Credential id is empty.")); +} + +struct SecurityResult { + bool started = false; + int exitCode = -1; + QString standardOutput; + QString standardError; +}; + +SecurityResult runSecurity(const QStringList &arguments, const QByteArray &standardInput = {}) { + QProcess process; + process.start(QStringLiteral("/usr/bin/security"), arguments); + if (!process.waitForStarted()) + return {}; + process.write(standardInput); + process.closeWriteChannel(); + if (!process.waitForFinished(-1)) + return {true, -1, {}, QStringLiteral("The security command did not finish.")}; + return { + true, + process.exitCode(), + QString::fromUtf8(process.readAllStandardOutput()).trimmed(), + QString::fromUtf8(process.readAllStandardError()).trimmed(), + }; +} + +PlatformResult securityFailure(const SecurityResult &result, const QString &action) { + const QString detail = result.standardError.isEmpty() + ? QStringLiteral("exit code %1").arg(result.exitCode) + : result.standardError; + return PlatformResult::failure(PlatformError::NativeFailure, + QStringLiteral("%1: %2").arg(action, detail), + result.exitCode); +} + +} // namespace + +PlatformResult CredentialStore::save(const QString &id, const QString &secret) { + if (id.isEmpty()) + return invalidId(); + const SecurityResult result = runSecurity({ + QStringLiteral("add-generic-password"), + QStringLiteral("-a"), id, + QStringLiteral("-s"), kService, + QStringLiteral("-U"), + QStringLiteral("-w"), + }, secret.toUtf8() + '\n'); + return result.started && result.exitCode == 0 + ? PlatformResult::success() + : securityFailure(result, QStringLiteral("Keychain save")); +} + +PlatformResult CredentialStore::load(const QString &id, QString *secret) { + if (secret) + secret->clear(); + if (id.isEmpty()) + return invalidId(); + const SecurityResult result = runSecurity({ + QStringLiteral("find-generic-password"), + QStringLiteral("-a"), id, + QStringLiteral("-s"), kService, + QStringLiteral("-w"), + }); + if (result.started && result.exitCode == 0) { + if (secret) + *secret = result.standardOutput; + return PlatformResult::success(); + } + if (result.standardError.contains(QStringLiteral("could not be found"), + Qt::CaseInsensitive)) { + return PlatformResult::failure(PlatformError::NotFound, + QStringLiteral("Credential was not found."), + result.exitCode); + } + return securityFailure(result, QStringLiteral("Keychain lookup")); +} + +PlatformResult CredentialStore::remove(const QString &id) { + if (id.isEmpty()) + return invalidId(); + const SecurityResult result = runSecurity({ + QStringLiteral("delete-generic-password"), + QStringLiteral("-a"), id, + QStringLiteral("-s"), kService, + }); + if (result.started && result.exitCode == 0) + return PlatformResult::success(); + if (result.standardError.contains(QStringLiteral("could not be found"), + Qt::CaseInsensitive)) { + return PlatformResult::success(); + } + return securityFailure(result, QStringLiteral("Keychain removal")); +} diff --git a/src/platform/macos/MacOpenWithHandlers.mm b/src/platform/macos/MacOpenWithHandlers.mm new file mode 100644 index 00000000..59b2099b --- /dev/null +++ b/src/platform/macos/MacOpenWithHandlers.mm @@ -0,0 +1,128 @@ +#include "OpenWithHandlers.h" + +#import +#import + +#include + +namespace { + +QString stringFromNSString(NSString *value) { + return value ? QString::fromUtf8(value.UTF8String) : QString(); +} + +QString pathFromURL(NSURL *url) { + return stringFromNSString(url.path); +} + +NSString *bundleIdentifierForURL(NSURL *url) { + NSBundle *bundle = [NSBundle bundleWithURL:url]; + return bundle.bundleIdentifier; +} + +QString displayNameForURL(NSURL *url) { + NSBundle *bundle = [NSBundle bundleWithURL:url]; + NSString *name = [bundle objectForInfoDictionaryKey:@"CFBundleDisplayName"]; + if (!name) + name = [bundle objectForInfoDictionaryKey:@"CFBundleName"]; + if (!name) + name = url.lastPathComponent.stringByDeletingPathExtension; + return stringFromNSString(name); +} + +NSArray *applicationURLsForPath(NSString *path) { + NSWorkspace *workspace = [NSWorkspace sharedWorkspace]; + NSURL *fileURL = [NSURL fileURLWithPath:path]; + if ([NSFileManager.defaultManager fileExistsAtPath:path]) + return [workspace URLsForApplicationsToOpenURL:fileURL]; + + NSString *extension = path.pathExtension; + if (extension.length == 0) + return @[]; + UTType *type = [UTType typeWithFilenameExtension:extension]; + if (!type) + return @[]; + return [workspace URLsForApplicationsToOpenContentType:type]; +} + +} // namespace + +namespace fc { + +QVector openWithHandlers(const QString &filePath) { + if (filePath.isEmpty()) + return {}; + + @autoreleasepool { + NSString *path = [NSString stringWithUTF8String:filePath.toUtf8().constData()]; + if (!path) + return {}; + + NSArray *applications = applicationURLsForPath(path); + if (!applications || applications.count == 0) + return {}; + + NSWorkspace *workspace = [NSWorkspace sharedWorkspace]; + NSURL *fileURL = [NSURL fileURLWithPath:path]; + NSURL *defaultURL = nil; + if ([NSFileManager.defaultManager fileExistsAtPath:path]) { + defaultURL = [workspace URLForApplicationToOpenURL:fileURL]; + } else { + NSString *extension = path.pathExtension; + UTType *type = extension.length > 0 + ? [UTType typeWithFilenameExtension:extension] + : nil; + if (type) + defaultURL = [workspace URLForApplicationToOpenContentType:type]; + } + + const QString defaultPath = pathFromURL(defaultURL); + QVector handlers; + for (NSURL *applicationURL in applications) { + const QString applicationPath = pathFromURL(applicationURL); + if (applicationPath.isEmpty()) + continue; + + OpenWithHandler handler; + handler.displayName = displayNameForURL(applicationURL); + if (handler.displayName.isEmpty()) + handler.displayName = QFileInfo(applicationPath).completeBaseName(); + handler.program = applicationPath; + handler.iconPath = applicationPath; + handler.token = stringFromNSString(bundleIdentifierForURL(applicationURL)); + handler.recommended = + !defaultPath.isEmpty() && + QFileInfo(applicationPath).canonicalFilePath() == + QFileInfo(defaultPath).canonicalFilePath(); + handlers.append(handler); + } + return tidyOpenWithHandlers(std::move(handlers)); + } +} + +bool launchOpenWithHandler(const OpenWithHandler &handler, const QString &filePath) { + if (handler.program.isEmpty() || filePath.isEmpty()) + return false; + + @autoreleasepool { + NSString *applicationPath = + [NSString stringWithUTF8String:handler.program.toUtf8().constData()]; + NSString *filePathString = + [NSString stringWithUTF8String:filePath.toUtf8().constData()]; + if (!applicationPath || !filePathString) + return false; + + NSURL *applicationURL = [NSURL fileURLWithPath:applicationPath]; + NSURL *fileURL = [NSURL fileURLWithPath:filePathString]; + NSError *error = nil; + NSRunningApplication *application = + [[NSWorkspace sharedWorkspace] openURLs:@[fileURL] + withApplicationAtURL:applicationURL + options:NSWorkspaceLaunchDefault + configuration:@{} + error:&error]; + return application != nil && error == nil; + } +} + +} // namespace fc diff --git a/src/platform/macos/MacPrivilegeBroker.cpp b/src/platform/macos/MacPrivilegeBroker.cpp new file mode 100644 index 00000000..d3bbc1a8 --- /dev/null +++ b/src/platform/macos/MacPrivilegeBroker.cpp @@ -0,0 +1,166 @@ +#include "privilege/PrivilegeBroker.h" + +#include +#include + +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace { + +PrivilegeBroker::LinuxPrivilegeLauncher &testLauncher() { + static PrivilegeBroker::LinuxPrivilegeLauncher launcher; + return launcher; +} + +PrivilegeBroker::LinuxExecutableResolver &testResolver() { + static PrivilegeBroker::LinuxExecutableResolver resolver; + return resolver; +} + +QString helperPath() { + const QString overridePath = + qEnvironmentVariable("FILECOMMANDER_PRIVILEGED_HELPER"); + if (!overridePath.isEmpty() && QFileInfo(overridePath).isExecutable()) + return overridePath; + + const QString helperName = + QStringLiteral("com.aigutta.FileCommander.privileged-helper"); + const QString applicationDir = QCoreApplication::applicationDirPath(); + const QStringList candidates = { + QDir(applicationDir).filePath(QStringLiteral("../Library/LaunchServices/") + helperName), + QDir(applicationDir).filePath(helperName), + }; + for (const QString &candidate : candidates) { + const QFileInfo info(candidate); + if (info.isFile() && info.isExecutable()) + return info.absoluteFilePath(); + } + return {}; +} + +PrivilegeResult failed(OSStatus status, const QString &message) { + return {PrivilegeStatus::Failed, static_cast(status), message}; +} + +PrivilegeResult authorizationFailure(OSStatus status) { + if (status == errAuthorizationCanceled || status == errAuthorizationDenied) + return {PrivilegeStatus::Denied, static_cast(status), + QStringLiteral("Administrator authorization was denied.")}; + return failed(status, QStringLiteral("macOS could not authorize the administrator operation.")); +} + +} // namespace + +namespace PrivilegeBroker { + +bool isAvailable() { + return !helperPath().isEmpty(); +} + +PrivilegeResult execute(const PrivilegedOperationRequest &request, CancelCheck cancelled) { + const PrivilegeResult validation = validatePrivilegedOperationRequest(request); + if (validation.status != PrivilegeStatus::Succeeded) + return validation; + if (cancelled && cancelled()) + return {PrivilegeStatus::Cancelled, ECANCELED, + QStringLiteral("The operation was cancelled.")}; + + const QString helper = helperPath(); + if (helper.isEmpty()) + return {PrivilegeStatus::Failed, ENOENT, + QStringLiteral("The FileCommander administrator helper is not installed.")}; + + AuthorizationRef authorization = nullptr; + OSStatus status = AuthorizationCreate(nullptr, nullptr, kAuthorizationFlagDefaults, + &authorization); + if (status != errAuthorizationSuccess) + return authorizationFailure(status); + + const QByteArray helperBytes = QFile::encodeName(helper); + AuthorizationItem right{ + kAuthorizationRightExecute, + static_cast(helperBytes.size()), + const_cast(helperBytes.constData()), + 0, + }; + AuthorizationRights rights{1, &right}; + status = AuthorizationCopyRights( + authorization, &rights, nullptr, + kAuthorizationFlagInteractionAllowed | kAuthorizationFlagPreAuthorize | + kAuthorizationFlagExtendRights, + nullptr); + if (status != errAuthorizationSuccess) { + AuthorizationFree(authorization, kAuthorizationFlagDefaults); + return authorizationFailure(status); + } + + const QByteArray encoded = encodePrivilegedRequest(request); + if (encoded.isEmpty()) { + AuthorizationFree(authorization, kAuthorizationFlagDefaults); + return {PrivilegeStatus::InvalidRequest, EINVAL, + QStringLiteral("The administrator request could not be encoded.")}; + } + + char *arguments[] = {const_cast(encoded.constData()), nullptr}; + FILE *pipe = nullptr; + status = AuthorizationExecuteWithPrivileges( + authorization, helperBytes.constData(), kAuthorizationFlagDefaults, arguments, &pipe); + if (status != errAuthorizationSuccess) { + AuthorizationFree(authorization, kAuthorizationFlagDefaults); + return authorizationFailure(status); + } + + QByteArray output; + if (pipe) { + char buffer[4096]; + while (!feof(pipe)) { + const size_t count = fread(buffer, 1, sizeof(buffer), pipe); + if (count > 0) + output.append(buffer, static_cast(count)); + if (ferror(pipe)) + break; + } + fclose(pipe); + } + AuthorizationFree(authorization, kAuthorizationFlagDefaults); + + QJsonParseError parseError; + const QJsonDocument document = QJsonDocument::fromJson(output, &parseError); + if (parseError.error != QJsonParseError::NoError || !document.isObject()) + return failed(EIO, QStringLiteral("The administrator helper returned no valid result.")); + + const QJsonObject object = document.object(); + const auto resultStatus = + static_cast(object.value(QStringLiteral("status")).toInt( + static_cast(PrivilegeStatus::Failed))); + const qint64 nativeCode = + static_cast(object.value(QStringLiteral("nativeCode")).toDouble()); + const QString message = object.value(QStringLiteral("message")).toString(); + return {resultStatus, nativeCode, message}; +} + +void setLinuxPrivilegeLauncherForTesting(LinuxPrivilegeLauncher launcher) { + testLauncher() = std::move(launcher); +} + +void resetLinuxPrivilegeLauncherForTesting() { + testLauncher() = {}; +} + +void setLinuxExecutableResolverForTesting(LinuxExecutableResolver resolver) { + testResolver() = std::move(resolver); +} + +void resetLinuxExecutableResolverForTesting() { + testResolver() = {}; +} + +} // namespace PrivilegeBroker diff --git a/src/platform/macos/MacShellShortcuts.cpp b/src/platform/macos/MacShellShortcuts.cpp new file mode 100644 index 00000000..75cfd62a --- /dev/null +++ b/src/platform/macos/MacShellShortcuts.cpp @@ -0,0 +1,106 @@ +#include "ShellShortcuts.h" + +#include +#include +#include + +namespace { + +const QString kDesktopScript = QStringLiteral( + "on run argv\n" + "set targetPath to item 1 of argv\n" + "set aliasName to item 2 of argv\n" + "tell application \"Finder\"\n" + "set desktopFolder to desktop\n" + "try\n" + "delete (some item of desktopFolder whose name is aliasName)\n" + "end try\n" + "set newAlias to make new alias file at desktopFolder to (POSIX file targetPath as alias)\n" + "set name of newAlias to aliasName\n" + "end tell\n" + "end run"); + +PlatformResult runAppleScript(const QStringList &arguments) { + QProcess process; + process.start(QStringLiteral("/usr/bin/osascript"), + QStringList{QStringLiteral("-e"), kDesktopScript} + arguments); + if (!process.waitForStarted()) + return PlatformResult::failure( + PlatformError::NativeFailure, + QStringLiteral("Could not start Finder automation.")); + if (!process.waitForFinished(-1)) + return PlatformResult::failure( + PlatformError::NativeFailure, + QStringLiteral("Finder automation did not finish.")); + if (process.exitStatus() != QProcess::NormalExit || process.exitCode() != 0) { + const QString error = + QString::fromUtf8(process.readAllStandardError()).trimmed(); + return PlatformResult::failure( + PlatformError::NativeFailure, + error.isEmpty() ? QStringLiteral("Finder could not create the alias.") : error, + process.exitCode()); + } + return PlatformResult::success(); +} + +} // namespace + +namespace fc::ShellShortcuts { + +bool isSupported() { + return true; +} + +bool supports(Destination where) { + return where == Destination::Desktop; +} + +QString locationFor(Destination where) { + if (where != Destination::Desktop) + return {}; + return QStandardPaths::writableLocation(QStandardPaths::DesktopLocation); +} + +bool isLaunchable(const QString &path) { + const QFileInfo info(path); + if (!info.exists()) + return false; + if (info.isDir()) + return info.fileName().endsWith(QStringLiteral(".app"), Qt::CaseInsensitive); + return info.isExecutable(); +} + +bool needsExecutableBit(const QString &) { + return false; +} + +PlatformResult makeExecutable(const QString &) { + return PlatformResult::failure( + PlatformError::Unsupported, + QStringLiteral("macOS launchable items do not require an AppImage executable-bit fix.")); +} + +PlatformResult create(const QString &targetPath, Destination where) { + if (!supports(where)) + return PlatformResult::failure( + PlatformError::Unsupported, + QStringLiteral("This shortcut destination is not available.")); + + const QFileInfo target(targetPath); + if (!target.exists() && !target.isSymLink()) + return PlatformResult::failure(PlatformError::NotFound, + QStringLiteral("The target does not exist.")); + + const QString desktop = locationFor(where); + if (desktop.isEmpty() || !QFileInfo(desktop).isDir()) + return PlatformResult::failure( + PlatformError::NativeFailure, + QStringLiteral("The Desktop folder is not available.")); + + QString aliasName = target.fileName(); + if (aliasName.isEmpty()) + aliasName = target.absoluteFilePath(); + return runAppleScript({target.absoluteFilePath(), aliasName}); +} + +} // namespace fc::ShellShortcuts diff --git a/src/platform/macos/MacTrashService.mm b/src/platform/macos/MacTrashService.mm new file mode 100644 index 00000000..c7463c43 --- /dev/null +++ b/src/platform/macos/MacTrashService.mm @@ -0,0 +1,152 @@ +#include "TrashService.h" + +#import + +#include +#include +#include +#include +#include + +namespace { + +QString tokenFor(const QString &original, const QString &trashed) { + const QJsonObject object{ + {QStringLiteral("version"), 1}, + {QStringLiteral("original"), original}, + {QStringLiteral("trashed"), trashed}, + }; + return QString::fromLatin1( + QJsonDocument(object).toJson(QJsonDocument::Compact).toBase64()); +} + +bool decodeToken(const QString &token, QString *original, QString *trashed, + QString *errorMessage) { + const QJsonDocument document = + QJsonDocument::fromJson(QByteArray::fromBase64(token.toLatin1())); + if (!document.isObject()) { + if (errorMessage) + *errorMessage = QStringLiteral("The Trash restore token is invalid."); + return false; + } + + const QJsonObject object = document.object(); + if (object.value(QStringLiteral("version")).toInt() != 1 || + !object.value(QStringLiteral("original")).isString() || + !object.value(QStringLiteral("trashed")).isString()) { + if (errorMessage) + *errorMessage = QStringLiteral("The Trash restore token is invalid."); + return false; + } + + const QString originalPath = object.value(QStringLiteral("original")).toString(); + const QString trashedPath = object.value(QStringLiteral("trashed")).toString(); + if (!QDir::isAbsolutePath(originalPath) || !QDir::isAbsolutePath(trashedPath)) { + if (errorMessage) + *errorMessage = QStringLiteral("The Trash restore token contains a relative path."); + return false; + } + + if (original) + *original = originalPath; + if (trashed) + *trashed = trashedPath; + return true; +} + +struct RecycleResult { + bool ok = false; + QString trashedPath; + QString error; +}; + +RecycleResult recycleOne(const QString &path) { + RecycleResult result; + if (!QFileInfo(path).exists() && !QFileInfo(path).isSymLink()) { + result.error = QStringLiteral("No such file: %1").arg(path); + return result; + } + + NSString *sourcePath = + [NSString stringWithUTF8String:path.toUtf8().constData()]; + if (!sourcePath) { + result.error = QStringLiteral("The source path is not valid UTF-8."); + return result; + } + NSURL *sourceURL = [NSURL fileURLWithPath:sourcePath]; + + NSURL *trashedURL = nil; + NSError *operationError = nil; + const BOOL recycled = + [[NSFileManager defaultManager] trashItemAtURL:sourceURL + resultingItemURL:&trashedURL + error:&operationError]; + if (!recycled) { + if (operationError && operationError.localizedDescription) + result.error = QString::fromUtf8(operationError.localizedDescription.UTF8String); + else + result.error = QStringLiteral("macOS could not move the item to the Trash."); + return result; + } + + if (!trashedURL) { + result.error = QStringLiteral("macOS did not return the new Trash location."); + return result; + } + result.ok = true; + result.trashedPath = QString::fromUtf8(trashedURL.path.UTF8String); + return result; +} + +PlatformResult restoreOne(const QString &token) { + QString original; + QString trashed; + QString error; + if (!decodeToken(token, &original, &trashed, &error)) + return PlatformResult::failure(PlatformError::InvalidPath, error); + if (!QFileInfo(trashed).exists() && !QFileInfo(trashed).isSymLink()) + return PlatformResult::failure(PlatformError::NotFound, + QStringLiteral("The item is no longer in the Trash.")); + if (QFileInfo(original).exists() || QFileInfo(original).isSymLink()) + return PlatformResult::failure( + PlatformError::Busy, + QStringLiteral("The original path already exists: %1").arg(original)); + if (!QDir().mkpath(QFileInfo(original).absolutePath())) + return PlatformResult::failure( + PlatformError::NativeFailure, + QStringLiteral("Could not create the original parent directory.")); + if (!QFile::rename(trashed, original)) + return PlatformResult::failure( + PlatformError::NativeFailure, + QStringLiteral("Could not restore the item from the Trash.")); + return PlatformResult::success(); +} + +class MacTrashService final : public TrashService { +public: + PlatformResult moveToTrash(const QStringList &paths) override { + QStringList undoEntries; + for (const QString &path : paths) { + const RecycleResult result = recycleOne(path); + if (!result.ok) + return PlatformResult::failure(PlatformError::NativeFailure, result.error); + undoEntries.append(tokenFor(path, result.trashedPath)); + } + return PlatformResult::success(undoEntries); + } + + PlatformResult restoreFromTrash(const QStringList &entries) override { + for (const QString &entry : entries) { + const PlatformResult result = restoreOne(entry); + if (!result.ok) + return result; + } + return PlatformResult::success(); + } +}; + +} // namespace + +std::unique_ptr createTrashService() { + return std::make_unique(); +} diff --git a/src/smbhelper/CMakeLists.txt b/src/smbhelper/CMakeLists.txt index f7f45963..4cbb031b 100644 --- a/src/smbhelper/CMakeLists.txt +++ b/src/smbhelper/CMakeLists.txt @@ -6,7 +6,7 @@ # its variables in the calling directory's scope, which does not reach sibling # subdirectories. find_package(PkgConfig REQUIRED) -pkg_check_modules(SMBCLIENT REQUIRED smbclient) +pkg_check_modules(SMBCLIENT REQUIRED IMPORTED_TARGET GLOBAL smbclient) include(GNUInstallDirs) @@ -14,10 +14,9 @@ add_executable(FileCommander-smb-helper main.cpp) target_include_directories(FileCommander-smb-helper PRIVATE ${CMAKE_SOURCE_DIR}/src/core/network # SmbHelperProtocol.h (Qt-free by design) - ${SMBCLIENT_INCLUDE_DIRS} ) -target_link_libraries(FileCommander-smb-helper PRIVATE ${SMBCLIENT_LIBRARIES}) +target_link_libraries(FileCommander-smb-helper PRIVATE PkgConfig::SMBCLIENT) # Land beside the FileCommander binary in the build tree, because SmbHelperClient looks # for the helper next to the running executable first -- so a development build @@ -25,7 +24,19 @@ target_link_libraries(FileCommander-smb-helper PRIVATE ${SMBCLIENT_LIBRARIES}) # AUTOMOC is on project-wide; this target has no Qt at all, so turn it off # rather than run moc over a translation unit that can never need it. set_target_properties(FileCommander-smb-helper PROPERTIES - RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR} AUTOMOC OFF) +if(APPLE) + set_target_properties(FileCommander-smb-helper PROPERTIES + RUNTIME_OUTPUT_DIRECTORY + "${CMAKE_BINARY_DIR}/FileCommander.app/Contents/Helpers") +else() + set_target_properties(FileCommander-smb-helper PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}") +endif() -install(TARGETS FileCommander-smb-helper RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}) +if(APPLE) + install(TARGETS FileCommander-smb-helper + RUNTIME DESTINATION FileCommander.app/Contents/Helpers) +else() + install(TARGETS FileCommander-smb-helper RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}) +endif() diff --git a/src/ui/CMakeLists.txt b/src/ui/CMakeLists.txt index 0e08ab60..237a2de2 100644 --- a/src/ui/CMakeLists.txt +++ b/src/ui/CMakeLists.txt @@ -58,7 +58,6 @@ set(UI_SOURCES DragPixmap.h DragPixmap.cpp DesktopNotify.h - DesktopNotify.cpp PendingSendQueue.h PendingSendQueue.cpp CloudClipboardController.h @@ -120,6 +119,12 @@ set(UI_SOURCES dialogs/AboutDialog.cpp ) +if(APPLE) + list(APPEND UI_SOURCES DesktopNotify_macos.mm) +else() + list(APPEND UI_SOURCES DesktopNotify.cpp) +endif() + if(WIN32) list(APPEND UI_SOURCES media/WindowsMediaSurface.h @@ -228,6 +233,37 @@ if(FILECOMMANDER_PREVIEW_PDF) INTERFACE_INCLUDE_DIRECTORIES "${FILECOMMANDER_POPPLER_QT5_ROOT}/include/poppler/qt5" ) + elseif(APPLE) + set(FILECOMMANDER_POPPLER_QT5_ROOT + "$ENV{FILECOMMANDER_POPPLER_QT5_ROOT}" CACHE PATH + "Poppler Qt5 installation built against the selected Qt 5 SDK") + if(NOT FILECOMMANDER_POPPLER_QT5_ROOT) + set(FILECOMMANDER_POPPLER_QT5_ROOT + "${CMAKE_SOURCE_DIR}/.deps/macos/poppler-qt5-x64" + CACHE PATH + "Poppler Qt5 installation built against the selected Qt 5 SDK") + endif() + if(NOT EXISTS + "${FILECOMMANDER_POPPLER_QT5_ROOT}/include/poppler/qt5/poppler-qt5.h") + message(FATAL_ERROR + "FILECOMMANDER_PREVIEW_PDF requires " + "FILECOMMANDER_POPPLER_QT5_ROOT to point to a Poppler Qt5 " + "build made against this Qt 5 SDK.") + endif() + find_library(_fc_poppler_qt5 + NAMES poppler-qt5 + PATHS "${FILECOMMANDER_POPPLER_QT5_ROOT}/lib" + NO_DEFAULT_PATH) + if(NOT _fc_poppler_qt5) + message(FATAL_ERROR + "Poppler Qt5 library was not found below " + "${FILECOMMANDER_POPPLER_QT5_ROOT}/lib.") + endif() + add_library(FileCommander::PopplerQt5 SHARED IMPORTED GLOBAL) + set_target_properties(FileCommander::PopplerQt5 PROPERTIES + IMPORTED_LOCATION "${_fc_poppler_qt5}" + INTERFACE_INCLUDE_DIRECTORIES + "${FILECOMMANDER_POPPLER_QT5_ROOT}/include/poppler/qt5") else() find_package(PkgConfig REQUIRED) pkg_check_modules(POPPLER_QT5 REQUIRED IMPORTED_TARGET GLOBAL poppler-qt5) @@ -291,3 +327,8 @@ endif() if(FILECOMMANDER_ENABLE_LINUX_INTEGRATION) target_link_libraries(ui PRIVATE Qt5::X11Extras PkgConfig::XCB Qt5::DBus) endif() +if(APPLE) + target_link_libraries(ui PRIVATE + "-framework UserNotifications" + ) +endif() diff --git a/src/ui/DesktopNotify.h b/src/ui/DesktopNotify.h index dfe7bb7d..5904b388 100644 --- a/src/ui/DesktopNotify.h +++ b/src/ui/DesktopNotify.h @@ -5,10 +5,8 @@ namespace ttc { // Fires a best-effort passive desktop notification. A silent no-op where there -// is no notification service (headless, a platform without -// org.freedesktop.Notifications, or a bus that refuses): an arrival must never -// cost the user a modal or a crash. Linux only for now; other platforms are a -// no-op until they get a native path. +// is no notification service or the platform refuses the request: an arrival +// must never cost the user a modal or a crash. void notify(const QString &title, const QString &body); } // namespace ttc diff --git a/src/ui/DesktopNotify_macos.mm b/src/ui/DesktopNotify_macos.mm new file mode 100644 index 00000000..b3463bc6 --- /dev/null +++ b/src/ui/DesktopNotify_macos.mm @@ -0,0 +1,52 @@ +#include "DesktopNotify.h" + +#import + +#include + +namespace ttc { + +void notify(const QString &title, const QString &body) { + @autoreleasepool { + UNUserNotificationCenter *center = + [UNUserNotificationCenter currentNotificationCenter]; + if (!center) + return; + + NSString *titleString = + [NSString stringWithUTF8String:title.toUtf8().constData()]; + NSString *bodyString = + [NSString stringWithUTF8String:body.toUtf8().constData()]; + if (!titleString) + titleString = @"FileCommander"; + if (!bodyString) + bodyString = @""; + + [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert | + UNAuthorizationOptionSound) + completionHandler:^(BOOL granted, NSError *) { + if (!granted) + return; + UNMutableNotificationContent *content = + [[UNMutableNotificationContent alloc] init]; + content.title = titleString; + content.body = bodyString; + content.sound = [UNNotificationSound defaultSound]; + + NSString *identifier = + [NSString stringWithFormat:@"filecommander-%lld", + QDateTime::currentMSecsSinceEpoch()]; + UNNotificationRequest *request = + [UNNotificationRequest requestWithIdentifier:identifier + content:content + trigger:nil]; + [center addNotificationRequest:request + withCompletionHandler:nil]; +#if !__has_feature(objc_arc) + [content release]; +#endif + }]; + } +} + +} // namespace ttc diff --git a/src/ui/MainWindow.cpp b/src/ui/MainWindow.cpp index 3ef2bb7c..e6a4224e 100644 --- a/src/ui/MainWindow.cpp +++ b/src/ui/MainWindow.cpp @@ -159,16 +159,18 @@ #include "network/CurlWebDavProvider.h" #include "network/ConnectionStore.h" #include "network/SftpProvider.h" +#if FILECOMMANDER_HAS_LINUX_INTEGRATION || defined(Q_OS_MACOS) +#include "network/SmbProvider.h" +#endif #if defined(Q_OS_WIN) #include "network/WindowsSmbProvider.h" #endif #endif -#if FILECOMMANDER_HAS_LINUX_INTEGRATION || defined(Q_OS_WIN) +#if FILECOMMANDER_HAS_LINUX_INTEGRATION || defined(Q_OS_WIN) || defined(Q_OS_MACOS) #include "devices/RemovableDeviceMonitor.h" #endif -#if FILECOMMANDER_HAS_LINUX_INTEGRATION +#if FILECOMMANDER_HAS_LINUX_INTEGRATION || defined(Q_OS_MACOS) #include "network/GvfsMounter.h" -#include "network/SmbProvider.h" #endif #if FILECOMMANDER_HAS_LINUX_INTEGRATION || (defined(Q_OS_WIN) && FILECOMMANDER_HAS_NETWORK) #include "network/SmbHostBrowser.h" @@ -1458,7 +1460,7 @@ void MainWindow::setupFeatureBatch() { return; m_featureBatchStarted = true; -#if FILECOMMANDER_HAS_LINUX_INTEGRATION || defined(Q_OS_WIN) +#if FILECOMMANDER_HAS_LINUX_INTEGRATION || defined(Q_OS_WIN) || defined(Q_OS_MACOS) // Removable-device hot-plug: when a new USB stick / phone / drive appears and // the preference is on, mount it and open it in a fresh, activated tab. m_deviceMonitor = new RemovableDeviceMonitor(this); @@ -1475,7 +1477,7 @@ void MainWindow::setupFeatureBatch() { m_rightPanel->setTreeSources(m_deviceMonitor, m_connRegistry); #endif -#if FILECOMMANDER_HAS_LINUX_INTEGRATION || defined(Q_OS_WIN) +#if FILECOMMANDER_HAS_LINUX_INTEGRATION || defined(Q_OS_WIN) || defined(Q_OS_MACOS) connect(m_deviceMonitor, &RemovableDeviceMonitor::deviceAdded, this, [this](const RemovableDevice &dev) { if (!m_settings.autoOpenNewDevice() || !m_activePanel) @@ -2191,13 +2193,14 @@ SavedNativeProvider providerForSaved(const SavedConnection &c) { factory}; } case ConnectionProtocol::Smb: { -#if FILECOMMANDER_HAS_LINUX_INTEGRATION +#if FILECOMMANDER_HAS_LINUX_INTEGRATION || defined(Q_OS_MACOS) auto p = std::make_shared(); #elif defined(Q_OS_WIN) auto p = std::make_shared(); #else return {}; #endif +#if FILECOMMANDER_HAS_LINUX_INTEGRATION || defined(Q_OS_WIN) || defined(Q_OS_MACOS) auto factory = [p, c](const QString &u, const QString &pw) { return std::function([p, c, u, pw](QString *e) { return p->connectToHost(c.host, u, pw, QString(), /*anonymous=*/false, e); @@ -2208,6 +2211,9 @@ SavedNativeProvider providerForSaved(const SavedConnection &c) { return p->connectToHost(c.host, c.user, password, QString(), c.anonymous, e); }, factory}; +#else + return {}; +#endif } default: return {}; @@ -2381,7 +2387,7 @@ QVector MainWindow::computerEntries() { // a stale copy of it from another. QVector removable; QSet removableRoots; -#if FILECOMMANDER_HAS_LINUX_INTEGRATION || defined(Q_OS_WIN) +#if FILECOMMANDER_HAS_LINUX_INTEGRATION || defined(Q_OS_WIN) || defined(Q_OS_MACOS) if (m_deviceMonitor) { for (const RemovableDevice &device : m_deviceMonitor->devices()) { ComputerEntry entry; @@ -2444,7 +2450,7 @@ void MainWindow::showComputerView(FilePanel *panel) { if (!panel) return; -#if FILECOMMANDER_HAS_LINUX_INTEGRATION || defined(Q_OS_WIN) +#if FILECOMMANDER_HAS_LINUX_INTEGRATION || defined(Q_OS_WIN) || defined(Q_OS_MACOS) // Only once the window is up. During construction this would pull the // device monitor in ahead of the first paint, which the startup path exists // to avoid; setupFeatureBatch refreshes the view itself when it later runs. @@ -2486,7 +2492,7 @@ void MainWindow::openComputerEntry(FilePanel *panel, const ComputerEntry &entry) panel->navigateTo(entry.target, FilePanel::ParkedConnection::Drop); break; case ComputerEntry::Kind::RemovableDevice: { -#if FILECOMMANDER_HAS_LINUX_INTEGRATION || defined(Q_OS_WIN) +#if FILECOMMANDER_HAS_LINUX_INTEGRATION || defined(Q_OS_WIN) || defined(Q_OS_MACOS) if (!m_deviceMonitor) return; QString mountPoint; diff --git a/src/ui/dialogs/ConnectDialog.cpp b/src/ui/dialogs/ConnectDialog.cpp index 57d2ec0c..e9e95f5f 100644 --- a/src/ui/dialogs/ConnectDialog.cpp +++ b/src/ui/dialogs/ConnectDialog.cpp @@ -4,7 +4,7 @@ #include "network/CurlWebDavProvider.h" #include "network/GvfsMounter.h" #include "network/SftpProvider.h" -#if FILECOMMANDER_HAS_LINUX_INTEGRATION +#if FILECOMMANDER_HAS_LINUX_INTEGRATION || defined(Q_OS_MACOS) #include "network/SmbProvider.h" using NativeSmbProvider = SmbProvider; #elif defined(Q_OS_WIN) @@ -43,7 +43,7 @@ struct ProtocolChoice { const ProtocolChoice kProtocols[] = { {"SFTP (SSH)", GvfsMounter::Protocol::Sftp}, -#if FILECOMMANDER_HAS_LINUX_INTEGRATION || defined(Q_OS_WIN) +#if FILECOMMANDER_HAS_LINUX_INTEGRATION || defined(Q_OS_WIN) || defined(Q_OS_MACOS) {"SMB / Windows share", GvfsMounter::Protocol::Smb}, #endif {"WebDAV (HTTP)", GvfsMounter::Protocol::WebDav}, @@ -132,7 +132,7 @@ ConnectDialog::ConnectDialog(QWidget *parent) : FramelessDialog(parent) { auto *layout = new QVBoxLayout(this); layout->addWidget(savedBox); layout->addLayout(form); -#if FILECOMMANDER_HAS_LINUX_INTEGRATION || defined(Q_OS_WIN) +#if FILECOMMANDER_HAS_LINUX_INTEGRATION || defined(Q_OS_WIN) || defined(Q_OS_MACOS) const QString hintText = tr("SFTP, FTP, WebDAV and SMB all connect through a built-in client."); #else @@ -397,7 +397,7 @@ void ConnectDialog::accept() { } // SMB/CIFS (libsmbclient / SmbProvider). "/" lists the shares. -#if FILECOMMANDER_HAS_LINUX_INTEGRATION || defined(Q_OS_WIN) +#if FILECOMMANDER_HAS_LINUX_INTEGRATION || defined(Q_OS_WIN) || defined(Q_OS_MACOS) if (protocol == GvfsMounter::Protocol::Smb) { auto provider = std::make_shared(); m_remoteProvider = provider; diff --git a/tests/core/CMakeLists.txt b/tests/core/CMakeLists.txt index 942543a2..e1e4917e 100644 --- a/tests/core/CMakeLists.txt +++ b/tests/core/CMakeLists.txt @@ -71,6 +71,8 @@ if(WIN32) devices/test_WindowsRemovableStorage.cpp platform/test_TrashService.cpp ) +elseif(APPLE) + list(APPEND CORE_TEST_SOURCES platform/test_TrashService.cpp) endif() if(FILECOMMANDER_ENABLE_LINUX_INTEGRATION) list(APPEND CORE_TEST_SOURCES diff --git a/tests/core/platform/test_InstanceCoordinator.cpp b/tests/core/platform/test_InstanceCoordinator.cpp index c20ea0d2..03c61d93 100644 --- a/tests/core/platform/test_InstanceCoordinator.cpp +++ b/tests/core/platform/test_InstanceCoordinator.cpp @@ -15,7 +15,10 @@ TEST(InstanceCoordinatorTest, SecondLaunchForwardsArgumentsToPrimaryInstance) { QTemporaryDir temp; ASSERT_TRUE(temp.isValid()); - const QString serverName = QStringLiteral("FileCommander-test-") + + // macOS stores QLocalServer sockets below a long per-user temporary + // directory. Keep this unique name short enough for sockaddr_un's path + // limit on machines whose temp directory prefix is especially long. + const QString serverName = QStringLiteral("FC-") + QUuid::createUuid().toString(QUuid::WithoutBraces); const QStringList arguments{QStringLiteral("FileCommander"), temp.path()}; diff --git a/tests/core/platform/test_TerminalLauncher.cpp b/tests/core/platform/test_TerminalLauncher.cpp index 9d1c36c7..8ba8303d 100644 --- a/tests/core/platform/test_TerminalLauncher.cpp +++ b/tests/core/platform/test_TerminalLauncher.cpp @@ -93,6 +93,21 @@ TEST(TerminalLauncherTest, ConsoleHostsAreLaunchedWithNoArgumentsAtAll) { EXPECT_TRUE(candidate.arguments.isEmpty()); } } +#elif defined(Q_OS_MACOS) + +TEST(TerminalLauncherTest, MacOSUsesLaunchServicesForTerminalApplications) { + const QVector candidates = + fc::terminalCandidates(QStringLiteral("/tmp")); + ASSERT_EQ(candidates.size(), 2); + EXPECT_EQ(candidates.at(0).program, QStringLiteral("/usr/bin/open")); + EXPECT_EQ(candidates.at(0).arguments, + (QStringList{QStringLiteral("-a"), QStringLiteral("Terminal"), + QStringLiteral("/tmp")})); + EXPECT_EQ(candidates.at(1).arguments, + (QStringList{QStringLiteral("-a"), QStringLiteral("iTerm"), + QStringLiteral("/tmp")})); +} + #else // "Open Terminal Here" always opened deepin-terminal no matter what the user // had configured, because the list named terminals ahead of the Debian diff --git a/tests/ui/CMakeLists.txt b/tests/ui/CMakeLists.txt index 78a6edbc..ceee72ae 100644 --- a/tests/ui/CMakeLists.txt +++ b/tests/ui/CMakeLists.txt @@ -72,14 +72,12 @@ set(UI_TEST_SOURCES test_MainWindowPreviewSwap.cpp test_DeleteConfirmDialog.cpp test_MainWindowActions.cpp - test_UpdateUi.cpp test_WindowActivation.cpp test_FilePanelTheme.cpp test_TabMotion.cpp test_FileListViewLayout.cpp test_ChecksumDialog.cpp test_NotepadPanel.cpp - test_ExternalConnectDialog.cpp test_AccountDialog.cpp test_PendingSendQueue.cpp test_ShortcutsDialog.cpp @@ -98,6 +96,15 @@ set(UI_TEST_SOURCES ../../resources/resources.qrc ) +if(FILECOMMANDER_ENABLE_LINUX_INTEGRATION OR WIN32) + list(APPEND UI_TEST_SOURCES test_UpdateUi.cpp) +endif() + +if(FILECOMMANDER_ENABLE_LINUX_INTEGRATION OR + (WIN32 AND FILECOMMANDER_ENABLE_NETWORK)) + list(APPEND UI_TEST_SOURCES test_ExternalConnectDialog.cpp) +endif() + if(FILECOMMANDER_ENABLE_LINUX_INTEGRATION OR WIN32) list(APPEND UI_TEST_SOURCES test_SecureWipeConfirmationDialog.cpp) endif() diff --git a/tests/ui/test_ShellShortcuts.cpp b/tests/ui/test_ShellShortcuts.cpp index cd4ac82b..81ab4ace 100644 --- a/tests/ui/test_ShellShortcuts.cpp +++ b/tests/ui/test_ShellShortcuts.cpp @@ -72,6 +72,9 @@ TEST(ShellShortcutsTest, SupportedDestinationsMatchThePlatform) { #ifdef Q_OS_WIN EXPECT_TRUE(fc::ShellShortcuts::supports(Destination::Startup)); EXPECT_FALSE(fc::ShellShortcuts::supports(Destination::Applications)); +#elif defined(Q_OS_MACOS) + EXPECT_FALSE(fc::ShellShortcuts::supports(Destination::Startup)); + EXPECT_FALSE(fc::ShellShortcuts::supports(Destination::Applications)); #else EXPECT_TRUE(fc::ShellShortcuts::supports(Destination::Applications)); EXPECT_FALSE(fc::ShellShortcuts::supports(Destination::Startup)); @@ -80,6 +83,8 @@ TEST(ShellShortcutsTest, SupportedDestinationsMatchThePlatform) { const Destination absent = #ifdef Q_OS_WIN Destination::Applications; +#elif defined(Q_OS_MACOS) + Destination::Applications; #else Destination::Startup; #endif @@ -151,6 +156,54 @@ TEST(ShellShortcutsTest, TheStartupFolderResolvesAndIsNotTheDesktop) { EXPECT_TRUE(QFileInfo(startup).isDir()) << qPrintable(startup); EXPECT_NE(startup, desktop); } +#elif defined(Q_OS_MACOS) + +TEST(ShellShortcutsTest, MacOSOffersDesktopAliasesOnly) { + using Destination = fc::ShellShortcuts::Destination; + EXPECT_TRUE(fc::ShellShortcuts::isSupported()); + EXPECT_TRUE(fc::ShellShortcuts::supports(Destination::Desktop)); + EXPECT_FALSE(fc::ShellShortcuts::supports(Destination::Applications)); + EXPECT_FALSE(fc::ShellShortcuts::supports(Destination::Startup)); + EXPECT_TRUE(fc::ShellShortcuts::locationFor(Destination::Applications).isEmpty()); + EXPECT_TRUE(fc::ShellShortcuts::locationFor(Destination::Startup).isEmpty()); +} + +TEST(ShellShortcutsTest, MacOSRecognizesExecutableFilesAndAppBundles) { + QTemporaryDir work; + ASSERT_TRUE(work.isValid()); + + const QString executable = QDir(work.path()).filePath(QStringLiteral("tool")); + QFile file(executable); + ASSERT_TRUE(file.open(QIODevice::WriteOnly)); + file.write("#!/bin/sh\n"); + file.close(); + ASSERT_TRUE(QFile::setPermissions(executable, + QFileDevice::ReadOwner | QFileDevice::WriteOwner | + QFileDevice::ExeOwner)); + EXPECT_TRUE(fc::ShellShortcuts::isLaunchable(executable)); + + const QString app = QDir(work.path()).filePath(QStringLiteral("Probe.app")); + ASSERT_TRUE(QDir().mkpath(app)); + EXPECT_TRUE(fc::ShellShortcuts::isLaunchable(app)); + + const QString text = QDir(work.path()).filePath(QStringLiteral("notes.txt")); + QFile plain(text); + ASSERT_TRUE(plain.open(QIODevice::WriteOnly)); + plain.write("text"); + plain.close(); + EXPECT_FALSE(fc::ShellShortcuts::isLaunchable(text)); +} + +TEST(ShellShortcutsTest, MacOSRejectsMissingDesktopAliasTarget) { + QTemporaryDir work; + ASSERT_TRUE(work.isValid()); + const QString absent = QDir(work.path()).filePath(QStringLiteral("gone.app")); + const PlatformResult result = + fc::ShellShortcuts::create(absent, fc::ShellShortcuts::Destination::Desktop); + EXPECT_FALSE(result.ok); + EXPECT_EQ(result.code, PlatformError::NotFound); +} + #else // Linux namespace {